reference-query 0.50.1

Reference Query — find the code you're looking for.
Documentation
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
//! Ruby plugin — the first language.
//!
//! Extracts classes, modules, methods (instance and singleton), and constants
//! via Tree-sitter. `parent` carries the enclosing qualified name so a method
//! renders as `Foo::Bar#baz` and a nested class as `Foo::Bar`.

use tree_sitter::Node;

use crate::core::{Kind, Symbol};
use crate::lang::{Ctx, LanguagePlugin, extract_with, qualify};

const LANGUAGE: &str = "ruby";

pub(crate) struct Ruby;

impl LanguagePlugin for Ruby {
    fn language(&self) -> &'static str {
        LANGUAGE
    }

    fn extensions(&self) -> &[&str] {
        &["rb"]
    }

    fn extract(&self, file: &str, source: &str) -> Vec<Symbol> {
        extract_with(
            LANGUAGE,
            tree_sitter_ruby::LANGUAGE.into(),
            file,
            source,
            |ctx, root, out| walk(ctx, root, None, "public", out),
        )
    }
}

/// Recursively collect definitions. `parent` is the enclosing qualified name;
/// `vis` is the access section in effect (a bare `private`/`protected`/`public`
/// marker flips it for everything after, including through wrapping nodes like
/// `private def foo`).
fn walk(ctx: &Ctx, node: Node, parent: Option<&str>, vis: &'static str, out: &mut Vec<Symbol>) {
    let mut vis = vis;
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        match child.kind() {
            "class" | "module" => {
                let kind = if child.kind() == "class" {
                    Kind::Class
                } else {
                    Kind::Module
                };
                if let Some(name) = ctx.field_text(child, "name") {
                    // a compact definition (`class A::B::C`) names the leaf `C`
                    // with `A::B` folded into the parent — same shape as the
                    // nested `module A; module B; class C` form, so the class
                    // is found by its leaf name either way
                    let (leaf, effective_parent) = leaf_and_parent(&name, parent);
                    let mut s = ctx.symbol(leaf, kind, child, effective_parent.as_deref());
                    s.visibility = Some("public");
                    out.push(s);
                    let qualified = qualify(effective_parent.as_deref(), leaf, "::");
                    // a fresh body starts a fresh (public) access section
                    walk(ctx, child, Some(&qualified), "public", out);
                } else {
                    walk(ctx, child, parent, vis, out);
                }
            }
            "method" | "singleton_method" => {
                if let Some(name) = ctx.field_text(child, "name") {
                    let mut s = ctx.symbol(&name, Kind::Method, child, parent);
                    // `private` sections don't apply to `def self.x`
                    s.visibility = Some(if child.kind() == "singleton_method" {
                        "public"
                    } else {
                        vis
                    });
                    out.push(s);
                }
                // method bodies rarely hold further definitions; don't recurse.
            }
            "alias" => {
                // `alias new old` — the keyword form of alias_method; a
                // global-variable alias (`alias $a $b`) defines no method
                if let Some(name) = ctx.field_text(child, "name")
                    && !name.starts_with('$')
                {
                    let mut s =
                        ctx.symbol(name.trim_start_matches(':'), Kind::Method, child, parent);
                    s.visibility = Some(vis);
                    out.push(s);
                }
            }
            "assignment" | "operator_assignment" => {
                // `CONST = …`, `Foo::BAR = …`, `A, B = …`, `RETRIES ||= …`
                // define constants; the right side can hold definitions too
                // (`Foo = Class.new do … end`)
                if let Some(left) = child.child_by_field_name("left") {
                    constants(ctx, left, child, parent, out);
                }
                walk(ctx, child, parent, vis, out);
            }
            // a bare access marker flips the section for what follows
            "identifier" => match ctx.node_text(child).as_deref() {
                Some("private") => vis = "private",
                Some("protected") => vis = "protected",
                Some("public") => vis = "public",
                _ => {}
            },
            "call" => {
                // metaprogramming: `attr_accessor :x`, `has_many :users`, … are
                // calls that *define* methods Tree-sitter can't see as defs.
                // Emit the literal names, pointing at the macro's line.
                dsl_symbols(ctx, child, parent, vis, out);
                // still recurse: a call can wrap real definitions
                // (`private def foo` — its `private` identifier flips `vis`
                // on the way down — or `Class.new do … end`)
                walk(ctx, child, parent, vis, out);
            }
            _ => walk(ctx, child, parent, vis, out),
        }
    }
}

/// How many of a DSL macro's arguments name methods it defines.
enum DslArgs {
    /// Every literal argument (`attr_accessor :a, :b`, `delegate :x, :y, to:`).
    All,
    /// Only the first (`define_method(:x)`, `scope :active`, `has_many :users`).
    First,
}

/// The method-defining macro vocabulary: Ruby core plus the everyday Rails
/// surface. Deliberately small — literal, high-confidence definitions only.
///
/// `field` earns its place the same way `has_many` does: it's the declaration
/// that defines the member, across several schema DSLs (graphql-ruby, Mongoid,
/// dry-types). Without it, a field declared `field :email, String` has no
/// definition to navigate to at all — the receiver form (`f.field :email`, a
/// form builder) is already excluded, which is where the name would otherwise
/// be ambiguous.
fn dsl_args(method: &str) -> Option<DslArgs> {
    match method {
        // `attr`'s optional boolean tail (`attr :x, true`) is skipped by the
        // literal-name filter, so All is safe for it too
        "attr" | "attr_accessor" | "attr_reader" | "attr_writer" | "delegate" => Some(DslArgs::All),
        "define_method" | "alias_method" | "scope" | "has_many" | "has_one" | "belongs_to"
        | "field" => Some(DslArgs::First),
        _ => None,
    }
}

/// Emit method symbols for a metaprogramming call: `attr_accessor :balance`
/// defines `balance` even though no `def` exists. Only *literal* symbol/string
/// arguments count — a computed name (`define_method(name)`) is unresolvable
/// statically, so it's skipped rather than guessed. Keyword arguments
/// (`delegate …, to: :owner`) are `pair` nodes and naturally excluded.
fn dsl_symbols(
    ctx: &Ctx,
    call: Node,
    parent: Option<&str>,
    vis: &'static str,
    out: &mut Vec<Symbol>,
) {
    if call.child_by_field_name("receiver").is_some() {
        return; // `Foo.attr_accessor` isn't the macro form we index
    }
    let Some(method) = ctx.field_text(call, "method") else {
        return;
    };
    let Some(args) = dsl_args(&method) else {
        return;
    };
    let Some(arg_list) = call.child_by_field_name("arguments") else {
        return;
    };
    let mut cursor = arg_list.walk();
    for arg in arg_list.children(&mut cursor) {
        if !arg.is_named() {
            continue; // parens and commas
        }
        if let Some(name) = literal_name(ctx, arg)
            && !name.is_empty()
        {
            let mut s = ctx.symbol(&name, Kind::Method, call, parent);
            s.visibility = Some(vis);
            out.push(s);
        }
        if matches!(args, DslArgs::First) {
            break; // later args are options (`scope :active, -> {…}`), not names
        }
    }
}

/// The name a literal `:symbol` or `"string"` argument carries, if any.
fn literal_name(ctx: &Ctx, node: Node) -> Option<String> {
    match node.kind() {
        "simple_symbol" => ctx
            .node_text(node)
            .map(|t| t.trim_start_matches(':').to_string()),
        "string" => ctx
            .node_text(node)
            .map(|t| t.trim_matches(|c| c == '"' || c == '\'').to_string()),
        _ => None,
    }
}

/// Emit constant symbols for an assignment's left side: a bare `CONST`, a
/// qualified `Foo::BAR`, or each constant in a multi-assignment list. Always
/// public — method visibility sections never apply to constants, and the
/// retroactive `private_constant` is out of static reach.
fn constants(ctx: &Ctx, left: Node, def: Node, parent: Option<&str>, out: &mut Vec<Symbol>) {
    match left.kind() {
        "constant" | "scope_resolution" => {
            if let Some(name) = ctx.node_text(left) {
                let (leaf, effective_parent) = leaf_and_parent(&name, parent);
                // a scope_resolution leaf can be lowercase (`Foo::bar = 1` is a
                // setter call, not a constant)
                if leaf.starts_with(char::is_uppercase) {
                    let mut s = ctx.symbol(leaf, Kind::Constant, def, effective_parent.as_deref());
                    s.visibility = Some("public");
                    out.push(s);
                }
            }
        }
        "left_assignment_list" => {
            let mut cursor = left.walk();
            for item in left.children(&mut cursor) {
                constants(ctx, item, def, parent, out);
            }
        }
        _ => {}
    }
}

/// Resolve a definition name that may be compact-qualified (`A::B::C`) or
/// rooted (`::Foo`) to its leaf plus the parent it belongs under. A compact
/// name folds its prefix into the parent — same shape as the nested form, so
/// the definition is found by its leaf name either way; a rooted name lives at
/// the top level, ignoring lexical nesting.
fn leaf_and_parent<'a>(name: &'a str, parent: Option<&str>) -> (&'a str, Option<String>) {
    let (name, rooted) = match name.strip_prefix("::") {
        Some(rest) => (rest, true),
        None => (name, false),
    };
    let (leaf, prefix) = split_qualified(name);
    let effective_parent = if rooted {
        prefix.map(str::to_string)
    } else {
        match prefix {
            Some(p) => Some(qualify(parent, p, "::")),
            None => parent.map(str::to_string),
        }
    };
    (leaf, effective_parent)
}

/// Split a possibly compact-qualified definition name (`A::B::C`) into its leaf
/// (`C`) and namespace prefix (`A::B`). A plain name has no prefix. Callers
/// strip a rooted `::` before splitting.
fn split_qualified(name: &str) -> (&str, Option<&str>) {
    match name.rfind("::") {
        Some(i) => {
            let prefix = &name[..i];
            (&name[i + 2..], (!prefix.is_empty()).then_some(prefix))
        }
        None => (name, None),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn extract(source: &str) -> Vec<Symbol> {
        Ruby.extract("test.rb", source)
    }

    fn find<'a>(syms: &'a [Symbol], name: &str) -> &'a Symbol {
        syms.iter()
            .find(|s| s.name == name)
            .unwrap_or_else(|| panic!("no symbol named {name} in {syms:?}"))
    }

    #[test]
    fn extracts_class_module_and_methods_with_nesting() {
        let src = r#"
module Billing
  class RefundProcessor
    def perform
    end

    def self.build
    end
  end
end
"#;
        let syms = extract(src);

        let module = find(&syms, "Billing");
        assert_eq!(module.kind, Kind::Module);
        assert_eq!(module.parent, None);
        assert_eq!(module.line, 2);
        // end_line spans the whole body to the matching `end`
        assert_eq!(module.end_line, 10);

        let class = find(&syms, "RefundProcessor");
        assert_eq!(class.kind, Kind::Class);
        assert_eq!(class.parent.as_deref(), Some("Billing"));

        let perform = find(&syms, "perform");
        assert_eq!(perform.kind, Kind::Method);
        assert_eq!(perform.parent.as_deref(), Some("Billing::RefundProcessor"));
        // the method body is lines 4..=5 (`def perform` through its `end`)
        assert_eq!((perform.line, perform.end_line), (4, 5));

        // singleton method (def self.build) is captured too
        let build = find(&syms, "build");
        assert_eq!(build.kind, Kind::Method);
        assert_eq!(build.parent.as_deref(), Some("Billing::RefundProcessor"));
    }

    #[test]
    fn compact_namespace_is_split_into_leaf_and_parent() {
        // `class A::B::C` names the leaf `C`, with `A::B` folded into the parent —
        // so it's found by its leaf name just like the nested form, and a method
        // inside it still qualifies fully
        let src = "class My::Module::EmployeesController\n  def index\n  end\nend\n";
        let syms = extract(src);

        let class = find(&syms, "EmployeesController");
        assert_eq!(class.kind, Kind::Class);
        assert_eq!(class.parent.as_deref(), Some("My::Module"));

        let index = find(&syms, "index");
        assert_eq!(
            index.parent.as_deref(),
            Some("My::Module::EmployeesController")
        );
    }

    #[test]
    fn metaprogramming_macros_define_methods() {
        let src = r#"
class Account
  attr_accessor :balance, :currency
  attr_reader "label"
  has_many :transactions, dependent: :destroy
  scope :active, -> { where(active: true) }
  delegate :name, :email, to: :owner, prefix: true
  define_method(:refresh!) { reload }
  alias_method :bal, :balance
end
"#;
        let syms = extract(src);

        for name in [
            "balance",
            "currency",
            "label",
            "transactions",
            "active",
            "name",
            "email",
            "refresh!",
            "bal",
        ] {
            let s = find(&syms, name);
            assert_eq!(s.kind, Kind::Method, "{name} is a method");
            assert_eq!(s.parent.as_deref(), Some("Account"), "{name} in Account");
        }

        // option arguments never become symbols
        for non_name in ["destroy", "owner", "dependent", "to", "prefix", "where"] {
            assert!(
                !syms.iter().any(|s| s.name == non_name),
                "{non_name} is an option, not a defined method: {syms:?}"
            );
        }
    }

    #[test]
    fn schema_dsl_field_declarations_define_methods() {
        let src = r#"
module Types
  class UserType < Types::BaseObject
    field :id, ID, null: false
    field :email, String, null: true
    field :posts, [Types::PostType], null: false do
      argument :first, Integer, required: false
    end

    def posts(first: nil)
      object.posts.limit(first)
    end
  end
end
"#;
        let syms = extract(src);

        for name in ["id", "email", "posts"] {
            let s = find(&syms, name);
            assert_eq!(s.kind, Kind::Method, "{name} is a method");
            assert_eq!(
                s.parent.as_deref(),
                Some("Types::UserType"),
                "{name} in UserType"
            );
        }
        // the block form declares `posts` once as a field and once as a real
        // `def`; both are definitions of the same member, and both are indexed
        assert_eq!(
            syms.iter().filter(|s| s.name == "posts").count(),
            2,
            "{syms:?}"
        );
        // type arguments and options are not members
        for non_name in ["ID", "String", "null", "required", "first"] {
            assert!(
                !syms.iter().any(|s| s.name == non_name),
                "{non_name} is not a defined method: {syms:?}"
            );
        }
    }

    #[test]
    fn alias_keyword_defines_the_new_name() {
        let src = r#"
class Foo
  def bar
  end

  alias baz bar
  alias :qux :bar
  alias $copy $orig
end
"#;
        let syms = extract(src);
        for name in ["baz", "qux"] {
            let s = find(&syms, name);
            assert_eq!(s.kind, Kind::Method, "{name} is a method");
            assert_eq!(s.parent.as_deref(), Some("Foo"));
        }
        // a global-variable alias defines no method
        assert!(!syms.iter().any(|s| s.name.contains("copy")), "{syms:?}");
    }

    #[test]
    fn bare_attr_defines_readers() {
        let src = "class Foo\n  attr :size, :color\n  attr :flag, true\nend\n";
        let syms = extract(src);
        for name in ["size", "color", "flag"] {
            assert_eq!(find(&syms, name).kind, Kind::Method, "{name}");
        }
        // the boolean writer switch is an option, not a name
        assert_eq!(syms.len(), 4, "{syms:?}");
    }

    #[test]
    fn rooted_definition_resets_to_top_level() {
        // `class ::Bar` inside a module defines top-level `Bar`, not `Foo::Bar`
        let src = "module Foo\n  class ::Bar\n  end\n  class ::Baz::Qux\n  end\nend\n";
        let syms = extract(src);
        assert_eq!(find(&syms, "Bar").parent, None);
        assert_eq!(find(&syms, "Qux").parent.as_deref(), Some("Baz"));
    }

    #[test]
    fn singleton_class_methods_belong_to_the_class() {
        let src = r#"
class Foo
  class << self
    def build
    end

    private

    def hidden
    end
  end
end
"#;
        let syms = extract(src);
        let build = find(&syms, "build");
        assert_eq!(build.parent.as_deref(), Some("Foo"));
        assert_eq!(build.visibility, Some("public"));
        // unlike `def self.x`, visibility applies inside `class << self`
        assert_eq!(find(&syms, "hidden").visibility, Some("private"));
    }

    #[test]
    fn constant_assignments_are_indexed() {
        let src = r#"
module Config
  LIMIT = 10
  Names::DEFAULT = "x"
  ::ROOT = 1
  A, B = 1, 2
  RETRIES ||= 3

  private

  SECRET = 4
end
Version = Struct.new(:major)
"#;
        let syms = extract(src);
        let limit = find(&syms, "LIMIT");
        assert_eq!(limit.kind, Kind::Constant);
        assert_eq!(limit.parent.as_deref(), Some("Config"));
        // qualified and rooted lefts resolve like compact class definitions
        assert_eq!(
            find(&syms, "DEFAULT").parent.as_deref(),
            Some("Config::Names")
        );
        assert_eq!(find(&syms, "ROOT").parent, None);
        for name in ["A", "B", "RETRIES"] {
            assert_eq!(find(&syms, name).kind, Kind::Constant, "{name}");
        }
        // method visibility sections don't apply to constants
        assert_eq!(find(&syms, "SECRET").visibility, Some("public"));
        // an anonymous class is at least findable by the constant naming it
        assert_eq!(find(&syms, "Version").kind, Kind::Constant);
    }

    #[test]
    fn computed_and_received_macro_names_are_skipped() {
        let src = r#"
class Widget
  define_method(dynamic_name) { }
  Other.attr_accessor :not_ours
  form.field :not_ours_either
end
"#;
        let syms = extract(src);
        // only the class itself — no guessed names, no receiver-form macros
        assert_eq!(syms.len(), 1, "{syms:?}");
        assert_eq!(syms[0].name, "Widget");
    }

    #[test]
    fn a_def_wrapped_in_a_visibility_call_is_still_found() {
        let src = "class Widget\n  private def hidden\n  end\nend\n";
        let syms = extract(src);
        let hidden = find(&syms, "hidden");
        assert_eq!(hidden.kind, Kind::Method);
        assert_eq!(hidden.parent.as_deref(), Some("Widget"));
        assert_eq!(hidden.visibility, Some("private"));
    }

    #[test]
    fn access_sections_set_visibility() {
        let src = r#"
class Widget
  def open_api
  end

  private

  def internal
  end
  attr_reader :secret

  public

  def reopened
  end
end
"#;
        let syms = extract(src);
        assert_eq!(find(&syms, "open_api").visibility, Some("public"));
        assert_eq!(find(&syms, "internal").visibility, Some("private"));
        // a macro under `private` defines private methods too
        assert_eq!(find(&syms, "secret").visibility, Some("private"));
        assert_eq!(find(&syms, "reopened").visibility, Some("public"));
    }

    #[test]
    fn empty_and_unparseable_yield_no_symbols() {
        assert!(extract("").is_empty());
        assert!(extract("# just a comment\n").is_empty());
    }

    #[test]
    fn language_tag_is_set() {
        let syms = extract("class Foo\nend\n");
        assert_eq!(syms[0].language, "ruby");
    }
}