Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add enum discriminants #337

Merged
merged 18 commits into from
Sep 1, 2024
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
toolchain: ["1.77", "beta", "nightly"]
toolchain: ["1.77", "1.78"]
steps:
- name: Checkout
uses: actions/checkout@v4
Expand Down
12 changes: 12 additions & 0 deletions src/adapter/edges.rs
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,18 @@ pub(super) fn resolve_variant_edge<'a, V: AsVertex<Vertex<'a>> + 'a>(
})),
}
}),
"discriminant" => resolve_neighbors_with(contexts, move |vertex| {
let origin = vertex.origin;
let item = vertex.as_variant().expect("vertex was not a Variant");

if let Some(discriminant) = &item.discriminant {
Box::new(std::iter::once(
origin.make_discriminant_vertex(discriminant),
))
} else {
Box::new(std::iter::empty())
}
}),
_ => unreachable!("resolve_variant_edge {edge_name}"),
}
}
Expand Down
3 changes: 3 additions & 0 deletions src/adapter/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,9 @@ impl<'a> Adapter<'a> for RustdocAdapter<'a> {
properties::resolve_associated_constant_property(contexts, property_name)
}
"Constant" => properties::resolve_constant_property(contexts, property_name),
"Discriminant" => {
properties::resolve_discriminant_property(contexts, property_name)
}
_ => unreachable!("resolve_property {type_name} {property_name}"),
}
}
Expand Down
10 changes: 10 additions & 0 deletions src/adapter/origin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,4 +96,14 @@ impl Origin {
kind: abi.into(),
}
}

pub(super) fn make_discriminant_vertex<'a>(
&self,
discriminant: &'a rustdoc_types::Discriminant,
) -> Vertex<'a> {
Vertex {
origin: *self,
kind: discriminant.into(),
}
}
}
11 changes: 11 additions & 0 deletions src/adapter/properties.rs
Original file line number Diff line number Diff line change
Expand Up @@ -560,3 +560,14 @@ pub(crate) fn resolve_constant_property<'a, V: AsVertex<Vertex<'a>> + 'a>(
_ => unreachable!("Constant property {property_name}"),
}
}

pub(crate) fn resolve_discriminant_property<'a, V: AsVertex<Vertex<'a>> + 'a>(
contexts: ContextIterator<'a, V>,
property_name: &str,
) -> ContextOutcomeIterator<'a, V, FieldValue> {
match property_name {
"expr" => resolve_property_with(contexts, field_property!(as_discriminant, expr)),
"value" => resolve_property_with(contexts, field_property!(as_discriminant, value)),
_ => unreachable!("AssociatedConstant property {property_name}"),
}
}
84 changes: 84 additions & 0 deletions src/adapter/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1657,3 +1657,87 @@ fn unions() {

similar_asserts::assert_eq!(expected_results, results);
}

#[test]
fn enum_discriminants() {
let path = "./localdata/test_data/enum_discriminants/rustdoc.json";
let content = std::fs::read_to_string(path)
.with_context(|| format!("Could not load {path} file, did you forget to run ./scripts/regenerate_test_rustdocs.sh ?"))
.expect("failed to load rustdoc");

let crate_ = serde_json::from_str(&content).expect("failed to parse rustdoc");
let indexed_crate = IndexedCrate::new(&crate_);
let adapter = RustdocAdapter::new(&indexed_crate, None);

let query = r#"
{
Crate {
item {
... on Enum {
name @output
variant {
discriminant {
SuperSonicHub1 marked this conversation as resolved.
Show resolved Hide resolved
expr @output
value @output
}
}
}
}
}
}
"#;
let variables: BTreeMap<&str, &str> = btreemap! {};

let schema =
Schema::parse(include_str!("../rustdoc_schema.graphql")).expect("schema failed to parse");

#[derive(Debug, PartialOrd, Ord, PartialEq, Eq, serde::Deserialize)]
struct Output {
name: String,
expr: String,
value: String,
}

let mut results: Vec<Output> =
trustfall::execute_query(&schema, adapter.into(), query, variables.clone())
.expect("failed to run query")
.map(|row| row.try_into_struct().expect("shape mismatch"))
.collect();
results.sort_unstable();

similar_asserts::assert_eq!(
vec![
Output {
name: "A".into(),
expr: "1".into(),
value: "1".into(),
},
Output {
name: "A".into(),
expr: "99".into(),
value: "99".into(),
},
Output {
name: "A".into(),
expr: "{ _ }".into(),
value: "2".into(),
},
Output {
name: "Fieldful".into(),
expr: "9".into(),
value: "9".into(),
},
Output {
name: "FieldlessWithDiscrimants".into(),
expr: "10".into(),
value: "10".into(),
},
Output {
name: "FieldlessWithDiscrimants".into(),
expr: "20".into(),
value: "20".into(),
},
],
results
);
}
19 changes: 17 additions & 2 deletions src/adapter/vertex.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use std::rc::Rc;

use rustdoc_types::{
Abi, Constant, Crate, Enum, Function, Impl, Item, Module, Path, Span, Static, Struct, Trait,
Type, Union, Variant, VariantKind,
Abi, Constant, Crate, Discriminant, Enum, Function, Impl, Item, Module, Path, Span, Static,
Struct, Trait, Type, Union, Variant, VariantKind,
};
use trustfall::provider::Typename;

Expand Down Expand Up @@ -36,6 +36,7 @@ pub enum VertexKind<'a> {
ImplementedTrait(&'a Path, &'a Item),
FunctionParameter(&'a str),
FunctionAbi(&'a Abi),
Discriminant(&'a Discriminant),
}

impl<'a> Typename for Vertex<'a> {
Expand Down Expand Up @@ -77,6 +78,7 @@ impl<'a> Typename for Vertex<'a> {
},
VertexKind::FunctionParameter(..) => "FunctionParameter",
VertexKind::FunctionAbi(..) => "FunctionAbi",
VertexKind::Discriminant(..) => "Discriminant",
}
}
}
Expand Down Expand Up @@ -254,6 +256,13 @@ impl<'a> Vertex<'a> {
_ => None,
}
}

pub(super) fn as_discriminant(&self) -> Option<&'a rustdoc_types::Discriminant> {
match &self.kind {
VertexKind::Discriminant(discriminant) => Some(discriminant),
_ => None,
}
}
}

impl<'a> From<&'a Item> for VertexKind<'a> {
Expand All @@ -279,3 +288,9 @@ impl<'a> From<&'a Abi> for VertexKind<'a> {
Self::FunctionAbi(a)
}
}

impl<'a> From<&'a Discriminant> for VertexKind<'a> {
fn from(d: &'a Discriminant) -> Self {
Self::Discriminant(d)
}
}
26 changes: 26 additions & 0 deletions src/rustdoc_schema.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -429,6 +429,29 @@ interface Variant implements Item {

# own edges
field: [StructField!]

"""
The discriminant, if explicitly specified.
SuperSonicHub1 marked this conversation as resolved.
Show resolved Hide resolved
"""
discriminant: Discriminant
obi1kenobi marked this conversation as resolved.
Show resolved Hide resolved
}

"""
https://docs.rs/rustdoc-types/0.28.0/rustdoc_types/struct.Discriminant.html
https://doc.rust-lang.org/reference/items/enumerations.html
"""
type Discriminant {
"""
The expression that produced the discriminant. Preserves the original formatting seen in source code (e.g. suffixes, hexadecimal, and underscores).

In some cases, when the value is to complex, this may be "`{ _ }`".
SuperSonicHub1 marked this conversation as resolved.
Show resolved Hide resolved
"""
expr: String!

"""
The numerical value of the discriminant. Stored as a string. Ranges from `i128::MIN` to `u128::MAX`.
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor phrasing tweak suggestion:

Suggested change
The numerical value of the discriminant. Stored as a string. Ranges from `i128::MIN` to `u128::MAX`.
The numerical value of the discriminant, represented as a string.
May range from `i128::MIN` to `u128::MAX`.

"""
value: String!
}

"""
Expand Down Expand Up @@ -483,6 +506,7 @@ type PlainVariant implements Item & Variant {

# edges from Variant
field: [StructField!]
discriminant: Discriminant
SuperSonicHub1 marked this conversation as resolved.
Show resolved Hide resolved
}

"""
Expand Down Expand Up @@ -537,6 +561,7 @@ type TupleVariant implements Item & Variant {

# edges from Variant
field: [StructField!]
discriminant: Discriminant
}

"""
Expand Down Expand Up @@ -591,6 +616,7 @@ type StructVariant implements Item & Variant {

# edges from Variant
field: [StructField!]
discriminant: Discriminant
}

"""
Expand Down
9 changes: 9 additions & 0 deletions test_crates/enum_discriminants/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
[package]
publish = false
name = "enum_discriminants"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
29 changes: 29 additions & 0 deletions test_crates/enum_discriminants/src/lib.rs
SuperSonicHub1 marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/// Some examples from <https://doc.rust-lang.org/reference/items/enumerations.html#implicit-discriminants>

#[repr(C)]
pub enum A {
Zero,
One = 1,
Two = 1 + 1,
Three,
Four = 99,
Five
}
SuperSonicHub1 marked this conversation as resolved.
Show resolved Hide resolved

#[repr(u8)]
pub enum FieldlessWithDiscrimants {
First = 10,
Tuple(),
Second = 20,
Struct{},
Unit,
}

#[repr(i64)]
pub enum Fieldful {
Unit,
Tuple(bool),
Struct{a: bool},
Unit2 = 9
}