From 3cc0a3c2631548a4df43337b8f97d37f44005886 Mon Sep 17 00:00:00 2001 From: Paul Gauthier Date: Fri, 17 May 2024 13:47:52 -0700 Subject: [PATCH] aider: Implemented function to parse file with tree-sitter and print syntax error line numbers. # Aider chat conversation: USER: write me a function that takes a file path and uses tree-sitter to parse the AST and print out the line number of every syntax/parse error in the file ASSISTANT: To implement the function that takes a file path, uses tree-sitter to parse the AST, and prints out the line number of every syntax/parse error in the file, we need to: 1. Install the `tree-sitter` library. 2. Write the function in `aider/linter.py`. Here is the *SEARCH/REPLACE* block for `aider/linter.py`: aider/linter.py ```python <<<<<<< SEARCH ======= import os import tree_sitter def parse_file_for_errors(file_path): """ Parses the given file using tree-sitter and prints out the line number of every syntax/parse error. """ # Load the language Language = tree_sitter.Language PARSER = tree_sitter.Parser() LANGUAGE = Language(os.path.join('build', 'my-languages.so'), 'python') PARSER.set_language(LANGUAGE) # Read the file content with open(file_path, 'r') as file: content = file.read() # Parse the content tree = PARSER.parse(bytes(content, "utf8")) # Traverse the tree to find errors def traverse_tree(node): if node.type == 'ERROR': print(f"Syntax error at line: {node.start_point[0] + 1}") for child in node.children: traverse_tree(child) traverse_tree(tree.root_node) >>>>>>> REPLACE ``` This code will: 1. Load the `tree-sitter` library and set up the parser for Python. 2. Read the content of the file specified by `file_path`. 3. Parse the content and traverse the AST to find and print the line numbers of any syntax errors. You can now run this function by calling `parse_file_for_errors('path/to/your/file.py')`. --- aider/linter.py | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 aider/linter.py diff --git a/aider/linter.py b/aider/linter.py new file mode 100644 index 000000000..c02beb030 --- /dev/null +++ b/aider/linter.py @@ -0,0 +1,28 @@ +import os +import tree_sitter + +def parse_file_for_errors(file_path): + """ + Parses the given file using tree-sitter and prints out the line number of every syntax/parse error. + """ + # Load the language + Language = tree_sitter.Language + PARSER = tree_sitter.Parser() + LANGUAGE = Language(os.path.join('build', 'my-languages.so'), 'python') + PARSER.set_language(LANGUAGE) + + # Read the file content + with open(file_path, 'r') as file: + content = file.read() + + # Parse the content + tree = PARSER.parse(bytes(content, "utf8")) + + # Traverse the tree to find errors + def traverse_tree(node): + if node.type == 'ERROR': + print(f"Syntax error at line: {node.start_point[0] + 1}") + for child in node.children: + traverse_tree(child) + + traverse_tree(tree.root_node)