From 5e46fef0d7746a62cf245ea5e91010e600943800 Mon Sep 17 00:00:00 2001 From: Amaan Qureshi Date: Sat, 7 Sep 2024 20:13:58 -0400 Subject: [PATCH] chore: clippy lints --- cli/src/fuzz/edits.rs | 1 + cli/src/fuzz/mod.rs | 30 ++++++------- cli/src/fuzz/random.rs | 1 + cli/src/fuzz/scope_sequence.rs | 1 + cli/src/generate/build_tables/item.rs | 2 +- .../generate/build_tables/item_set_builder.rs | 2 +- cli/src/generate/mod.rs | 2 +- cli/src/generate/node_types.rs | 17 ++++---- .../prepare_grammar/extract_tokens.rs | 6 +-- .../prepare_grammar/flatten_grammar.rs | 2 +- cli/src/generate/prepare_grammar/mod.rs | 42 +++++++++---------- cli/src/generate/render.rs | 4 +- cli/src/generate/rules.rs | 4 +- cli/src/query_testing.rs | 7 +++- cli/src/test.rs | 5 +-- lib/binding_rust/lib.rs | 3 +- lib/language/language.rs | 7 ++-- 17 files changed, 72 insertions(+), 64 deletions(-) diff --git a/cli/src/fuzz/edits.rs b/cli/src/fuzz/edits.rs index 788eef5b..ef862d8e 100644 --- a/cli/src/fuzz/edits.rs +++ b/cli/src/fuzz/edits.rs @@ -7,6 +7,7 @@ pub struct Edit { pub inserted_text: Vec, } +#[must_use] pub fn invert_edit(input: &[u8], edit: &Edit) -> Edit { let position = edit.position; let removed_content = &input[position..(position + edit.deleted_length)]; diff --git a/cli/src/fuzz/mod.rs b/cli/src/fuzz/mod.rs index 14f50c72..0fdde6e9 100644 --- a/cli/src/fuzz/mod.rs +++ b/cli/src/fuzz/mod.rs @@ -65,20 +65,6 @@ pub fn fuzz_language_corpus( grammar_dir: &Path, options: &mut FuzzOptions, ) { - let subdir = options.subdir.take().unwrap_or_default(); - - let corpus_dir = grammar_dir.join(subdir).join("test").join("corpus"); - - if !corpus_dir.exists() || !corpus_dir.is_dir() { - eprintln!("No corpus directory found, ensure that you have a `test/corpus` directory in your grammar directory with at least one test file."); - return; - } - - if std::fs::read_dir(&corpus_dir).unwrap().count() == 0 { - eprintln!("No corpus files found in `test/corpus`, ensure that you have at least one test file in your corpus directory."); - return; - } - fn retain(entry: &mut TestEntry, language_name: &str) -> bool { match entry { TestEntry::Example { attributes, .. } => { @@ -97,6 +83,20 @@ pub fn fuzz_language_corpus( } } + let subdir = options.subdir.take().unwrap_or_default(); + + let corpus_dir = grammar_dir.join(subdir).join("test").join("corpus"); + + if !corpus_dir.exists() || !corpus_dir.is_dir() { + eprintln!("No corpus directory found, ensure that you have a `test/corpus` directory in your grammar directory with at least one test file."); + return; + } + + if std::fs::read_dir(&corpus_dir).unwrap().count() == 0 { + eprintln!("No corpus files found in `test/corpus`, ensure that you have at least one test file in your corpus directory."); + return; + } + let mut main_tests = parse_tests(&corpus_dir).unwrap(); match main_tests { TestEntry::Group { @@ -104,7 +104,7 @@ pub fn fuzz_language_corpus( } => { children.retain_mut(|child| retain(child, language_name)); } - _ => unreachable!(), + TestEntry::Example { .. } => unreachable!(), } let tests = flatten_tests(main_tests, options.filter.as_ref()); diff --git a/cli/src/fuzz/random.rs b/cli/src/fuzz/random.rs index a4069b32..8a8410f4 100644 --- a/cli/src/fuzz/random.rs +++ b/cli/src/fuzz/random.rs @@ -10,6 +10,7 @@ const OPERATORS: &[char] = &[ pub struct Rand(StdRng); impl Rand { + #[must_use] pub fn new(seed: usize) -> Self { Self(StdRng::seed_from_u64(seed as u64)) } diff --git a/cli/src/fuzz/scope_sequence.rs b/cli/src/fuzz/scope_sequence.rs index 436455d4..68647015 100644 --- a/cli/src/fuzz/scope_sequence.rs +++ b/cli/src/fuzz/scope_sequence.rs @@ -6,6 +6,7 @@ pub struct ScopeSequence(Vec); type ScopeStack = Vec<&'static str>; impl ScopeSequence { + #[must_use] pub fn new(tree: &Tree) -> Self { let mut result = Self(Vec::new()); let mut scope_stack = Vec::new(); diff --git a/cli/src/generate/build_tables/item.rs b/cli/src/generate/build_tables/item.rs index da19c4ba..cfc72540 100644 --- a/cli/src/generate/build_tables/item.rs +++ b/cli/src/generate/build_tables/item.rs @@ -144,7 +144,7 @@ impl<'a> ParseItem<'a> { /// Create an item identical to this one, but with a different production. /// This is used when dynamically "inlining" certain symbols in a production. - pub const fn substitute_production(&self, production: &'a Production) -> ParseItem<'a> { + pub const fn substitute_production(&self, production: &'a Production) -> Self { let mut result = *self; result.production = production; result diff --git a/cli/src/generate/build_tables/item_set_builder.rs b/cli/src/generate/build_tables/item_set_builder.rs index ff0323c5..16305bd3 100644 --- a/cli/src/generate/build_tables/item_set_builder.rs +++ b/cli/src/generate/build_tables/item_set_builder.rs @@ -237,7 +237,7 @@ impl<'a> ParseItemSetBuilder<'a> { result } - pub fn transitive_closure(&mut self, item_set: &ParseItemSet<'a>) -> ParseItemSet<'a> { + pub fn transitive_closure(&self, item_set: &ParseItemSet<'a>) -> ParseItemSet<'a> { let mut result = ParseItemSet::default(); for (item, lookaheads) in &item_set.entries { if let Some(productions) = self diff --git a/cli/src/generate/mod.rs b/cli/src/generate/mod.rs index 0ce63d1b..dc392634 100644 --- a/cli/src/generate/mod.rs +++ b/cli/src/generate/mod.rs @@ -130,7 +130,7 @@ pub fn generate_parser_for_grammar(grammar_json: &str) -> Result<(String, String let input_grammar = parse_grammar(&grammar_json)?; let parser = generate_parser_for_grammar_with_opts(&input_grammar, tree_sitter::LANGUAGE_VERSION, None)?; - Ok((input_grammar.name.clone(), parser.c_code)) + Ok((input_grammar.name, parser.c_code)) } fn generate_parser_for_grammar_with_opts( diff --git a/cli/src/generate/node_types.rs b/cli/src/generate/node_types.rs index 25353e8c..392e87ec 100644 --- a/cli/src/generate/node_types.rs +++ b/cli/src/generate/node_types.rs @@ -628,13 +628,16 @@ pub fn generate_node_types_json( for (name, kind) in regular_tokens.chain(external_tokens) { match kind { VariableType::Named => { - let node_type_json = node_types_json.entry(name.clone()).or_insert(NodeInfoJSON { - kind: name.clone(), - named: true, - fields: None, - children: None, - subtypes: None, - }); + let node_type_json = + node_types_json + .entry(name.clone()) + .or_insert_with(|| NodeInfoJSON { + kind: name.clone(), + named: true, + fields: None, + children: None, + subtypes: None, + }); if let Some(children) = &mut node_type_json.children { children.required = false; } diff --git a/cli/src/generate/prepare_grammar/extract_tokens.rs b/cli/src/generate/prepare_grammar/extract_tokens.rs index 34d99dec..80a0d712 100644 --- a/cli/src/generate/prepare_grammar/extract_tokens.rs +++ b/cli/src/generate/prepare_grammar/extract_tokens.rs @@ -28,11 +28,7 @@ pub(super) fn extract_tokens( let mut lexical_variables = Vec::with_capacity(extractor.extracted_variables.len()); for variable in extractor.extracted_variables { - lexical_variables.push(Variable { - name: variable.name, - kind: variable.kind, - rule: variable.rule, - }); + lexical_variables.push(variable); } // If a variable's entire rule was extracted as a token and that token didn't diff --git a/cli/src/generate/prepare_grammar/flatten_grammar.rs b/cli/src/generate/prepare_grammar/flatten_grammar.rs index 765ab3b0..7006a3cc 100644 --- a/cli/src/generate/prepare_grammar/flatten_grammar.rs +++ b/cli/src/generate/prepare_grammar/flatten_grammar.rs @@ -15,7 +15,7 @@ struct RuleFlattener { } impl RuleFlattener { - fn new() -> Self { + const fn new() -> Self { Self { production: Production { steps: Vec::new(), diff --git a/cli/src/generate/prepare_grammar/mod.rs b/cli/src/generate/prepare_grammar/mod.rs index 7e4800c1..1cb4ef40 100644 --- a/cli/src/generate/prepare_grammar/mod.rs +++ b/cli/src/generate/prepare_grammar/mod.rs @@ -90,6 +90,27 @@ pub fn prepare_grammar( /// within the `precedences` lists, and also that there are no conflicting /// precedence orderings declared in those lists. fn validate_precedences(grammar: &InputGrammar) -> Result<()> { + // Check that no rule contains a named precedence that is not present in + // any of the `precedences` lists. + fn validate(rule_name: &str, rule: &Rule, names: &HashSet<&String>) -> Result<()> { + match rule { + Rule::Repeat(rule) => validate(rule_name, rule, names), + Rule::Seq(elements) | Rule::Choice(elements) => elements + .iter() + .try_for_each(|e| validate(rule_name, e, names)), + Rule::Metadata { rule, params } => { + if let Precedence::Name(n) = ¶ms.precedence { + if !names.contains(n) { + return Err(anyhow!("Undeclared precedence '{n}' in rule '{rule_name}'")); + } + } + validate(rule_name, rule, names)?; + Ok(()) + } + _ => Ok(()), + } + } + // For any two precedence names `a` and `b`, if `a` comes before `b` // in some list, then it cannot come *after* `b` in any list. let mut pairs = HashMap::new(); @@ -120,27 +141,6 @@ fn validate_precedences(grammar: &InputGrammar) -> Result<()> { } } - // Check that no rule contains a named precedence that is not present in - // any of the `precedences` lists. - fn validate(rule_name: &str, rule: &Rule, names: &HashSet<&String>) -> Result<()> { - match rule { - Rule::Repeat(rule) => validate(rule_name, rule, names), - Rule::Seq(elements) | Rule::Choice(elements) => elements - .iter() - .try_for_each(|e| validate(rule_name, e, names)), - Rule::Metadata { rule, params } => { - if let Precedence::Name(n) = ¶ms.precedence { - if !names.contains(n) { - return Err(anyhow!("Undeclared precedence '{n}' in rule '{rule_name}'")); - } - } - validate(rule_name, rule, names)?; - Ok(()) - } - _ => Ok(()), - } - } - let precedence_names = grammar .precedence_orderings .iter() diff --git a/cli/src/generate/render.rs b/cli/src/generate/render.rs index 34e1d426..d70b23b6 100644 --- a/cli/src/generate/render.rs +++ b/cli/src/generate/render.rs @@ -849,7 +849,7 @@ impl Generator { // are not at the end of the file. let check_eof = large_set.contains('\0'); if check_eof { - add!(self, "(!eof && ") + add!(self, "(!eof && "); } let char_set_info = &mut self.large_character_set_info[large_char_set_ix]; @@ -1663,7 +1663,7 @@ impl Generator { '\r' => add!(self, "'\\r'"), _ => { if c == '\0' { - add!(self, "0") + add!(self, "0"); } else if c == ' ' || c.is_ascii_graphic() { add!(self, "'{c}'"); } else { diff --git a/cli/src/generate/rules.rs b/cli/src/generate/rules.rs index ab74a14b..d8124ef4 100644 --- a/cli/src/generate/rules.rs +++ b/cli/src/generate/rules.rs @@ -146,7 +146,7 @@ impl Rule { Self::Choice(elements) } - pub fn seq(rules: Vec) -> Self { + pub const fn seq(rules: Vec) -> Self { Self::Seq(rules) } } @@ -272,7 +272,7 @@ impl From for Rule { } impl TokenSet { - pub fn new() -> Self { + pub const fn new() -> Self { Self { terminal_bits: SmallBitVec::new(), external_bits: SmallBitVec::new(), diff --git a/cli/src/query_testing.rs b/cli/src/query_testing.rs index cdf2e988..801d880d 100644 --- a/cli/src/query_testing.rs +++ b/cli/src/query_testing.rs @@ -25,7 +25,12 @@ pub struct Assertion { impl Assertion { #[must_use] - pub fn new(row: usize, col: usize, negative: bool, expected_capture_name: String) -> Self { + pub const fn new( + row: usize, + col: usize, + negative: bool, + expected_capture_name: String, + ) -> Self { Self { position: Point::new(row, col), negative, diff --git a/cli/src/test.rs b/cli/src/test.rs index f1f82a43..fedffd95 100644 --- a/cli/src/test.rs +++ b/cli/src/test.rs @@ -216,9 +216,8 @@ pub fn get_test_info<'test>( } => { if *test_num == target_test { return Some((name, input, attributes.languages.clone())); - } else { - *test_num += 1; } + *test_num += 1; } TestEntry::Group { children, .. } => { for child in children { @@ -648,7 +647,7 @@ fn write_tests_to_buffer( if attributes_str.is_empty() { attributes_str.clone() } else { - format!("{}\n", attributes_str) + format!("{attributes_str}\n") }, "=".repeat(*header_delim_len), "-".repeat(*divider_delim_len), diff --git a/lib/binding_rust/lib.rs b/lib/binding_rust/lib.rs index 6bf58dd4..79cfadf3 100644 --- a/lib/binding_rust/lib.rs +++ b/lib/binding_rust/lib.rs @@ -291,8 +291,9 @@ pub struct LossyUtf8<'a> { } impl Language { + #[must_use] pub fn new(builder: LanguageFn) -> Self { - Self(unsafe { (builder.into_raw())() as _ }) + Self(unsafe { builder.into_raw()().cast() }) } /// Get the ABI version number that indicates which version of the diff --git a/lib/language/language.rs b/lib/language/language.rs index 1997b1f3..504c9374 100644 --- a/lib/language/language.rs +++ b/lib/language/language.rs @@ -1,11 +1,11 @@ #![no_std] -/// LanguageFn wraps a C function that returns a pointer to a tree-sitter grammer. +/// `LanguageFn` wraps a C function that returns a pointer to a tree-sitter grammer. #[repr(transparent)] #[derive(Clone, Copy)] pub struct LanguageFn(unsafe extern "C" fn() -> *const ()); impl LanguageFn { - /// Creates a `LanguageFn`. + /// Creates a [`LanguageFn`]. /// /// # Safety /// @@ -15,7 +15,8 @@ impl LanguageFn { Self(f) } - /// Gets the function wrapped by this `LanguageFn`. + /// Gets the function wrapped by this [`LanguageFn`]. + #[must_use] pub const fn into_raw(self) -> unsafe extern "C" fn() -> *const () { self.0 }