tree-sitter / py-tree-sitter

Python bindings to the Tree-sitter parsing library

Home Page:https://tree-sitter.github.io/py-tree-sitter/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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

skye95git opened this issue · comments

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