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

Escape stubgen names #406

Merged
merged 18 commits into from
Jul 27, 2023
Merged
Show file tree
Hide file tree
Changes from 8 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
9 changes: 7 additions & 2 deletions trustfall_stubgen/src/edges_creator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ use maplit::btreemap;
use quote::quote;
use trustfall::{Schema, SchemaAdapter, TryIntoStruct};

use crate::util::escaped_rust_name;
u9g marked this conversation as resolved.
Show resolved Hide resolved

use super::{
root::RustFile,
util::{
Expand Down Expand Up @@ -77,7 +79,10 @@ fn make_type_edge_resolver(
edges: Vec<(String, Vec<(String, String)>)>,
) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) {
let lower_type_name = to_lower_snake_case(type_name);
let mod_name = syn::Ident::new(&lower_type_name, proc_macro2::Span::call_site());
let mod_name = syn::Ident::new(
&escaped_rust_name(lower_type_name.clone()),
proc_macro2::Span::call_site(),
);

let mut arms = proc_macro2::TokenStream::new();
let mut edge_resolvers = proc_macro2::TokenStream::new();
Expand Down Expand Up @@ -135,7 +140,7 @@ fn make_edge_resolver_and_call(
},
);

let resolver_fn_name = to_lower_snake_case(edge_name);
let resolver_fn_name = escaped_rust_name(to_lower_snake_case(edge_name));
let resolver_fn_ident = syn::Ident::new(&resolver_fn_name, proc_macro2::Span::call_site());
let conversion_fn_name = format!("as_{}", to_lower_snake_case(type_name));
let conversion_fn_ident = syn::Ident::new(&conversion_fn_name, proc_macro2::Span::call_site());
Expand Down
7 changes: 5 additions & 2 deletions trustfall_stubgen/src/entrypoints_creator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@ use maplit::btreemap;
use quote::quote;
use trustfall::{Schema, SchemaAdapter, TryIntoStruct};

use crate::edges_creator::{prepare_call_parameters, FnCall};
use crate::{
edges_creator::{prepare_call_parameters, FnCall},
util::escaped_rust_name,
};

use super::{
root::RustFile,
Expand Down Expand Up @@ -70,7 +73,7 @@ fn make_entrypoint_fn(
},
);

let entrypoint_fn_name = to_lower_snake_case(entrypoint);
let entrypoint_fn_name = escaped_rust_name(to_lower_snake_case(entrypoint));
let ident = syn::Ident::new(&entrypoint_fn_name, proc_macro2::Span::call_site());
let todo_msg =
format!("implement resolving starting vertices for entrypoint edge '{entrypoint}'");
Expand Down
104 changes: 102 additions & 2 deletions trustfall_stubgen/src/root.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use std::{
collections::{BTreeMap, BTreeSet},
collections::{BTreeMap, BTreeSet, HashMap},
io::Write,
path::Path,
sync::{Arc, OnceLock},
Expand All @@ -10,7 +10,7 @@ use quote::quote;
use regex::Regex;
use trustfall::{Schema, SchemaAdapter, TryIntoStruct};

use crate::util::parse_import;
use crate::util::{escaped_rust_name, parse_import, to_lower_snake_case};

use super::{
adapter_creator::make_adapter_file, edges_creator::make_edges_file,
Expand Down Expand Up @@ -52,6 +52,9 @@ pub fn generate_rust_stub(schema: &str, target: &Path) -> anyhow::Result<()> {

let mut entrypoint_match_arms = proc_macro2::TokenStream::new();

ensure_no_vertex_name_keyword_conflicts(&querying_schema, schema_adapter.clone());
ensure_no_edge_name_keyword_conflicts(&querying_schema, schema_adapter.clone());

make_vertex_file(&querying_schema, schema_adapter.clone(), &mut stub.vertex);
make_entrypoints_file(
&querying_schema,
Expand Down Expand Up @@ -400,3 +403,100 @@ fn make_vertex_file(

vertex_file.top_level_items.push(vertex);
}

fn ensure_no_vertex_name_keyword_conflicts(
querying_schema: &Schema,
adapter: Arc<SchemaAdapter<'_>>,
) {
let query = r#"
{
VertexType {
name @output
}
}"#;
let variables: BTreeMap<String, String> = Default::default();

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

let mut rows: Vec<_> = trustfall::execute_query(querying_schema, adapter, query, variables)
.expect("invalid query")
.map(|x| x.try_into_struct::<ResultRow>().expect("invalid conversion"))
.collect();
rows.sort_unstable();

let mut uniq: HashMap<String, String> = HashMap::new();

for row in rows {
let name = row.name.clone();
let converted = escaped_rust_name(to_lower_snake_case(&name));
let v = uniq.insert(converted, name);
if let Some(v) = v {
panic!(
"cannot generate adapter for a schema containing both '{}' and '{}' vertices, consider renaming one of them",
v, &row.name
);
}
}
}

fn ensure_no_edge_name_keyword_conflicts(
Copy link
Owner

Choose a reason for hiding this comment

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

This function can probably use a better name, more in line with the panic message below

Copy link
Contributor Author

Choose a reason for hiding this comment

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

querying_schema: &Schema,
adapter: Arc<SchemaAdapter<'_>>,
) {
let query = r#"
{
VertexType {
name @output
edge_: edge @fold {
names: name @output
}
property_: property @fold {
names: name @output
}
}
}"#;
let variables: BTreeMap<String, String> = Default::default();

#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, serde::Deserialize)]
struct ResultRow {
name: String,
edge_names: Vec<String>,
property_names: Vec<String>,
}

let mut rows: Vec<_> = trustfall::execute_query(querying_schema, adapter, query, variables)
.expect("invalid query")
.map(|x| x.try_into_struct::<ResultRow>().expect("invalid conversion"))
.collect();
rows.sort_unstable();

for row in &rows {
let mut uniq: HashMap<String, String> = HashMap::new();

for edge_name in &row.edge_names {
let edge_name_for_map = edge_name.clone();
let converted = escaped_rust_name(to_lower_snake_case(&edge_name_for_map));
let v = uniq.insert(converted, edge_name_for_map);
if let Some(v) = v {
panic!(
"cannot generate adapter for a schema containing both '{}' and '{}' as field names on vertex '{}', consider renaming one of them",
v, &edge_name, &row.name
);
}
}
for property_name in &row.property_names {
let property_name_for_map = property_name.clone();
let converted = escaped_rust_name(to_lower_snake_case(&property_name_for_map));
let v = uniq.insert(converted, property_name_for_map);
if let Some(v) = v {
panic!(
"cannot generate adapter for a schema containing both '{}' and '{}' as field names on vertex '{}', consider renaming one of them",
v, &property_name, &row.name
);
}
}
u9g marked this conversation as resolved.
Show resolved Hide resolved
}
}
37 changes: 37 additions & 0 deletions trustfall_stubgen/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,3 +153,40 @@ fn test_schema(name: &str) {
fn test_hackernews_schema() {
test_schema("hackernews")
}

#[test]
fn test_use_reserved_rust_names_in_schema() {
test_schema("use_reserved_rust_names_in_schema");
}

#[test]
#[should_panic(
expected = "cannot generate adapter for a schema containing both 'Type' and 'Type_' vertices, consider renaming one of them"
)]
fn use_type_and_typeunderscore_edge_names() {
test_schema("use_type_and_typeunderscore_edge_names");
}

#[test]
#[should_panic(
expected = "cannot generate adapter for a schema containing both 'Type_' and 'Type' as field names on vertex 'Type', consider renaming one of them"
)]
fn vertextype_with_type_and_typeunderscore_edge_and_property() {
test_schema("vertextype_with_type_and_typeunderscore_edge_and_property");
}

#[test]
#[should_panic(
expected = "cannot generate adapter for a schema containing both 'Type' and 'Type_' as field names on vertex 'Type', consider renaming one of them"
)]
fn vertextype_with_type_and_typeunderscore_edges() {
test_schema("vertextype_with_type_and_typeunderscore_edges");
}

#[test]
#[should_panic(
expected = "cannot generate adapter for a schema containing both 'Type' and 'Type_' as field names on vertex 'Type', consider renaming one of them"
)]
fn vertextype_with_type_and_typeunderscore_properties() {
test_schema("vertextype_with_type_and_typeunderscore_properties");
}
12 changes: 12 additions & 0 deletions trustfall_stubgen/src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,3 +138,15 @@ pub(crate) fn field_value_to_rust_type(
#base.#suffix
}
}

pub fn escaped_rust_name(name: String) -> String {
u9g marked this conversation as resolved.
Show resolved Hide resolved
// https://doc.rust-lang.org/reference/keywords.html
match name.as_str() {
"as" | "break" | "const" | "continue" | "crate" | "else" | "enum" | "extern" | "false"
| "fn" | "for" | "if" | "impl" | "in" | "let" | "loop" | "match" | "mod" | "move"
| "mut" | "pub" | "ref" | "return" | "self" | "Self" | "static" | "struct" | "super"
| "trait" | "true" | "type" | "unsafe" | "use" | "where" | "while" | "async" | "await"
| "dyn" | "try" | "macro_rules" | "union" | "'static" => name + "_",
_ => name,
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
use std::sync::{Arc, OnceLock};

use trustfall::{FieldValue, Schema, provider::{ContextIterator, ContextOutcomeIterator, EdgeParameters, ResolveEdgeInfo, ResolveInfo, VertexIterator, resolve_coercion_using_schema}};

use super::vertex::Vertex;

static SCHEMA: OnceLock<Schema> = OnceLock::new();

#[non_exhaustive]
#[derive(Debug)]
pub struct Adapter {}

impl Adapter {
pub const SCHEMA_TEXT: &'static str = include_str!("./schema.graphql");

pub fn schema() -> &'static Schema {
SCHEMA
.get_or_init(|| {
Schema::parse(Self::SCHEMA_TEXT).expect("not a valid schema")
})
}

pub fn new() -> Self {
Self {}
}
}

impl<'a> trustfall::provider::Adapter<'a> for Adapter {
type Vertex = Vertex;

fn resolve_starting_vertices(
&self,
edge_name: &Arc<str>,
parameters: &EdgeParameters,
resolve_info: &ResolveInfo,
) -> VertexIterator<'a, Self::Vertex> {
match edge_name.as_ref() {
"type" => super::entrypoints::type_(resolve_info),
"type2" => super::entrypoints::type2(resolve_info),
_ => {
unreachable!(
"attempted to resolve starting vertices for unexpected edge name: {edge_name}"
)
}
}
}

fn resolve_property(
&self,
contexts: ContextIterator<'a, Self::Vertex>,
type_name: &Arc<str>,
property_name: &Arc<str>,
resolve_info: &ResolveInfo,
) -> ContextOutcomeIterator<'a, Self::Vertex, FieldValue> {
match type_name.as_ref() {
"Type2" => {
super::properties::resolve_type2_property(
contexts,
property_name.as_ref(),
resolve_info,
)
}
_ => {
unreachable!(
"attempted to read property '{property_name}' on unexpected type: {type_name}"
)
}
}
}

fn resolve_neighbors(
&self,
contexts: ContextIterator<'a, Self::Vertex>,
type_name: &Arc<str>,
edge_name: &Arc<str>,
parameters: &EdgeParameters,
resolve_info: &ResolveEdgeInfo,
) -> ContextOutcomeIterator<'a, Self::Vertex, VertexIterator<'a, Self::Vertex>> {
match type_name.as_ref() {
"Type" => {
super::edges::resolve_type_edge(
contexts,
edge_name.as_ref(),
parameters,
resolve_info,
)
}
_ => {
unreachable!(
"attempted to resolve edge '{edge_name}' on unexpected type: {type_name}"
)
}
}
}

fn resolve_coercion(
&self,
contexts: ContextIterator<'a, Self::Vertex>,
_type_name: &Arc<str>,
coerce_to_type: &Arc<str>,
_resolve_info: &ResolveInfo,
) -> ContextOutcomeIterator<'a, Self::Vertex, bool> {
resolve_coercion_using_schema(contexts, Self::schema(), coerce_to_type.as_ref())
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
use trustfall::provider::{ContextIterator, ContextOutcomeIterator, EdgeParameters, ResolveEdgeInfo, VertexIterator};

use super::vertex::Vertex;

pub(super) fn resolve_type_edge<'a>(
contexts: ContextIterator<'a, Vertex>,
edge_name: &str,
parameters: &EdgeParameters,
resolve_info: &ResolveEdgeInfo,
) -> ContextOutcomeIterator<'a, Vertex, VertexIterator<'a, Vertex>> {
match edge_name {
"type" => type_::type_(contexts, resolve_info),
_ => {
unreachable!(
"attempted to resolve unexpected edge '{edge_name}' on type 'Type'"
)
}
}
}

mod type_ {
use trustfall::provider::{
resolve_neighbors_with, ContextIterator, ContextOutcomeIterator, ResolveEdgeInfo,
VertexIterator,
};

use super::super::vertex::Vertex;

pub(super) fn type_<'a>(
contexts: ContextIterator<'a, Vertex>,
_resolve_info: &ResolveEdgeInfo,
) -> ContextOutcomeIterator<'a, Vertex, VertexIterator<'a, Vertex>> {
resolve_neighbors_with(
contexts,
|vertex| {
let vertex = vertex
.as_type()
.expect("conversion failed, vertex was not a Type");
todo!("get neighbors along edge 'type' for type 'Type'")
},
)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
use trustfall::provider::{ResolveInfo, VertexIterator};

use super::vertex::Vertex;

pub(super) fn type_<'a>(_resolve_info: &ResolveInfo) -> VertexIterator<'a, Vertex> {
todo!("implement resolving starting vertices for entrypoint edge 'type'")
}

pub(super) fn type2<'a>(_resolve_info: &ResolveInfo) -> VertexIterator<'a, Vertex> {
todo!("implement resolving starting vertices for entrypoint edge 'type2'")
}
Loading