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 no_unused_variables and mark missing defer ones #1

Merged
merged 3 commits into from
May 22, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
8 changes: 2 additions & 6 deletions benches/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,19 +41,15 @@ fn graphql_ast_print_graphql_query_rs(bench: &mut Bencher) {
bench.iter(|| ast.print());
}



fn graphql_ast_print_gql_parser(bench: &mut Bencher) {
use graphql_parser::query::parse_query;
let ast = parse_query::<&str>(QUERY).ok().unwrap();
bench.iter(|| {
ast.to_string()
});
bench.iter(|| ast.to_string());
}

fn graphql_ast_print_apollo_parser(bench: &mut Bencher) {
use apollo_parser::Parser;
use apollo_parser::cst::CstNode;
use apollo_parser::Parser;
let parser = Parser::new(QUERY);
let cst = parser.parse();
let doc = cst.document();
Expand Down
2 changes: 1 addition & 1 deletion src/ast/ast.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
pub use super::ast_conversion::*;
use crate::error::{Error, ErrorType, Result};
use bumpalo::collections::CollectIn;
use hashbrown::{HashMap, hash_map::DefaultHashBuilder};
use hashbrown::{hash_map::DefaultHashBuilder, HashMap};

/// A context for a GraphQL document which holds an arena allocator.
///
Expand Down
4 changes: 2 additions & 2 deletions src/ast/ast_conversion.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// #![allow(clippy::needless_update)]
use bumpalo::collections::{vec::IntoIter, Vec};
use super::ast::*;
use bumpalo::collections::{vec::IntoIter, Vec};

// TODO: from_iter_in could be a good helper here as well

Expand Down Expand Up @@ -75,7 +75,7 @@ impl<'a> DefaultIn<'a> for Document<'a> {
fn default_in(arena: &'a bumpalo::Bump) -> Self {
Document {
definitions: Vec::new_in(&arena),
size_hint: 0
size_hint: 0,
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/ast/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ mod parser;
mod printer;

pub use ast::*;
pub use ast_kind::ASTKind;
pub use ast_conversion::DefaultIn;
pub use ast_kind::ASTKind;
pub use parser::ParseNode;
pub use printer::PrintNode;
4 changes: 2 additions & 2 deletions src/json/values.rs
Original file line number Diff line number Diff line change
Expand Up @@ -287,7 +287,7 @@ mod tests {
name: "Int",
}))),
default_value: Value::Null,
directives: Directives::default_in(&ctx.arena)
directives: Directives::default_in(&ctx.arena),
}];

let var_defs = VariableDefinitions {
Expand All @@ -313,7 +313,7 @@ mod tests {
name: "orderByInput",
})),
default_value: Value::Null,
directives: Directives::default_in(&ctx.arena)
directives: Directives::default_in(&ctx.arena),
}];

let var_defs = VariableDefinitions {
Expand Down
12 changes: 11 additions & 1 deletion src/validate/rules/mod.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
use crate::visit::ComposedVisitor;

// Missing schemaless rules
// https://github.com/graphql/graphql-js/blob/main/src/validation/rules/DeferStreamDirectiveLabelRule.ts
// https://github.com/graphql/graphql-js/blob/main/src/validation/rules/DeferStreamDirectiveOnValidOperationsRule.ts
mod known_fragment_names;
mod lone_anonymous_operation;
mod no_fragment_cycles;
mod no_undefined_variables;
mod no_unused_fragments;
mod no_unused_variables;
mod unique_argument_names;
mod unique_fragment_names;
mod unique_operation_names;
Expand All @@ -16,6 +20,7 @@ pub use lone_anonymous_operation::*;
pub use no_fragment_cycles::*;
pub use no_undefined_variables::*;
pub use no_unused_fragments::*;
pub use no_unused_variables::*;
pub use unique_argument_names::*;
pub use unique_fragment_names::*;
pub use unique_operation_names::*;
Expand Down Expand Up @@ -51,7 +56,12 @@ pub type DefaultRules<'a> = ComposedVisitor<
'a,
ValidationContext<'a>,
NoFragmentCycles<'a>,
NoUndefinedVariables<'a>,
ComposedVisitor<
'a,
ValidationContext<'a>,
NoUndefinedVariables<'a>,
NoUnusedVariables<'a>,
>,
>,
>,
>,
Expand Down
94 changes: 94 additions & 0 deletions src/validate/rules/no_unused_variables.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
use bumpalo::collections::Vec;

use super::super::{ValidationContext, ValidationRule};
use crate::{ast::*, visit::*};

/// Validate that a document uses all the variables it defines at least once.
///
/// See [`ValidationRule`]
/// [Reference](https://spec.graphql.org/draft/#sec-All-Variables-Used)
pub struct NoUnusedVariables<'a> {
variables: Vec<'a, &'a str>,
used_variables: Vec<'a, &'a str>,
}

impl<'a> DefaultIn<'a> for NoUnusedVariables<'a> {
fn default_in(arena: &'a bumpalo::Bump) -> Self {
Self {
variables: Vec::new_in(arena),
used_variables: Vec::new_in(arena),
}
}
}

impl<'a> ValidationRule<'a> for NoUnusedVariables<'a> {}

impl<'a> Visitor<'a, ValidationContext<'a>> for NoUnusedVariables<'a> {
fn enter_operation(
&mut self,
_ctx: &mut ValidationContext<'a>,
operation: &'a OperationDefinition<'a>,
_info: &VisitInfo,
) -> VisitFlow {
operation
.variable_definitions
.children
.iter()
.for_each(|def| {
self.variables.push(def.variable.name);
});
VisitFlow::Next
}

fn enter_field(
&mut self,
_ctx: &mut ValidationContext<'a>,
field: &'a Field<'a>,
_info: &VisitInfo,
) -> VisitFlow {
field.arguments.children.iter().for_each(|arg| {
if let Value::Variable(var) = arg.value {
self.used_variables.push(var.name);
}
});
VisitFlow::Next
}

fn leave_document(
&mut self,
ctx: &mut ValidationContext<'a>,
_document: &'a Document<'a>,
_info: &VisitInfo,
) -> VisitFlow {
self.variables.iter().for_each(|defined_variable| {
if !self.used_variables.contains(defined_variable) {
ctx.add_error("All defined variables must be at least used once");
}
});
VisitFlow::Next
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn used_all_variables() {
let ctx = ASTContext::new();
let document =
Document::parse(&ctx, "query ($x: Int!) { todos(from: $x) { id } }").unwrap();
NoUnusedVariables::validate(&ctx, document).unwrap();
}

#[test]
fn has_unused_variable() {
let ctx = ASTContext::new();
let document = Document::parse(
&ctx,
"query ($x: Int!, $unused: String!) { todos(from: $x) { id } }",
)
.unwrap();
NoUnusedVariables::validate(&ctx, document).unwrap_err();
}
}
1 change: 1 addition & 0 deletions src/validate/rules/validate.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@

1 change: 0 additions & 1 deletion src/validate/validate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ where
#[inline]
fn default_in(arena: &'a bumpalo::Bump) -> Self {
ComposedVisitor::new(A::default_in(arena), B::default_in(arena))

}
}

Expand Down
24 changes: 13 additions & 11 deletions src/visit/folder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1030,14 +1030,14 @@ mod tests {
if selection_set.is_empty() {
return Ok(selection_set);
}

let has_typename = selection_set.selections.iter().any(|selection| {
selection
.field()
.map(|field| field.name == "__typename" && field.alias.is_none())
.unwrap_or(false)
});

if !has_typename {
let typename_field = Selection::Field(Field {
alias: None,
Expand All @@ -1046,13 +1046,16 @@ mod tests {
directives: Directives::default_in(&ctx.arena),
selection_set: SelectionSet::default_in(&ctx.arena),
});

let new_selections = selection_set
.into_iter()
.chain(iter::once(typename_field))
.collect_in::<bumpalo::collections::Vec<Selection>>(&ctx.arena);

Ok(SelectionSet { selections: new_selections })

let new_selections =
selection_set
.into_iter()
.chain(iter::once(typename_field))
.collect_in::<bumpalo::collections::Vec<Selection>>(&ctx.arena);

Ok(SelectionSet {
selections: new_selections,
})
} else {
Ok(selection_set)
}
Expand All @@ -1066,8 +1069,7 @@ mod tests {
let ast = Document::parse(&ctx, query).unwrap();

let mut folder = AddTypenames {};
let new_ast = ast
.fold_operation(&ctx, None, &mut folder);
let new_ast = ast.fold_operation(&ctx, None, &mut folder);
assert_eq!(
new_ast.unwrap().print(),
"{\n todo {\n id\n author {\n id\n __typename\n }\n __typename\n }\n __typename\n}"
Expand Down
Loading