SKILL.md--- name: treesitter-patterns description: "Universal patterns for tree-sitter code parsing. Covers AST visitors, query patterns, and language plugin development. Framework-agnostic." --- # Tree-sitter Patterns Skill Universal patterns for working with tree-sitter in any project. Covers AST parsing, query patterns, visitors, and language plugin development. ## Design Principle This skill is **framework-generic**. It provides universal tree-sitter patterns: - NOT tailored to Code-Index-MCP, treesitter-chunker, or any specific project - Covers common patterns applicable across all tree-sitter projects - Project-specific queries go in project-specific skills ## Variables | Variable | Default | Description | |----------|---------|-------------| | TREE_SITTER_DIR | tree_sitter | Directory for language parsers | | QUERY_DIR | queries | Directory for .scm query files | | LANGUAGES | auto | Auto-detect or list of languages | ## Instructions **MANDATORY** - Follow the Workflow steps below in order. 1. Identify languages to parse 2. Install appropriate language parsers 3. Write queries for extraction needs 4. Handle edge cases and errors ## Red Flags - STOP and Reconsider If you're about to: - Parse without error handling (syntax errors are common) - Assume all files parse successfully - Write queries without testing on sample code - Ignore performance for large files **STOP** -> Add error handling -> Test on edge cases -> Then proceed ## Cookbook ### Language Plugin Development - IF: Creating a new language parser - THEN: Read and execute `./cookbook/language-plugin.md` ### AST Visitor Patterns - IF: Walking the AST to extract information - THEN: Read and execute `./cookbook/ast-visitor.md` ### Query Patterns - IF: Writing tree-sitter queries - THEN: Read and execute `./cookbook/query-patterns.md` ## Quick Reference ### Python Setup ```python import tree_sitter_python as tspython from tree_sitter import Language, Parser # Create parser parser = Parser(Language(tspython.language())) # Parse code source = b"def hello(): pass" tree = parser.parse(source) # Access root node root = tree.root_node print(root.sexp()) ``` ### Node Navigation ```python # Get children for child in node.children: print(child.type, child.text) # Named children only (skip punctuation) for child in node.named_children: print(child.type) # Find by type def find_all(node, type_name): results = [] if node.type == type_name: results.append(node) for child in node.children: results.extend(find_all(child, type_name)) return results functions = find_all(root, "function_definition") ``` ### Query Language ```scheme ; Match function definitions (function_definition name: (identifier) @function.name parameters: (parameters) @function.params body: (block) @function.body) ; Match class definitions (class_definition name: (identifier) @class.name body: (block) @class.body) ; Match imports (import_sta