tree-sitter / py-tree-sitter

Python bindings to the Tree-sitter parsing library
https://tree-sitter.github.io/py-tree-sitter/
MIT License
817 stars 96 forks source link

How to get the location of a variable name in the whole function? #232

Closed skye95git closed 4 months ago

skye95git commented 4 months ago

I want to use your tool to anonymize function variable names. I tried to use your tool to parse the function, and found that after parsing, the variable names all appear as identifiers. In this case, how to distinguish different variable names and where they appear in the function body?

For example, the original code:

def find_max(a, b):
    if a > b:
        return a
    else:
        return b

The result of tree.root_node.sexp():

(module 
  (function_definition name:   
  (identifier) parameters: (parameters (identifier) (identifier)) 
  body: (block (if_statement condition: (comparison_operator (identifier) (identifier)) consequence: (block (return_statement (identifier))) alternative: (else_clause body: (block (return_statement (identifier))))))))

But I want to get:

def find_max(var_0, var_1):
    if var_0 > var_1:
        return var_0
    else:
        return var_1