Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ Call graph roots can be narrowed with `--file` or `path/to/file.go:Name` when mu
| `canopy search grep` | Structural selector queries (e.g. `function_definition[name=/^Test/]`) |
| `canopy search refs` | Find references by symbol name or regex |
| `canopy search query` | Raw tree-sitter S-expression queries |
| `canopy search scope` | Resolve symbols in scope at file + line |
| `canopy search scope` | Resolve lexical scope at file + line, including Rust, Java, and C++ bindings |
| `canopy search context` | Pack focused context for agent token budgets. `--concept` for concept-aware packing |
| `canopy search symbols` | Search symbols by pattern |
| `canopy search imports` | Analyze import patterns |
Expand Down
2 changes: 1 addition & 1 deletion cmd/canopy/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -946,7 +946,7 @@ func work(input string) {
t.Fatalf("ReadFrom failed: %v", err)
}
text := output.String()
for _, expected := range []string{"package: sample", "input (param)", "value (local_var)", "fmt (import)"} {
for _, expected := range []string{"language: go", "package: sample", "input (param)", "value (local_var)", "fmt (import)"} {
if !strings.Contains(text, expected) {
t.Fatalf("expected output to contain %q, got:\n%s", expected, text)
}
Expand Down
3 changes: 2 additions & 1 deletion cmd/canopy/scope_cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ func newScopeCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "scope <file>",
Aliases: []string{"gtsscope"},
Short: "Resolve symbols in scope for a file and line",
Short: "Resolve lexical scope for a file and line",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
filePath := args[0]
Expand Down Expand Up @@ -47,6 +47,7 @@ func newScopeCmd() *cobra.Command {

fmt.Printf("file: %s\n", report.File)
fmt.Printf("line: %d\n", report.Line)
fmt.Printf("language: %s\n", report.Language)
fmt.Printf("package: %s\n", report.Package)
if report.Focus != nil {
fmt.Printf("focus: %s %s [%d:%d]\n", report.Focus.Kind, symbolLabel(report.Focus.Name, report.Focus.Signature), report.Focus.StartLine, report.Focus.EndLine)
Expand Down
56 changes: 56 additions & 0 deletions internal/mcp/call_scope_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package mcp

import (
"os"
"path/filepath"
"testing"

gtsscope "m31labs.dev/canopy/internal/scope"
)

func TestCallScopeReportsJavaLexicalBindings(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "Service.java")
const source = `package demo;
import java.util.List;

class Service {
int run(String input) {
for (String item : List.of(input)) {
return item.length();
}
return 0;
}
}
`
if err := os.WriteFile(path, []byte(source), 0o644); err != nil {
t.Fatalf("WriteFile: %v", err)
}

result, err := NewService(dir, "").Call("gts_scope", map[string]any{
"file": path,
"line": 7,
})
if err != nil {
t.Fatalf("gts_scope: %v", err)
}
report, ok := result.(gtsscope.Report)
if !ok {
t.Fatalf("gts_scope result type = %T, want scope.Report", result)
}
if report.Language != "java" || report.Package != "demo" {
t.Fatalf("report language/package = %q/%q, want java/demo", report.Language, report.Package)
}
for _, want := range []string{"List", "Service", "run", "input", "item"} {
found := false
for _, symbol := range report.Symbols {
if symbol.Name == want {
found = true
break
}
}
if !found {
t.Fatalf("missing %q in gts_scope result: %+v", want, report.Symbols)
}
}
}
2 changes: 1 addition & 1 deletion internal/mcp/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ func searchTools() []Tool {
},
{
Name: "gts_scope",
Description: "Resolve symbols in scope for a file and line",
Description: "Resolve lexical scope for a file and line, including imports, parameters, destructuring, and control-flow bindings",
InputSchema: Schema{
Properties: map[string]Property{
"file": {Type: "string"},
Expand Down
265 changes: 265 additions & 0 deletions internal/scope/bindings.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,265 @@
package scope

import (
"strings"

"github.com/odvcencio/gotreesitter"
)

type lexicalBinding struct {
name string
line int
}

func collectParameterNode(collector *symbolCollector, bound *gotreesitter.BoundTree, node *gotreesitter.Node, kind string) {
detail := nodeFieldText(bound, node, "type")
targets := parameterBindingNodes(bound, node)
seen := make(map[string]struct{})
for _, target := range targets {
for _, binding := range bindingNames(bound, target) {
if _, ok := seen[binding.name]; ok {
continue
}
seen[binding.name] = struct{}{}
collector.add(binding.name, kind, detail, binding.line)
}
}
}

func parameterBindingNodes(bound *gotreesitter.BoundTree, node *gotreesitter.Node) []*gotreesitter.Node {
if node == nil {
return nil
}
var targets []*gotreesitter.Node
seen := make(map[*gotreesitter.Node]struct{})
add := func(candidate *gotreesitter.Node) {
if candidate == nil {
return
}
if _, ok := seen[candidate]; ok {
return
}
seen[candidate] = struct{}{}
targets = append(targets, candidate)
}
for _, field := range []string{"name", "pattern", "declarator"} {
add(bound.ChildByField(node, field))
}

typeNode := bound.ChildByField(node, "type")
for i := 0; i < node.ChildCount(); i++ {
child := node.Child(i)
if child == nil || !child.IsNamed() || child == typeNode {
continue
}
if isBindingShape(bound.NodeType(child)) {
add(child)
}
}
return targets
}

func collectLocalDeclaration(collector *symbolCollector, bound *gotreesitter.BoundTree, declaration *gotreesitter.Node) {
if declaration == nil {
return
}
detail := nodeFieldText(bound, declaration, "type")
found := false
for i := 0; i < declaration.ChildCount(); i++ {
child := declaration.Child(i)
if child == nil || !child.IsNamed() {
continue
}
switch bound.NodeType(child) {
case "variable_declarator", "init_declarator":
found = addDeclaratorBindings(collector, bound, child, detail) || found
}
}
if found {
return
}
addDeclaratorBindings(collector, bound, declaration, detail)
}

func addDeclaratorBindings(collector *symbolCollector, bound *gotreesitter.BoundTree, declarator *gotreesitter.Node, detail string) bool {
if declarator == nil {
return false
}
var target *gotreesitter.Node
for _, field := range []string{"name", "declarator", "pattern"} {
if target = bound.ChildByField(declarator, field); target != nil {
break
}
}
if target == nil {
target = firstDirectBindingNode(bound, declarator)
}
bindings := bindingNames(bound, target)
for _, binding := range bindings {
collector.add(binding.name, "local_var", detail, binding.line)
}
return len(bindings) > 0
}

func collectEnclosingStmtDecls(collector *symbolCollector, bound *gotreesitter.BoundTree, node *gotreesitter.Node) {
if node == nil {
return
}
switch bound.NodeType(node) {
case "for_statement":
collectGoForDecls(collector, bound, node)
collectHeaderDeclarations(collector, bound, node)
case "enhanced_for_statement":
addFieldBinding(collector, bound, node, "name", "local_var", nodeFieldText(bound, node, "type"))
case "for_range_loop":
addFieldBinding(collector, bound, node, "declarator", "local_var", nodeFieldText(bound, node, "type"))
case "for_expression":
addFieldBinding(collector, bound, node, "pattern", "local_var", "")
case "catch_clause":
collectCatchBinding(collector, bound, node)
case "if_statement", "while_statement", "switch_statement":
collectHeaderDeclarations(collector, bound, node)
case "if_expression", "while_expression", "match_expression":
collectHeaderDeclarations(collector, bound, node)
}
}

func collectHeaderDeclarations(collector *symbolCollector, bound *gotreesitter.BoundTree, node *gotreesitter.Node) {
for i := 0; i < node.ChildCount(); i++ {
child := node.Child(i)
if child == nil || !child.IsNamed() || isBlockNode(bound.NodeType(child)) {
continue
}
collectHeaderNode(collector, bound, child)
}
}

func collectHeaderNode(collector *symbolCollector, bound *gotreesitter.BoundTree, node *gotreesitter.Node) {
if node == nil || isBlockNode(bound.NodeType(node)) {
return
}
switch bound.NodeType(node) {
case "short_var_declaration":
collectShortVarDecl(collector, bound, node)
return
case "range_clause":
collectRangeClauseDecls(collector, bound, node)
return
case "let_declaration":
collectRustLetDecl(collector, bound, node)
return
case "local_variable_declaration", "declaration":
collectLocalDeclaration(collector, bound, node)
return
}
for i := 0; i < node.ChildCount(); i++ {
child := node.Child(i)
if child != nil && child.IsNamed() {
collectHeaderNode(collector, bound, child)
}
}
}

func collectCatchBinding(collector *symbolCollector, bound *gotreesitter.BoundTree, catch *gotreesitter.Node) {
for i := 0; i < catch.ChildCount(); i++ {
child := catch.Child(i)
if child == nil || !child.IsNamed() {
continue
}
switch bound.NodeType(child) {
case "catch_formal_parameter", "formal_parameter", "parameter_declaration":
collectParameterNode(collector, bound, child, "local_var")
return
}
}
}

func addFieldBinding(collector *symbolCollector, bound *gotreesitter.BoundTree, node *gotreesitter.Node, field, kind, detail string) {
target := bound.ChildByField(node, field)
if target == nil {
target = firstDirectBindingNode(bound, node)
}
for _, binding := range bindingNames(bound, target) {
collector.add(binding.name, kind, detail, binding.line)
}
}

func firstDirectBindingNode(bound *gotreesitter.BoundTree, node *gotreesitter.Node) *gotreesitter.Node {
if node == nil {
return nil
}
typeNode := bound.ChildByField(node, "type")
for i := 0; i < node.ChildCount(); i++ {
child := node.Child(i)
if child == nil || !child.IsNamed() || child == typeNode {
continue
}
if isBindingShape(bound.NodeType(child)) {
return child
}
}
return nil
}

func bindingNames(bound *gotreesitter.BoundTree, node *gotreesitter.Node) []lexicalBinding {
if node == nil {
return nil
}
var out []lexicalBinding
seen := make(map[string]struct{})
var visit func(*gotreesitter.Node)
visit = func(current *gotreesitter.Node) {
if current == nil || !current.IsNamed() {
return
}
nodeType := bound.NodeType(current)
switch nodeType {
case "identifier", "field_identifier", "shorthand_field_identifier_pattern",
"shorthand_property_identifier_pattern":
name := strings.TrimSpace(bound.NodeText(current))
if name == "" || name == "_" {
return
}
if _, ok := seen[name]; ok {
return
}
seen[name] = struct{}{}
out = append(out, lexicalBinding{name: name, line: int(current.StartPoint().Row) + 1})
return
}
if isTypeOnlyNode(nodeType) {
return
}
for i := 0; i < current.ChildCount(); i++ {
visit(current.Child(i))
}
}
visit(node)
return out
}

func isBindingShape(nodeType string) bool {
if nodeType == "identifier" || nodeType == "field_identifier" {
return true
}
return strings.Contains(nodeType, "declarator") || strings.Contains(nodeType, "pattern")
}

func isTypeOnlyNode(nodeType string) bool {
if strings.Contains(nodeType, "type") && !strings.Contains(nodeType, "pattern") {
return true
}
switch nodeType {
case "namespace_identifier", "primitive_type", "integral_type", "floating_point_type":
return true
}
return false
}

func nodeFieldText(bound *gotreesitter.BoundTree, node *gotreesitter.Node, field string) string {
child := bound.ChildByField(node, field)
if child == nil {
return ""
}
return strings.TrimSpace(bound.NodeText(child))
}
Loading
Loading