-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathruby_ast.go
More file actions
1738 lines (1634 loc) · 64.4 KB
/
Copy pathruby_ast.go
File metadata and controls
1738 lines (1634 loc) · 64.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package rubyextractor
import (
"path/filepath"
"sort"
"strings"
"github.com/enola-labs/enola/internal/facts"
sitter "github.com/tree-sitter/go-tree-sitter"
ruby "github.com/tree-sitter/tree-sitter-ruby/bindings/go"
)
// sortedKeys returns the keys of a set in deterministic (sorted) order — used to
// emit stable prop values into facts.
func sortedKeys(m map[string]bool) []string {
out := make([]string, 0, len(m))
for k := range m {
out = append(out, k)
}
sort.Strings(out)
return out
}
// extractFileAST parses a Ruby file with tree-sitter and emits architectural
// facts. It replaces the former line-based regex scanner: every symbol, import,
// mixin, constant, attr, ActiveRecord storage/association, and RelCalls edge the
// regex produced is preserved here, with higher fidelity (heredocs, multi-line
// expressions, endless methods, and nested scopes are handled by the grammar).
func extractFileAST(src []byte, relFile string, isRails, exportedByPackwerk bool) []facts.Fact {
parser := sitter.NewParser()
defer parser.Close()
if err := parser.SetLanguage(sitter.NewLanguage(ruby.Language())); err != nil {
return nil
}
tree := parser.Parse(src, nil)
defer tree.Close()
w := &rubyWalker{
src: src,
relFile: relFile,
dir: filepath.Dir(relFile),
isRails: isRails,
exportedByPackwerk: exportedByPackwerk,
fileRefIdx: -1,
}
root := tree.RootNode()
w.walkBody(root)
// Capture executable calls made at file scope (top-level assignment RHS,
// conditionals, fixture `Badge.foo(...)`, plugin `after_initialize` blocks) on
// the file-scope ref fact. walkForCalls returns at nested defs/classes, which
// get their own pass.
if owner := w.bodyCallOwner(); owner >= 0 {
w.walkScopeForCalls(root, owner, map[string]bool{}, nil)
}
// Attach any dynamic-dispatch prefixes discovered anywhere in the file to the
// file-scope fact so the collector can mark same-prefix methods as used.
if len(w.dynamicPrefixes) > 0 {
idx := w.ensureFileRefFact()
w.out[idx].Props["dynamic_send_prefixes"] = sortedKeys(w.dynamicPrefixes)
}
// Drop the file-scope reference fact if it carries neither call edges nor
// dynamic-dispatch prefixes, so empty facts never reach the store.
if w.fileRefIdx >= 0 && len(w.out[w.fileRefIdx].Relations) == 0 &&
w.out[w.fileRefIdx].Props["dynamic_send_prefixes"] == nil {
w.out = append(w.out[:w.fileRefIdx], w.out[w.fileRefIdx+1:]...)
}
return w.out
}
// ensureFileRefFact returns the index of this file's lazily-created file-scope
// reference fact (facts.KindFileRef), creating it on first use.
func (w *rubyWalker) ensureFileRefFact() int {
if w.fileRefIdx < 0 {
w.out = append(w.out, facts.Fact{
Kind: facts.KindFileRef,
Name: w.relFile,
File: w.relFile,
Props: map[string]any{"language": "ruby"},
})
w.fileRefIdx = len(w.out) - 1
}
return w.fileRefIdx
}
// bodyCallOwner returns the index of the fact that class/module-body and
// top-level call edges should attach to: the enclosing class/module symbol fact
// when inside a type scope, otherwise (top level, or an eigenclass body whose
// symFactIdx is -1) the lazily-created file-scope reference fact.
func (w *rubyWalker) bodyCallOwner() int {
if s := w.cur(); s != nil && s.symFactIdx >= 0 {
return s.symFactIdx
}
return w.ensureFileRefFact()
}
// rubyScope tracks a class/module/eigenclass nesting level.
type rubyScope struct {
name string // simple (last) name; "" for an eigenclass (class << self)
kind string // "class", "module", or "eigenclass"
visibility string // "public" | "private" | "protected"
moduleFunc bool // module_function active: subsequent defs are class methods
isModel bool // ActiveRecord model: associations/scopes/table_name apply
isSerializer bool // ActiveModel::Serializer: attributes/associations back methods
// hasInstanceMethod records that this scope directly defined a `def foo`
// (instance, not `def self.x`) method. For a module this signals a mixin
// (meant to be included), which makes the module abstract for package metrics.
hasInstanceMethod bool
symFactIdx int // index into w.out of this scope's class/module symbol fact, or -1
}
type rubyWalker struct {
src []byte
relFile string
dir string
isRails bool
exportedByPackwerk bool
out []facts.Fact
scopeStack []rubyScope
// fileRefIdx is the index into out of the lazily-created file-scope reference
// fact (facts.KindFileRef) that holds top-level call edges; -1 until first used.
fileRefIdx int
// dynamicPrefixes accumulates the static prefixes of interpolated symbols
// (`:"report_#{type}"` -> "report_") seen anywhere in the file. They mark
// dynamic dispatch (public_send/send by computed name), letting the dead-code
// detector treat same-prefix methods as used. File-global; nil until first hit.
dynamicPrefixes map[string]bool
// pendingStrPrefixes / sawDispatcher gate interpolated-STRING prefixes
// (`"present_#{idx}"`) per scope: unlike symbols, snake_case strings are commonly
// cache/Redis keys, so a string prefix is committed to dynamicPrefixes only when
// the same scope also invokes a dispatcher (send/public_send/__send__/try). Reset
// at each scope-entry walk (walkScopeForCalls / handleMethod) and committed after.
pendingStrPrefixes map[string]bool
sawDispatcher bool
// Per-method complexity state, set up by handleMethod around walkForCalls.
// metrics is nil outside a method body walk. loopDepth is the current loop
// nesting depth; selfName/selfShort are the enclosing method's full and short
// names (for direct-recursion detection — Ruby self-calls are usually bare).
metrics *rubyBodyMetrics
loopDepth int
selfName string
selfShort string
}
// rubyBodyMetrics accumulates per-method complexity signals during the single
// walkForCalls body traversal — mirrors the Go/Python extractors.
type rubyBodyMetrics struct {
loopDepth int // max loop nesting depth
loopCount int // number of loop constructs (syntactic + iterator blocks)
decisions int // decision points (cyclomatic = 1 + decisions)
callsInLoop []string // distinct call targets invoked at loop depth >= 1
inLoopSeen map[string]bool // dedup set for callsInLoop
recursive bool // body directly calls the enclosing method
}
// rubyIterators are methods whose block runs once per element — i.e. a loop.
// Block-taking methods NOT in this set (transaction, tap, synchronize,
// File.open, …) run their block once and are deliberately not treated as loops.
// Aggregate-or-iterate methods (count/sum/find/all?…) are safe to include
// because a block is required before any of these counts as a loop.
//
// find_in_batches / in_batches are deliberately excluded: their block runs once
// per *batch* (an array), so the real per-element loop is the inner .each/.map
// over that batch. Counting the batch block as a loop as well double-counts and
// mislabels a single O(n) pass as O(n²). (find_each yields individual elements
// and is a genuine per-element loop, so it stays.) Both names remain in the
// enterprise expensiveMethods gate, so a batch scan nested inside another loop is
// still flagged by name — only the spurious extra depth is dropped.
var rubyIterators = map[string]bool{
"each": true, "each_with_index": true, "each_with_object": true,
"each_pair": true, "each_key": true, "each_value": true,
"each_slice": true, "each_cons": true, "each_line": true,
"each_char": true, "each_entry": true,
"map": true, "map!": true, "collect": true, "collect!": true,
"flat_map": true, "select": true, "select!": true, "filter": true,
"filter_map": true, "reject": true, "reject!": true,
"detect": true, "find": true, "find_all": true, "find_index": true,
"find_each": true,
"reduce": true, "inject": true, "min_by": true, "max_by": true,
"sort_by": true, "group_by": true, "partition": true, "chunk_while": true,
"zip": true, "cycle": true, "times": true, "upto": true, "downto": true,
"step": true, "loop": true, "all?": true, "any?": true, "none?": true,
"one?": true, "count": true, "sum": true, "tally_by": true,
}
// recordCallMetrics notes a resolved call target against the current method's
// complexity metrics: flags direct recursion and records calls made inside loops.
func (w *rubyWalker) recordCallMetrics(target string) {
if w.metrics == nil || target == "" {
return
}
if target == w.selfShort || target == w.selfName || target == "self."+w.selfShort {
w.metrics.recursive = true
}
w.recordInLoopCall(target)
}
// recordSelfAwareMetrics records a call target's metrics but only counts it as
// recursion when the call dispatches to the SAME object as the enclosing method —
// a receiverless call or a plain `self.foo`. An explicit receiver (`x.foo`,
// `self.class.foo`, `obj.try(:foo)`) targets a different object or a sibling
// class/instance method, so it feeds the in-loop N+1 signal but never the recursion
// flag. (A `Const.foo` that resolves to this exact method is handled by the caller
// via a selfName match before reaching here.)
func (w *rubyWalker) recordSelfAwareMetrics(target string, recv *sitter.Node) {
if recv == nil || recv.Kind() == "self" {
w.recordCallMetrics(target)
return
}
w.recordInLoopCall(target)
}
// recordInLoopCall adds a target to calls_in_loop (deduped) when inside a loop,
// without the recursion check — used for raw instance-method names (e.g. an
// association read `u.posts`) whose name must not be mistaken for self-recursion.
func (w *rubyWalker) recordInLoopCall(target string) {
if w.metrics == nil || target == "" || w.loopDepth == 0 {
return
}
if w.metrics.inLoopSeen == nil {
w.metrics.inLoopSeen = make(map[string]bool)
}
if !w.metrics.inLoopSeen[target] {
w.metrics.inLoopSeen[target] = true
w.metrics.callsInLoop = append(w.metrics.callsInLoop, target)
}
}
// rubyCheapMethods are obviously-cheap attribute/Enumerable/Kernel methods that
// are not DB I/O. No-arg instance calls to these inside loops are not recorded in
// calls_in_loop, to keep it focused (the enterprise association/keyword gate is
// the real precision filter, so this list need not be exhaustive).
var rubyCheapMethods = map[string]bool{
"id": true, "name": true, "to_s": true, "to_str": true, "to_i": true,
"to_a": true, "to_h": true, "to_sym": true, "to_param": true, "inspect": true,
"hash": true, "class": true, "object_id": true, "freeze": true, "frozen?": true,
"dup": true, "clone": true, "present?": true, "blank?": true, "nil?": true,
"empty?": true, "any?": true, "size": true, "length": true, "first": true,
"last": true, "keys": true, "values": true, "key?": true, "include?": true,
"is_a?": true, "kind_of?": true, "instance_of?": true, "respond_to?": true,
"tap": true, "then": true, "itself": true, "send": true, "public_send": true,
}
// --- scope helpers ---
func (w *rubyWalker) push(s rubyScope) { w.scopeStack = append(w.scopeStack, s) }
func (w *rubyWalker) pop() { w.scopeStack = w.scopeStack[:len(w.scopeStack)-1] }
func (w *rubyWalker) cur() *rubyScope {
if len(w.scopeStack) == 0 {
return nil
}
return &w.scopeStack[len(w.scopeStack)-1]
}
// scopeQual joins the enclosing class/module names into a Ruby-qualified name.
// Eigenclass and anonymous entries do not contribute.
func (w *rubyWalker) scopeQual() string {
var parts []string
for _, s := range w.scopeStack {
if s.kind == "eigenclass" || s.name == "" {
continue
}
parts = append(parts, s.name)
}
return strings.Join(parts, "::")
}
// curVisibility returns the visibility of the innermost type scope.
func (w *rubyWalker) curVisibility() string {
if s := w.cur(); s != nil && s.visibility != "" {
return s.visibility
}
return "public"
}
// inEigenclass reports whether the innermost scope is an eigenclass.
func (w *rubyWalker) inEigenclass() bool {
s := w.cur()
return s != nil && s.kind == "eigenclass"
}
func (w *rubyWalker) exported() bool {
return w.curVisibility() == "public" && w.exportedByPackwerk
}
// --- body walking ---
// walkBody iterates the statements of a program or body_statement, dispatching
// each. It is the single entry point for both top-level and nested scopes.
func (w *rubyWalker) walkBody(node *sitter.Node) {
if node == nil {
return
}
for i := uint(0); i < node.ChildCount(); i++ {
w.walkStatement(node.Child(i))
}
}
func (w *rubyWalker) walkStatement(node *sitter.Node) {
if node == nil || !node.IsNamed() {
return
}
switch node.Kind() {
case "module":
w.handleModule(node)
case "class":
w.handleClass(node)
case "singleton_class":
w.handleSingletonClass(node)
case "method":
w.handleMethod(node, w.classMethodContext())
case "singleton_method":
w.handleMethod(node, true)
case "assignment":
w.handleAssignment(node)
case "call":
w.handleBodyCall(node)
// Executable call EDGES in this statement (macro args, qualified
// `Const.method` calls, calls inside blocks) are captured by the per-scope
// walkForCalls pass run in handleClass/handleModule/extractFileAST — not here
// — so assignments and every other statement kind are covered uniformly.
// This case still descends into a trailing do/brace block to capture nested
// DECLARATIONS (def/class/const inside included/class_methods/concerning blocks).
if body := blockBody(node); body != nil {
w.walkBody(body)
}
case "identifier":
// Bare statements: visibility markers and module_function.
switch rubyText(node, w.src) {
case "private", "protected", "public":
if s := w.cur(); s != nil {
s.visibility = rubyText(node, w.src)
}
case "module_function":
if s := w.cur(); s != nil {
s.moduleFunc = true
}
}
case "comment":
// ignore
default:
// Control-flow / grouping containers (if, unless, begin, case, while,
// modifiers, ...): descend so nested require/include/def/const
// declarations are captured, as the line-based scanner did.
for i := uint(0); i < node.ChildCount(); i++ {
w.walkStatement(node.Child(i))
}
}
}
// classMethodContext reports whether a plain `def` in the current scope should be
// treated as a class method (eigenclass body or after module_function).
func (w *rubyWalker) classMethodContext() bool {
if w.inEigenclass() {
return true
}
if s := w.cur(); s != nil && s.moduleFunc {
return true
}
return false
}
// --- modules / classes ---
func (w *rubyWalker) handleModule(node *sitter.Node) {
name := w.constName(node.ChildByFieldName("name"))
if name == "" {
return
}
qual := w.qualify(name)
body := node.ChildByFieldName("body")
props := map[string]any{
"symbol_kind": facts.SymbolInterface,
"exported": w.exportedByPackwerk,
"language": "ruby",
// Package-metrics abstractness: a Ruby module is only "abstract" when it is
// a mixin (defines instance methods or is an ActiveSupport::Concern). Most
// Rails modules are pure namespaces (`module Api; class Foo`), so default to
// concrete and promote to abstract below once the body is known.
"abstract": false,
}
if bodyHasConcern(body, w.src) {
props["concern"] = true
props["abstract"] = true // Concern = behavior mixed into includers
}
if w.isRails {
props["framework"] = "rails"
}
w.out = append(w.out, facts.Fact{
Kind: facts.KindSymbol,
Name: qual,
File: w.relFile,
Line: line(node),
Props: props,
Relations: []facts.Relation{{Kind: facts.RelDeclares, Target: w.dir}},
})
modIdx := len(w.out) - 1
w.push(rubyScope{name: name, kind: "module", visibility: "public", symFactIdx: modIdx})
w.walkBody(body)
// Capture executable calls made directly in the module body (see handleClass).
w.walkScopeForCalls(body, modIdx, map[string]bool{}, nil)
// A module that defined instance methods during the walk is a mixin → abstract.
// props is shared by reference with the fact appended above, so this updates it
// in place (same mechanism handleMethod uses for cyclomatic).
if s := w.cur(); s != nil && s.hasInstanceMethod {
props["abstract"] = true
}
w.pop()
}
func (w *rubyWalker) handleClass(node *sitter.Node) {
name := w.constName(node.ChildByFieldName("name"))
if name == "" {
return
}
qual := w.qualify(name)
superclass := w.superclassName(node.ChildByFieldName("superclass"))
props := map[string]any{
"symbol_kind": facts.SymbolClass,
"exported": w.exported(),
"language": "ruby",
}
if w.isRails {
props["framework"] = "rails"
}
if superclass != "" {
props["superclass"] = superclass
}
rels := []facts.Relation{{Kind: facts.RelDeclares, Target: w.dir}}
if superclass != "" {
rels = append(rels, facts.Relation{Kind: facts.RelImplements, Target: superclass})
}
w.out = append(w.out, facts.Fact{
Kind: facts.KindSymbol,
Name: qual,
File: w.relFile,
Line: line(node),
Props: props,
Relations: rels,
})
clsIdx := len(w.out) - 1
// ActiveRecord model: emit a storage fact and flag the scope so the body
// scan picks up associations, scopes, and explicit table names.
isModel := isARBaseClass(superclass)
if isModel {
w.out = append(w.out, facts.Fact{
Kind: facts.KindStorage,
Name: qual,
File: w.relFile,
Line: line(node),
Props: map[string]any{
"storage_kind": "model",
"table": inferTableName(qual),
"language": "ruby",
"framework": "rails",
},
Relations: []facts.Relation{{Kind: facts.RelDeclares, Target: w.dir}},
})
}
w.push(rubyScope{name: name, kind: "class", visibility: "public", isModel: isModel,
isSerializer: isSerializerBase(superclass), symFactIdx: clsIdx})
body := node.ChildByFieldName("body")
w.walkBody(body)
// Capture executable calls made directly in the class body (assignment RHS,
// conditionals, hash/Proc literals, macro args) as uses of this class.
// walkForCalls returns at nested defs/classes, which get their own pass.
w.walkScopeForCalls(body, clsIdx, map[string]bool{}, nil)
w.pop()
}
func (w *rubyWalker) handleSingletonClass(node *sitter.Node) {
// class << self — methods inside become class (singleton) methods. The
// eigenclass entry carries no name and does not affect qualification.
w.push(rubyScope{name: "", kind: "eigenclass", visibility: "public", symFactIdx: -1})
body := node.ChildByFieldName("body")
w.walkBody(body)
// The eigenclass has no symbol fact (symFactIdx -1); attribute any executable
// calls in its body to the file-scope ref fact via bodyCallOwner.
if owner := w.bodyCallOwner(); owner >= 0 {
w.walkScopeForCalls(body, owner, map[string]bool{}, nil)
}
w.pop()
}
// --- methods ---
func (w *rubyWalker) handleMethod(node *sitter.Node, isClassMethod bool) {
name := rubyText(node.ChildByFieldName("name"), w.src)
if name == "" {
return
}
// An instance method (`def foo`, not `def self.x`) directly in a module body
// marks that module as a mixin — behavior meant to be included into another
// type — which makes it abstract for package metrics. Fetch the scope fresh:
// push() can reallocate scopeStack, so a cached pointer would be stale.
if !isClassMethod {
if s := w.cur(); s != nil && s.kind == "module" {
s.hasInstanceMethod = true
}
}
scope := w.scopeQual()
var fullName string
switch {
case scope == "":
fullName = w.dir + "." + name
case isClassMethod:
fullName = scope + "." + name
default:
fullName = scope + "#" + name
}
symbolKind := facts.SymbolMethod
if isClassMethod {
symbolKind = facts.SymbolFunc
}
props := map[string]any{
"symbol_kind": symbolKind,
"exported": w.exported(),
"language": "ruby",
}
if w.isRails {
props["framework"] = "rails"
}
w.out = append(w.out, facts.Fact{
Kind: facts.KindSymbol,
Name: fullName,
File: w.relFile,
Line: line(node),
Props: props,
Relations: []facts.Relation{{Kind: facts.RelDeclares, Target: w.dir}},
})
ownerIdx := len(w.out) - 1
// Accumulate RelCalls from the body onto this method (deduplicated), while
// computing complexity metrics in the same walk. The props map is shared by
// reference with the fact just appended, so writing to it after the walk
// updates the emitted fact.
seen := make(map[string]bool)
locals := collectLocals(node, w.src)
// The method scope (parameters + body) gates interpolated-string prefixes: reset
// the tentative state before the walks and commit after (see commitPendingStrPrefixes).
w.pendingStrPrefixes = nil
w.sawDispatcher = false
// Default parameter values (`def f(x = self.class.foo)`) contain real call
// references. Walk them with metrics off (params are not the body, so they must
// not affect the complexity score); seen is shared so body calls still dedup.
w.walkForCalls(node.ChildByFieldName("parameters"), ownerIdx, seen, locals)
w.metrics = &rubyBodyMetrics{}
w.loopDepth = 0
w.selfName = fullName
w.selfShort = name
w.walkForCalls(node.ChildByFieldName("body"), ownerIdx, seen, locals)
props["cyclomatic"] = 1 + w.metrics.decisions
if w.metrics.loopDepth > 0 {
props["loop_depth"] = w.metrics.loopDepth
}
if w.metrics.loopCount > 0 {
props["loop_count"] = w.metrics.loopCount
}
if len(w.metrics.callsInLoop) > 0 {
props["calls_in_loop"] = w.metrics.callsInLoop
}
if w.metrics.recursive {
props["recursive_self"] = true
}
w.metrics = nil
w.commitPendingStrPrefixes()
}
// isClassHoldingReceiver reports whether a call receiver is a variable named by the
// Ruby idiom for a Class object (`klass`/`clazz`/`klazz`, plain or instance var). A
// method call on such a receiver is a class-method dispatch (`klass.inline`), not an
// attribute read, so it is recorded regardless of the method name.
func isClassHoldingReceiver(recv *sitter.Node, src []byte) bool {
if recv == nil {
return false
}
switch recv.Kind() {
case "identifier", "instance_variable":
switch rubyText(recv, src) {
case "klass", "clazz", "klazz", "@klass", "@clazz", "@klazz":
return true
}
}
return false
}
// isVarReceiver reports whether a call receiver node kind is a simple variable
// reference — a local/method identifier or an instance/class/global variable.
// A no-arg, underscored call on such a receiver (`items.preload_relations`,
// `@klass.bo_search_fields`) is a scope/class-method invocation, not an attribute
// read, so it is recorded as a reference.
func isVarReceiver(kind string) bool {
switch kind {
case "identifier", "instance_variable", "class_variable", "global_variable":
return true
}
return false
}
// constantBoundReceiver reports whether an iterator's receiver is provably bounded by
// a compile-time constant, so the loop runs a fixed number of times regardless of the
// method's input (O(1) in n): an integer literal (`6.times`), a collection literal
// (`[…].each`, `{…}.each`, `%w[…]`, `%i[…]`), or an ALL-CAPS data constant
// (`STOP_CHARS.any?`). Mixed-case constants (classes like `User`) are excluded — a
// `.each` on a class/relation is not a bounded literal.
func constantBoundReceiver(recv *sitter.Node, src []byte) bool {
if recv == nil {
return false
}
switch recv.Kind() {
case "integer", "array", "hash", "string_array", "symbol_array":
return true
case "constant":
return isScreamingSnake(rubyText(recv, src))
case "call":
// A trailing size-preserving/reducing chain method keeps a bounded base
// bounded: `[a,b].compact.all?`, `%w[x y].map { … }.each`. Unwrap it and
// re-check the inner receiver. Size-expanding ops (product/cycle/flat_map)
// are excluded, so this never turns an unbounded source into "bounded".
if m := recv.ChildByFieldName("method"); m != nil && chainPreservesBound[rubyText(m, src)] {
return constantBoundReceiver(recv.ChildByFieldName("receiver"), src)
}
}
return false
}
// chainPreservesBound are Enumerable methods that never grow a collection beyond its
// input size, so a bounded literal/constant piped through them stays bounded.
var chainPreservesBound = map[string]bool{
"compact": true, "uniq": true, "flatten": true, "sort": true, "sort_by": true,
"reverse": true, "to_a": true, "dup": true, "freeze": true,
"map": true, "collect": true, "select": true, "filter": true, "reject": true,
"first": true, "take": true,
}
// isScreamingSnake reports whether s is a SCREAMING_SNAKE_CASE data constant — only
// uppercase letters, digits, and underscores, with at least one letter.
func isScreamingSnake(s string) bool {
hasLetter := false
for _, r := range s {
switch {
case r >= 'A' && r <= 'Z':
hasLetter = true
case r >= '0' && r <= '9', r == '_':
default:
return false
}
}
return hasLetter
}
// walkScopeForCalls runs walkForCalls over one scope (a class/module body or the
// top-level program) with the per-scope interpolated-string-prefix gate: it resets
// the tentative state, walks, then commits any pending string prefixes iff the scope
// invoked a dispatcher. (Method bodies are gated inline in handleMethod, which spans
// the parameter + body walks.)
func (w *rubyWalker) walkScopeForCalls(node *sitter.Node, ownerIdx int, seen, locals map[string]bool) {
w.pendingStrPrefixes = nil
w.sawDispatcher = false
w.walkForCalls(node, ownerIdx, seen, locals)
w.commitPendingStrPrefixes()
}
// commitPendingStrPrefixes promotes the tentative interpolated-string dispatch
// prefixes gathered in the current scope into the committed set — but only if the
// scope also invoked a dispatcher (send/public_send/…). Then it clears the per-scope
// state. This keeps `"present_#{idx}"` (in a method that calls send) while dropping
// cache/Redis key strings like `"fetch_#{id}"` in non-dispatching methods.
func (w *rubyWalker) commitPendingStrPrefixes() {
if w.sawDispatcher {
for p := range w.pendingStrPrefixes {
if w.dynamicPrefixes == nil {
w.dynamicPrefixes = map[string]bool{}
}
w.dynamicPrefixes[p] = true
}
}
w.pendingStrPrefixes = nil
w.sawDispatcher = false
}
// walkForCalls recursively scans a method body for call expressions and appends
// RelCalls edges to the owner fact. It does not descend into nested
// method/class/module definitions — those receive their own owner.
//
// Four reference shapes are captured: (1) qualified calls via callTarget
// ("Const.method", "var.method"); (2) bare calls with a method name but no
// receiver ("render :x", "helper(arg)") → the bare method name; (3) lone
// identifiers in expression position ("current_user") that are not known locals
// → the bare name; (4) bare constant references ("MyJob", "Chat::Message") used
// as values → the constant name. (2) and (3) are why Ruby methods invoked without
// a receiver (the common Rails case) are recorded as referenced; (4) is why a
// class/module used only as a value (registered, passed as an argument, matched in
// case/when) is. Bare targets — from (2), (3) and (4) — carry no ".", so
// constFromCall ignores them and the package-metrics coupling graph (which keys
// off "Recv.method" constant receivers) is unaffected.
func (w *rubyWalker) walkForCalls(node *sitter.Node, ownerIdx int, seen, locals map[string]bool) {
if node == nil {
return
}
// Skip anonymous tokens (keywords/operators/punctuation). They are childless
// leaves, and critically the keyword token for a statement shares its Kind
// (e.g. the `while`/`if` keyword reports Kind "while"/"if"), which would
// otherwise double-count loops and decisions below.
if !node.IsNamed() {
return
}
// Complexity metrics: count decision points so the single body walk doubles
// as the cyclomatic pass. `case` itself is not counted (each `when` branch is);
// loop constructs are counted in their own handling below.
if w.metrics != nil {
switch node.Kind() {
case "if", "elsif", "unless", "if_modifier", "unless_modifier",
"when", "rescue", "conditional":
w.metrics.decisions++
}
}
switch node.Kind() {
case "method", "singleton_method", "class", "module", "singleton_class":
return
case "super":
// `super` invokes the same-named method in an ancestor (superclass or mixin),
// so it references that base method. Only meaningful inside a method body
// (metrics != nil), where selfShort is the enclosing method's bare name.
// Record the call edge (dead-code marks the ancestor method used) but NOT the
// complexity metrics: `super` climbs the inheritance chain and terminates —
// it is not self-recursion, and treating it as such was the dominant recursion
// false positive (every override with a `super` call). Recurse afterwards to
// capture any calls in `super(args)`.
if w.metrics != nil && w.selfShort != "" {
w.addCall(ownerIdx, seen, w.selfShort)
}
for i := uint(0); i < node.ChildCount(); i++ {
w.walkForCalls(node.Child(i), ownerIdx, seen, locals)
}
return
case "while", "until", "for", "while_modifier", "until_modifier":
// Syntactic loops: everything in the body runs per iteration.
if w.metrics != nil {
w.metrics.loopCount++
w.metrics.decisions++
if w.loopDepth+1 > w.metrics.loopDepth {
w.metrics.loopDepth = w.loopDepth + 1
}
}
w.loopDepth++
for i := uint(0); i < node.ChildCount(); i++ {
w.walkForCalls(node.Child(i), ownerIdx, seen, locals)
}
w.loopDepth--
return
case "call":
method := node.ChildByFieldName("method")
recv := node.ChildByFieldName("receiver")
// Dynamic dispatch by LITERAL name — `obj.try(:foo)`, `send(:bar)`,
// `respond_to?(:baz)` — names the target method exactly, so record it as a
// call. Safe-nav `&.try` still exposes the `method` child. Distinct from an
// interpolated symbol (`:"report_#{x}"`), which is only a prefix hint.
if method != nil && rubyDispatchers[rubyText(method, w.src)] {
w.sawDispatcher = true // gates tentative interpolated-string prefixes
if nm := dispatchSymbolArg(node.ChildByFieldName("arguments"), w.src); nm != "" {
w.addCall(ownerIdx, seen, nm)
// `obj.try(:foo)` dispatches to a DIFFERENT object; only a
// receiverless/self dispatch (`send(:foo)`, `self.try(:foo)`) can recurse.
w.recordSelfAwareMetrics(nm, recv)
}
}
if target := w.callTarget(node); target != "" {
w.addCall(ownerIdx, seen, target)
// Recursion only for a same-object self dispatch. callTarget returns a bare
// method name for both plain `self.foo` (recv kind "self" — genuine
// recursion) and `self.class.foo` (recv kind "call" — the instance method
// calling its sibling CLASS method, NOT recursion), so the target string
// alone can't tell them apart; gate on the receiver. An explicit
// `Const.foo` that resolves to this exact method (selfName) is real
// class-method self-recursion and is preserved.
if target == w.selfName {
w.recordCallMetrics(target)
} else {
w.recordSelfAwareMetrics(target, recv)
}
} else if recv == nil && method != nil && method.Kind() == "identifier" {
if name := rubyText(method, w.src); !rubyNonCalls[name] {
w.addCall(ownerIdx, seen, name)
w.recordCallMetrics(name)
}
} else if recv != nil && method != nil && method.Kind() == "identifier" {
// A no-arg call on a receiver that callTarget suppressed. Bare target
// (no ".") -> no coupling impact. Skip keywords and common
// attribute/enumerable reads so a dead method sharing a name with
// `.name`/`.count`/`.first` isn't hidden.
name := rubyText(method, w.src)
switch {
case rubyNonCalls[name] || rubyCheapMethods[name]:
// keyword / cheap attribute-or-enumerable read — ignore
case recv.Kind() == "call" || strings.HasSuffix(name, "?") || strings.HasSuffix(name, "!") ||
(isVarReceiver(recv.Kind()) && strings.Contains(name, "_")) ||
isClassHoldingReceiver(recv, w.src):
// Chained receiver (ActiveRecord scope / class-method chains
// `Model.scope1.scope2.final`, `assoc.class_method`, `x.class.method`),
// a predicate/bang call on ANY receiver (`viewer.rich?`, `x.save!`), OR a
// call on a variable receiver — a local, a bare method, or an
// instance/class/global variable (`@klass.bo_search_fields`) — whose name
// is scope/class-method-like (has `_`) — e.g.
// `items.preload_relations`, `some_relation.pluck_job_id`. All are
// unambiguously method calls (an attribute read never ends in `?`/`!`,
// and a snake_case multi-word name is a scope/class-method, not a plain
// attribute). Single-word reads (`user.email`, `x.name`) stay out.
//
// Record the call edge and (if in a loop) the in-loop N+1 signal, but
// NOT recursion: this branch always has an explicit, non-self receiver
// (self-receiver calls resolve via callTarget above), so a call whose
// name matches the enclosing method is a same-named call on a DIFFERENT
// object — the SimpleDelegator/decorator pattern (`@delegate.render`,
// `new.call`), not self-recursion.
w.addCall(ownerIdx, seen, name)
w.recordInLoopCall(name)
case w.loopDepth > 0:
// A no-arg single-level read inside a loop (the association read
// `u.posts` or `record.reload`). It is not a graph edge, but its method
// name feeds the perf metric so the enterprise analyzer can flag
// lazy-loaded association / per-iteration I/O (N+1).
w.recordInLoopCall(name)
}
}
// An iterator method with a block (users.each { … }, n.times { … }) is a
// loop: its block body runs per element, but the receiver and arguments
// are evaluated once — so only the block child walks at +1 depth (mirrors
// the Python comprehension handling).
block := node.ChildByFieldName("block")
isIter := block != nil && method != nil && rubyIterators[rubyText(method, w.src)]
// A constant-bounded iterator (`6.times`, `[…].each`, `STOP_CHARS.any?`) runs a
// fixed number of times regardless of the method's input, so it still counts as
// a loop (cyclomatic) but must not add scaling loop DEPTH — otherwise a literal
// or constant inner/outer loop inflates a genuine O(n) into a false O(n²)/O(n³).
bounded := isIter && constantBoundReceiver(recv, w.src)
if isIter && w.metrics != nil {
w.metrics.loopCount++
w.metrics.decisions++
if !bounded && w.loopDepth+1 > w.metrics.loopDepth {
w.metrics.loopDepth = w.loopDepth + 1
}
}
// Recurse into every child EXCEPT the callee `method` child, which has
// already been consumed above (otherwise it would be re-counted by the
// bare-identifier case below).
for i := uint(0); i < node.ChildCount(); i++ {
c := node.Child(i)
if method != nil && c.StartByte() == method.StartByte() && c.EndByte() == method.EndByte() {
continue
}
if isIter && c.StartByte() == block.StartByte() && c.EndByte() == block.EndByte() {
if bounded {
// Fixed iteration count: walk the block at the SAME depth so any
// inner scaling loop or per-iteration I/O is measured against the
// real input, not multiplied by a constant.
w.walkForCalls(c, ownerIdx, seen, locals)
continue
}
w.loopDepth++
w.walkForCalls(c, ownerIdx, seen, locals)
w.loopDepth--
continue
}
w.walkForCalls(c, ownerIdx, seen, locals)
}
return
case "identifier":
// A bare identifier outside callee position: either an arg-less method
// call or a local variable read. Emit unless it is a known local or a
// keyword/builtin; matching is conservative so over-emitting is safe.
if name := rubyText(node, w.src); name != "" && !locals[name] && !rubyNonCalls[name] {
w.addCall(ownerIdx, seen, name)
w.recordCallMetrics(name)
}
return
case "constant", "scope_resolution":
// A bare constant reference in expression position — an argument
// (register(MyJob)), array/hash element, case/when or rescue clause,
// assignment RHS, or a lone `Foo` value. It is NOT a `Const.method` call
// (that is captured as the receiver via callTarget above) and NOT a
// definition name (handleClass/handleModule consume those), so without this
// a class/module used only as a value looks unreferenced and is mis-reported
// as dead. Record it as a use of that constant. The target carries no ".",
// so constFromCall ignores it and the package-metrics coupling graph is
// unaffected; it is not a method invocation, so perf metrics are untouched.
// scope_resolution is recorded whole (e.g. "Chat::Message") and not
// descended into, so the qualified path is matched rather than its segments.
if name := stripLeadingColons(rubyText(node, w.src)); name != "" && !rubyBuiltinConsts[name] {
w.addCall(ownerIdx, seen, name)
}
return
case "delimited_symbol":
// An interpolated symbol `:"report_#{type}"` — a method name computed for
// dynamic dispatch (public_send/send). Record its static prefix so the
// dead-code detector treats same-prefix methods as used. Symbols are captured
// unconditionally (they are almost always method names). Fall through to
// recurse: the interpolation may itself contain real calls.
if p := dynamicSymbolPrefix(node, w.src); p != "" {
if w.dynamicPrefixes == nil {
w.dynamicPrefixes = map[string]bool{}
}
w.dynamicPrefixes[p] = true
}
case "string":
// An interpolated string `"present_#{idx}"` may be a computed dispatch name
// too, but snake_case strings are commonly cache/Redis keys — so record its
// prefix only TENTATIVELY, committed after the scope walk iff the scope also
// invokes a dispatcher (see commitPendingStrPrefixes). Recurse for nested calls.
if p := dynamicSymbolPrefix(node, w.src); p != "" {
if w.pendingStrPrefixes == nil {
w.pendingStrPrefixes = map[string]bool{}
}
w.pendingStrPrefixes[p] = true
}
}
for i := uint(0); i < node.ChildCount(); i++ {
w.walkForCalls(node.Child(i), ownerIdx, seen, locals)
}
}
// dynamicSymbolPrefix returns the static literal prefix of an interpolated symbol
// node (`:"report_#{type}"` -> "report_"), or "" when the node is not an
// interpolated symbol or the prefix is not specific enough to be a useful dispatch
// hint. The prefix is the string_content preceding the FIRST interpolation; it
// qualifies only when at least one interpolation is present and the prefix is >= 4
// chars ending in "_" (a word boundary), so generic 1-2 char stems don't over-match.
func dynamicSymbolPrefix(node *sitter.Node, src []byte) string {
var prefix strings.Builder
sawInterp := false
for i := uint(0); i < node.ChildCount(); i++ {
c := node.Child(i)
switch c.Kind() {
case "interpolation":
sawInterp = true
i = node.ChildCount() // stop at the first interpolation
case "string_content":
prefix.WriteString(rubyText(c, src))
}
}
if !sawInterp {
return ""
}
p := prefix.String()
if len(p) >= 4 && strings.HasSuffix(p, "_") {
return p
}
return ""
}
// rubyDispatchers are methods that invoke (or reference) another method named by
// their first argument: `obj.try(:foo)`, `send(:bar)`, `respond_to?(:baz)`,
// `method(:qux)`. When that argument is a LITERAL symbol/string the target method
// is statically known, so it is recorded as a call.
var rubyDispatchers = map[string]bool{
"send": true, "public_send": true, "__send__": true,
"try": true, "try!": true, "respond_to?": true,
"method": true, "public_method": true,
}
// dispatchSymbolArg returns the method name named by the first argument of a
// dispatcher call (`:foo` -> "foo", "foo" -> "foo"), or "" when the first argument
// is not a literal symbol / static string (e.g. a variable or interpolated value).
func dispatchSymbolArg(args *sitter.Node, src []byte) string {
if args == nil {
return ""
}
for i := uint(0); i < args.ChildCount(); i++ {
c := args.Child(i)
if !c.IsNamed() {
continue
}
switch c.Kind() {
case "simple_symbol":
return strings.TrimPrefix(rubyText(c, src), ":")
case "string":
// Static string only (no interpolation): the literal is the method name.
for j := uint(0); j < c.ChildCount(); j++ {
if c.Child(j).Kind() == "interpolation" {
return ""
}
}
return stringLiteralContent(c, src)
}