bashrusttreesitter

Why this tree-sitter query is capturing twice?


I don't understand why this tree-sitter query is capturing the same data twice.. How do I make it only once.

Here's my bash script that I'm parsing:

pkgname="potato"

Here's the tree-sitter query:

(program (variable_assignment
     name: (variable_name) @variable_name
     value: (string) @value
))

Here's the rust snippet I'm using to demonstrate this:

        for (query_match, _) in query.captures(
            &Query::new(
                tree_sitter_bash::language(),
                "(program (variable_assignment
                    name: (variable_name) @variable_name
                    value: (string) @value
                  ))",
            )
            .unwrap(),
            tree.root_node(),
            |_| sourced_code.stdout.clone(),
        ) {
            query_match.captures.iter().for_each(|f| {
                dbg!(f.node.utf8_text(&sourced_code.stdout)).unwrap();
            });

            dbg!(&query_match.captures);
        }

Here's the output:

[src/parser/pacbuild.rs:145] f.node.utf8_text(&sourced_code.stdout) = Ok(
    "pkgname",
)
[src/parser/pacbuild.rs:145] f.node.utf8_text(&sourced_code.stdout) = Ok(
    "\"potato\"",
)
[src/parser/pacbuild.rs:148] &query_match.captures = [
    QueryCapture {
        node: {Node variable_name (0, 0) - (0, 7)},
        index: 0,
    },
    QueryCapture {
        node: {Node string (0, 8) - (0, 16)},
        index: 1,
    },
]
[src/parser/pacbuild.rs:145] f.node.utf8_text(&sourced_code.stdout) = Ok(
    "pkgname",
)
[src/parser/pacbuild.rs:145] f.node.utf8_text(&sourced_code.stdout) = Ok(
    "\"potato\"",
)
[src/parser/pacbuild.rs:148] &query_match.captures = [
    QueryCapture {
        node: {Node variable_name (0, 0) - (0, 7)},
        index: 0,
    },
    QueryCapture {
        node: {Node string (0, 8) - (0, 16)},
        index: 1,
    },
]

As you can see, the loop's running twice, and printing the same data. How do I prevent this?


Solution

  • discussion answer

            for (query_match, index) in query.captures(
                &Query::new(
                    tree_sitter_bash::language(),
                    "(program (variable_assignment
                        name: (variable_name) @variable_name
                        value: (string) @value
                      ))",
                )
                .unwrap(),
                tree.root_node(),
                |_| sourced_code.stdout.clone(),
            ) {
                if index == 0 {
                    // code
                }
            }
    

    Fixed the issue