Skip to main content

rust_anything/lang/
ruby.rs

1//! Ruby: gems, requires, risks, the gem-to-crate table, and module functions (`def self.x`,
2//! `module_function`) with YARD types mapped into the TS-like type dialect.
3
4use std::collections::HashMap;
5use std::path::Path;
6
7use anyhow::Result;
8use tree_sitter::Node;
9
10use super::syntax::{self, named_children, text};
11use crate::risks::{Risk, regex_needs_fancy};
12use crate::ts::deps::CrateMatch;
13use crate::ts::discover::{FileKind, Package, SourceFile, Workspace};
14use crate::ts::exports::{ExportedFn, Param};
15use crate::ts::scan::{FileFacts, Import};
16
17fn language() -> tree_sitter::Language {
18    tree_sitter_ruby::LANGUAGE.into()
19}
20
21const SKIP_DIRS: &[&str] = &[
22    "vendor",
23    "node_modules",
24    "tmp",
25    "log",
26    "coverage",
27    "pkg",
28    "target",
29    ".bundle",
30];
31
32// ---- discovery -------------------------------------------------------------------------------
33
34/// `spec.add_dependency "name"` and `gem "name"` lines.
35fn gem_names(text: &str) -> (Vec<String>, Vec<String>) {
36    let (mut deps, mut dev) = (Vec::new(), Vec::new());
37    for line in text.lines() {
38        let line = line.trim();
39        let quoted = |rest: &str| {
40            rest.trim()
41                .trim_start_matches('(')
42                .split(['"', '\''])
43                .nth(1)
44                .map(str::to_string)
45        };
46        if let Some(rest) = line
47            .strip_prefix("spec.add_dependency")
48            .or_else(|| line.strip_prefix("spec.add_runtime_dependency"))
49            .or_else(|| line.strip_prefix("s.add_dependency"))
50            .or_else(|| line.strip_prefix("gem "))
51        {
52            deps.extend(quoted(rest));
53        } else if let Some(rest) = line
54            .strip_prefix("spec.add_development_dependency")
55            .or_else(|| line.strip_prefix("s.add_development_dependency"))
56        {
57            dev.extend(quoted(rest));
58        }
59    }
60    (deps, dev)
61}
62
63pub fn discover(root: &Path) -> Result<Workspace> {
64    let mut packages: Vec<Package> = Vec::new();
65    let mut files = Vec::new();
66    let walker = crate::walk::filtered(root, |e| {
67        !(e.file_type().is_some_and(|t| t.is_dir())
68            && SKIP_DIRS.contains(&e.file_name().to_string_lossy().as_ref()))
69    })
70    .hidden(true)
71    .require_git(false)
72    .build();
73    for entry in walker.flatten() {
74        if !entry.file_type().is_some_and(|t| t.is_file()) {
75            continue;
76        }
77        let Ok(rel) = entry.path().strip_prefix(root) else {
78            continue;
79        };
80        let rel = rel.to_string_lossy().replace('\\', "/");
81        let name = rel.rsplit('/').next().unwrap_or(&rel);
82        let dir = rel
83            .rsplit_once('/')
84            .map_or(String::new(), |(d, _)| d.to_string());
85        if name.ends_with(".gemspec") || name == "Gemfile" {
86            let text = std::fs::read_to_string(entry.path()).unwrap_or_default();
87            let (deps, dev) = gem_names(&text);
88            if let Some(p) = packages.iter_mut().find(|p| p.dir == dir) {
89                p.deps.extend(deps);
90                p.dev_deps.extend(dev);
91                if name.ends_with(".gemspec") {
92                    p.name = name.trim_end_matches(".gemspec").to_string();
93                }
94            } else {
95                packages.push(Package {
96                    name: if name.ends_with(".gemspec") {
97                        name.trim_end_matches(".gemspec").to_string()
98                    } else if dir.is_empty() {
99                        root.file_name()
100                            .map_or_else(|| "root".into(), |n| n.to_string_lossy().into_owned())
101                    } else {
102                        dir.clone()
103                    },
104                    src_root: if root.join(&dir).join("lib").is_dir() {
105                        join(&dir, "lib")
106                    } else {
107                        dir.clone()
108                    },
109                    dir,
110                    deps,
111                    dev_deps: dev,
112                });
113            }
114        } else if name.ends_with(".rb") {
115            let is_test = name.ends_with("_test.rb")
116                || name.ends_with("_spec.rb")
117                || name.starts_with("test_")
118                || rel
119                    .split('/')
120                    .any(|p| matches!(p, "test" | "spec" | "features"));
121            files.push((
122                rel,
123                if is_test {
124                    FileKind::Test
125                } else {
126                    FileKind::Source
127                },
128            ));
129        }
130    }
131    if !packages.iter().any(|p| p.dir.is_empty()) {
132        packages.push(Package {
133            name: root
134                .file_name()
135                .map_or_else(|| "root".into(), |n| n.to_string_lossy().into_owned()),
136            dir: String::new(),
137            src_root: if root.join("lib").is_dir() {
138                "lib".into()
139            } else {
140                String::new()
141            },
142            deps: Vec::new(),
143            dev_deps: Vec::new(),
144        });
145    }
146    packages.sort_by(|a, b| a.dir.cmp(&b.dir));
147    files.sort_by(|a, b| a.0.cmp(&b.0));
148    let files = files
149        .into_iter()
150        .map(|(path, kind)| {
151            let package = packages
152                .iter()
153                .enumerate()
154                .filter(|(_, p)| p.dir.is_empty() || path.starts_with(&format!("{}/", p.dir)))
155                .max_by_key(|(_, p)| p.dir.len())
156                .map_or(0, |(i, _)| i);
157            SourceFile {
158                path,
159                package,
160                kind,
161            }
162        })
163        .collect();
164    Ok(Workspace { packages, files })
165}
166
167fn join(dir: &str, rest: &str) -> String {
168    if dir.is_empty() {
169        rest.to_string()
170    } else {
171        format!("{dir}/{rest}")
172    }
173}
174
175// ---- risks and imports -----------------------------------------------------------------------
176
177const CORE_CLASSES: &[&str] = &[
178    "String",
179    "Array",
180    "Hash",
181    "Integer",
182    "Float",
183    "Numeric",
184    "Object",
185    "Kernel",
186    "Symbol",
187    "NilClass",
188    "Comparable",
189    "Enumerable",
190    "Module",
191    "Class",
192    "Time",
193    "Range",
194    "Proc",
195];
196
197const METAPROGRAMMING: &[&str] = &[
198    "define_method",
199    "method_missing",
200    "respond_to_missing?",
201    "instance_variable_set",
202    "instance_variable_get",
203    "class_eval",
204    "module_eval",
205    "instance_eval",
206    "const_set",
207    "remove_method",
208    "alias_method",
209    "prepend",
210    "refine",
211];
212
213pub fn scan(source: &str) -> FileFacts {
214    let mut facts = FileFacts {
215        loc: syntax::loc(source),
216        ..FileFacts::default()
217    };
218    let Some(tree) = syntax::parse(&language(), source) else {
219        return facts;
220    };
221    let root = tree.root_node();
222    facts.parse_errors = usize::from(root.has_error());
223    let add = |facts: &mut FileFacts, risk: Risk, node: Node| {
224        facts
225            .risks
226            .entry(risk)
227            .or_default()
228            .push(syntax::line(node))
229    };
230    syntax::walk(root, |node| match node.kind() {
231        "call" => {
232            let method = node
233                .child_by_field_name("method")
234                .map_or("", |m| text(m, source));
235            let has_receiver = node.child_by_field_name("receiver").is_some();
236            match method {
237                "require" | "require_relative" | "load" if !has_receiver => {
238                    let arg = node
239                        .child_by_field_name("arguments")
240                        .and_then(|a| named_children(a).into_iter().next());
241                    match arg {
242                        Some(a) if a.kind() == "string" && !text(a, source).contains("#{") => {
243                            let spec = text(a, source).trim_matches(|c| c == '"' || c == '\'');
244                            facts.imports.push(Import {
245                                specifier: if method == "require_relative" {
246                                    format!("./{spec}")
247                                } else {
248                                    spec.to_string()
249                                },
250                                type_only: false,
251                                dynamic: false,
252                            });
253                        }
254                        _ => add(&mut facts, Risk::DynamicCode, node),
255                    }
256                }
257                "eval" | "instance_exec" | "class_exec" => add(&mut facts, Risk::DynamicCode, node),
258                "send" | "public_send" | "__send__" | "method" | "const_get" | "respond_to?"
259                | "is_a?" | "kind_of?" | "instance_of?" => add(&mut facts, Risk::Reflection, node),
260                m if METAPROGRAMMING.contains(&m) => add(&mut facts, Risk::Monkeypatching, node),
261                "each" | "map" | "each_with_index" | "times" | "each_char" | "select"
262                | "reduce" | "inject" | "each_with_object" | "flat_map" => facts.loops += 1,
263                "sort_by" | "sort" | "uniq" | "group_by" | "tally" => {
264                    add(&mut facts, Risk::OrderedCollections, node)
265                }
266                "new"
267                    if node.child_by_field_name("receiver").is_some_and(|r| {
268                        matches!(text(r, source), "Thread" | "Mutex" | "Queue" | "Ractor")
269                    }) =>
270                {
271                    add(&mut facts, Risk::Concurrency, node)
272                }
273                "new"
274                    if node
275                        .child_by_field_name("receiver")
276                        .is_some_and(|r| text(r, source) == "Regexp") =>
277                {
278                    add(&mut facts, Risk::DynamicRegex, node)
279                }
280                "to_json" | "parse" | "generate" if text(node, source).contains("JSON") => {
281                    add(&mut facts, Risk::Json, node)
282                }
283                "raise" | "fail" => add(&mut facts, Risk::Exceptions, node),
284                _ => {}
285            }
286        }
287        "class" | "module" => {
288            if node.child_by_field_name("superclass").is_some() {
289                add(&mut facts, Risk::ClassInheritance, node);
290            }
291            // Reopening a core class changes it for every caller.
292            let name = node
293                .child_by_field_name("name")
294                .map_or("", |n| text(n, source));
295            if CORE_CLASSES.contains(&name) && node.parent().is_some_and(|p| p.kind() == "program")
296            {
297                add(&mut facts, Risk::Monkeypatching, node);
298            }
299        }
300        "singleton_class" => add(&mut facts, Risk::Monkeypatching, node),
301        "regex" => {
302            let pattern = text(node, source);
303            let body = pattern
304                .strip_prefix('/')
305                .and_then(|p| p.rsplit_once('/'))
306                .map_or(pattern, |(b, _)| b);
307            // Onigmo's \h is hex, not horizontal space; other features need fancy-regex.
308            if regex_needs_fancy(body, "") || body.contains("\\h") {
309                add(&mut facts, Risk::RegexSyntax, node);
310            }
311        }
312        "element_reference" => add(&mut facts, Risk::StringOffsets, node),
313        "binary" => {
314            let op = node
315                .child_by_field_name("operator")
316                .map_or("", |o| text(o, source));
317            match op {
318                "/" | "%" => add(&mut facts, Risk::DivisionSemantics, node),
319                "**" | "<<" => add(&mut facts, Risk::IntegerSemantics, node),
320                _ => {}
321            }
322        }
323        "rescue" | "ensure" => add(&mut facts, Risk::Exceptions, node),
324        "block" | "do_block" | "lambda" | "block_parameter" => {
325            add(&mut facts, Risk::Callbacks, node)
326        }
327        "yield" => add(&mut facts, Risk::Generators, node),
328        "nil" => add(&mut facts, Risk::NullReferences, node),
329        "hash" => add(&mut facts, Risk::OrderedCollections, node),
330        "while" | "until" | "for" => facts.loops += 1,
331        "method" | "singleton_method" => add(&mut facts, Risk::DynamicTyping, node),
332        _ => {}
333    });
334    facts
335}
336
337/// Ruby's standard library and default gems: no crate needed to replace a `require` of them.
338const STDLIB: &[&str] = &[
339    "json",
340    "set",
341    "time",
342    "date",
343    "securerandom",
344    "digest",
345    "base64",
346    "erb",
347    "fileutils",
348    "pathname",
349    "tempfile",
350    "stringio",
351    "strscan",
352    "uri",
353    "net/http",
354    "open3",
355    "optparse",
356    "logger",
357    "yaml",
358    "psych",
359    "csv",
360    "bigdecimal",
361    "forwardable",
362    "singleton",
363    "observer",
364    "English",
365    "shellwords",
366    "zlib",
367    "socket",
368    "timeout",
369    "benchmark",
370    "pp",
371    "prettyprint",
372    "ostruct",
373    "open-uri",
374    "tmpdir",
375    "etc",
376    "io/console",
377    "monitor",
378    "weakref",
379    "objspace",
380    "ripper",
381    "coverage",
382    "digest/sha2",
383    "digest/md5",
384    "openssl",
385    "cgi",
386    "rbconfig",
387];
388
389pub fn resolve(
390    from: &str,
391    spec: &str,
392    index: &HashMap<&str, usize>,
393    ws: &Workspace,
394) -> super::Resolution {
395    let with_ext = |p: &str| {
396        if p.ends_with(".rb") {
397            p.to_string()
398        } else {
399            format!("{p}.rb")
400        }
401    };
402    if let Some(rel) = spec.strip_prefix("./") {
403        let dir = from.rsplit_once('/').map_or("", |(d, _)| d);
404        if let Some(path) = normalize(&join(dir, &with_ext(rel)))
405            && let Some(i) = index.get(path.as_str())
406        {
407            return super::Resolution::File(*i);
408        }
409        return super::Resolution::Unresolved;
410    }
411    for p in &ws.packages {
412        let candidate = join(&p.src_root, &with_ext(spec));
413        if let Some(i) = index.get(candidate.as_str()) {
414            return super::Resolution::File(*i);
415        }
416    }
417    if STDLIB.contains(&spec) || STDLIB.contains(&spec.split('/').next().unwrap_or(spec)) {
418        return super::Resolution::Stdlib;
419    }
420    super::Resolution::External(spec.split('/').next().unwrap_or(spec).to_string())
421}
422
423fn normalize(path: &str) -> Option<String> {
424    let mut parts: Vec<&str> = Vec::new();
425    for part in path.split('/') {
426        match part {
427            "" | "." => {}
428            ".." => {
429                parts.pop()?;
430            }
431            _ => parts.push(part),
432        }
433    }
434    Some(parts.join("/"))
435}
436
437/// Rust counterparts of common gems.
438pub fn lookup(gem: &str) -> Option<CrateMatch> {
439    crate::crates::find("ruby", gem)
440}
441
442// ---- exports ---------------------------------------------------------------------------------
443
444/// A YARD type list (`String, nil`, `Array<Integer>`, `Hash{String => Integer}`) in the dialect.
445pub fn yard_to_ts(types: &str) -> String {
446    let parts = split_top(types, ',');
447    if parts.len() > 1 {
448        let mapped: Vec<String> = parts.iter().map(|p| yard_to_ts(p)).collect();
449        return mapped.join(" | ");
450    }
451    let t = types.trim();
452    if let Some(inner) = t.strip_prefix("Array<").and_then(|r| r.strip_suffix('>')) {
453        let inner = yard_to_ts(inner);
454        return if inner.contains(' ') {
455            format!("({inner})[]")
456        } else {
457            format!("{inner}[]")
458        };
459    }
460    if let Some(inner) = t.strip_prefix("Hash{").and_then(|r| r.strip_suffix('}'))
461        && let Some((k, v)) = inner.split_once("=>")
462    {
463        let key = yard_to_ts(k);
464        return if key == "string" {
465            format!("Record<string, {}>", yard_to_ts(v))
466        } else {
467            "unknown".into()
468        };
469    }
470    match t {
471        "String" => "string".into(),
472        "Integer" | "Fixnum" | "Bignum" => "int".into(),
473        "Float" | "Numeric" => "number".into(),
474        "Boolean" | "TrueClass" | "FalseClass" | "true" | "false" | "Bool" => "boolean".into(),
475        "nil" | "NilClass" | "void" => "undefined".into(),
476        "Array" => "unknown[]".into(),
477        "Symbol" => "string".into(),
478        _ => "unknown".into(),
479    }
480}
481
482fn split_top(text: &str, sep: char) -> Vec<String> {
483    let mut out = Vec::new();
484    let mut depth = 0i32;
485    let mut current = String::new();
486    for c in text.chars() {
487        match c {
488            '<' | '{' | '(' | '[' => depth += 1,
489            '>' | '}' | ')' | ']' => depth -= 1,
490            _ if c == sep && depth == 0 => {
491                out.push(current.trim().to_string());
492                current.clear();
493                continue;
494            }
495            _ => {}
496        }
497        current.push(c);
498    }
499    if !current.trim().is_empty() {
500        out.push(current.trim().to_string());
501    }
502    out
503}
504
505/// The comment lines right above line `row` (0-based), top to bottom.
506fn doc_above(lines: &[&str], row: usize) -> Vec<String> {
507    let mut out = Vec::new();
508    let mut i = row;
509    while i > 0 {
510        i -= 1;
511        let l = lines[i].trim();
512        if let Some(c) = l.strip_prefix('#') {
513            out.push(c.trim().to_string());
514        } else {
515            break;
516        }
517    }
518    out.reverse();
519    out
520}
521
522/// The dialect type of a literal default (`"-"`, `0`, `1.5`, `true`, `[]`).
523fn literal_type(value: &str) -> Option<&'static str> {
524    let v = value.trim();
525    if v.starts_with('"') || v.starts_with('\'') {
526        Some("string")
527    } else if v == "true" || v == "false" {
528        Some("boolean")
529    } else if v.parse::<i64>().is_ok() {
530        Some("int")
531    } else if v.parse::<f64>().is_ok() {
532        Some("number")
533    } else {
534        None
535    }
536}
537
538fn method_fn(
539    path: &str,
540    module: &str,
541    node: Node,
542    source: &str,
543    lines: &[&str],
544) -> Option<ExportedFn> {
545    let name = text(node.child_by_field_name("name")?, source).to_string();
546    let doc = doc_above(lines, node.start_position().row);
547    let yard_param = |p: &str| {
548        doc.iter().find_map(|l| {
549            let rest = l.strip_prefix("@param ")?;
550            let (pname, rest) = rest.split_once(' ')?;
551            if pname.trim_start_matches(':').trim_end_matches(':') != p {
552                return None;
553            }
554            let types = rest.trim().strip_prefix('[')?.split(']').next()?;
555            Some(yard_to_ts(types))
556        })
557    };
558    let returns = doc
559        .iter()
560        .find_map(|l| {
561            let rest = l.strip_prefix("@return ")?.trim().strip_prefix('[')?;
562            Some(yard_to_ts(rest.split(']').next()?))
563        })
564        .unwrap_or_else(|| "unknown".into());
565    let mut blocker = None;
566    if name.ends_with('=')
567        || name.ends_with('!')
568        || !name
569            .chars()
570            .next()
571            .is_some_and(|c| c.is_lowercase() || c == '_')
572    {
573        blocker = Some(format!("`{name}` is not a plain method name"));
574    }
575    let mut params = Vec::new();
576    let mut signature = String::new();
577    if let Some(list) = node.child_by_field_name("parameters") {
578        signature = text(list, source)
579            .trim_matches(|c| c == '(' || c == ')')
580            .to_string();
581        for p in named_children(list) {
582            let pname = p.child_by_field_name("name").map_or_else(
583                || text(p, source).to_string(),
584                |n| text(n, source).to_string(),
585            );
586            let value = p
587                .child_by_field_name("value")
588                .map(|v| text(v, source).to_string());
589            let (keyword_only, optional) = match p.kind() {
590                "identifier" => (false, false),
591                "optional_parameter" => (false, true),
592                "keyword_parameter" => (true, value.is_some()),
593                "splat_parameter" => {
594                    blocker.get_or_insert_with(|| "takes `*args`".into());
595                    (false, true)
596                }
597                "hash_splat_parameter" => {
598                    blocker.get_or_insert_with(|| "takes `**options`".into());
599                    (false, true)
600                }
601                "block_parameter" => {
602                    blocker.get_or_insert_with(|| "takes a block".into());
603                    continue;
604                }
605                _ => {
606                    blocker.get_or_insert_with(|| format!("parameter `{}`", text(p, source)));
607                    continue;
608                }
609            };
610            let mut ts_type = yard_param(&pname)
611                .or_else(|| value.as_deref().and_then(literal_type).map(str::to_string))
612                .unwrap_or_else(|| "unknown".into());
613            if value.as_deref() == Some("nil") && !ts_type.contains("undefined") {
614                ts_type = format!("{ts_type} | undefined");
615            }
616            params.push(Param {
617                name: pname,
618                ts_type,
619                optional,
620                default: value,
621                keyword_only,
622                ..Default::default()
623            });
624        }
625    }
626    infer_numbers(&mut params, node, source);
627    // A method that yields takes a block, even without `&block`.
628    if let Some(body) = node.child_by_field_name("body") {
629        let mut yields = false;
630        syntax::walk(body, |n| yields |= n.kind() == "yield");
631        if yields {
632            blocker.get_or_insert_with(|| "yields to a block".into());
633        }
634    }
635    Some(ExportedFn {
636        name,
637        file: path.to_string(),
638        line: syntax::line(node),
639        params,
640        returns,
641        prototype: Some(format!(
642            "{module}.{}({signature})",
643            text(node.child_by_field_name("name")?, source)
644        )),
645        blocker,
646        ..Default::default()
647    })
648}
649
650/// Parameters without a YARD type that the body uses in arithmetic become `number`.
651fn infer_numbers(params: &mut [Param], node: Node, source: &str) {
652    let Some(body) = node.child_by_field_name("body") else {
653        return;
654    };
655    let mut numeric: Vec<String> = Vec::new();
656    syntax::walk(body, |n| {
657        if n.kind() != "binary" {
658            return;
659        }
660        let op = n
661            .child_by_field_name("operator")
662            .map_or("", |o| text(o, source));
663        let (Some(l), Some(r)) = (
664            n.child_by_field_name("left"),
665            n.child_by_field_name("right"),
666        ) else {
667            return;
668        };
669        let literal = |x: Node| matches!(x.kind(), "integer" | "float");
670        if matches!(op, "-" | "*" | "/" | "**")
671            || (matches!(op, "+" | "%" | "<" | ">" | "<=" | ">=") && (literal(l) || literal(r)))
672        {
673            for side in [l, r] {
674                if side.kind() == "identifier" {
675                    numeric.push(text(side, source).to_string());
676                }
677            }
678        }
679    });
680    for p in params
681        .iter_mut()
682        .filter(|p| p.ts_type == "unknown" && numeric.contains(&p.name))
683    {
684        p.ts_type = "number".into();
685    }
686}
687
688/// Module functions: `def self.name` in a module or class, and methods after `module_function`
689/// or inside `class << self`. The receiver goes into `prototype` as `Module::Path.name(...)`.
690pub fn exports(path: &str, source: &str) -> Vec<ExportedFn> {
691    if !path.ends_with(".rb") {
692        return Vec::new();
693    }
694    let Some(tree) = syntax::parse(&language(), source) else {
695        return Vec::new();
696    };
697    let lines: Vec<&str> = source.lines().collect();
698    let mut out = Vec::new();
699    for child in named_children(tree.root_node()) {
700        if matches!(child.kind(), "module" | "class") {
701            namespace(path, child, source, &lines, &mut Vec::new(), &mut out);
702        }
703    }
704    out.sort_by_key(|f| f.line);
705    out
706}
707
708/// The module functions of one `module` or `class`, and of the namespaces nested in it.
709fn namespace(
710    path: &str,
711    node: Node,
712    source: &str,
713    lines: &[&str],
714    scope: &mut Vec<String>,
715    out: &mut Vec<ExportedFn>,
716) {
717    let Some(name) = node.child_by_field_name("name") else {
718        return;
719    };
720    scope.push(text(name, source).to_string());
721    let receiver = scope.join("::");
722    let is_module = node.kind() == "module";
723    let mut module_function = false;
724    let mut private = false;
725    let mut hidden: Vec<String> = Vec::new();
726    let mut found = Vec::new();
727    // Instance methods so far, for `module_function :name` after them.
728    let mut instance: Vec<Node> = Vec::new();
729    for item in node
730        .child_by_field_name("body")
731        .map(named_children)
732        .unwrap_or_default()
733    {
734        match item.kind() {
735            "identifier" if text(item, source) == "module_function" && is_module => {
736                module_function = true;
737            }
738            "identifier" if matches!(text(item, source), "private" | "protected") => {
739                private = true;
740            }
741            "call" if text(item, source).starts_with("private_class_method") => {
742                hidden.push(text(item, source).to_string());
743            }
744            "call" if is_module && text(item, source).starts_with("module_function") => {
745                let call = text(item, source);
746                for m in &instance {
747                    let name = m
748                        .child_by_field_name("name")
749                        .map_or("", |n| text(n, source));
750                    if call.contains(&format!(":{name}")) {
751                        found.extend(method_fn(path, &receiver, *m, source, lines));
752                    }
753                }
754            }
755            "singleton_method"
756                if item
757                    .child_by_field_name("object")
758                    .is_some_and(|o| text(o, source) == "self") =>
759            {
760                found.extend(method_fn(path, &receiver, item, source, lines));
761            }
762            "method" if module_function && !private => {
763                found.extend(method_fn(path, &receiver, item, source, lines));
764            }
765            "method" if !private => instance.push(item),
766            "singleton_class" => {
767                let mut private_here = false;
768                for m in item
769                    .child_by_field_name("body")
770                    .map(named_children)
771                    .unwrap_or_default()
772                {
773                    if m.kind() == "identifier" && text(m, source) == "private" {
774                        private_here = true;
775                    }
776                    if m.kind() == "method" && !private_here {
777                        found.extend(method_fn(path, &receiver, m, source, lines));
778                    }
779                }
780            }
781            "module" | "class" => namespace(path, item, source, lines, scope, out),
782            _ => {}
783        }
784    }
785    found.retain(|f| !hidden.iter().any(|h| h.contains(&format!(":{}", f.name))));
786    found.sort_by_key(|f| f.line);
787    out.extend(found);
788    scope.pop();
789}
790
791/// The receiver and method name of an export: `("Textkit::Words", "slugify")`.
792pub fn receiver(f: &ExportedFn) -> (String, String) {
793    let proto = f.prototype.as_deref().unwrap_or(&f.name);
794    let head = proto.split('(').next().unwrap_or(proto);
795    match head.rsplit_once('.') {
796        Some((recv, name)) => (recv.to_string(), name.to_string()),
797        None => ("Object".into(), f.name.clone()),
798    }
799}
800
801/// The parameter list as written: `text, sep = "-", max: nil`.
802pub fn signature(f: &ExportedFn) -> String {
803    let proto = f.prototype.as_deref().unwrap_or("");
804    proto
805        .split_once('(')
806        .map(|(_, rest)| rest.strip_suffix(')').unwrap_or(rest).to_string())
807        .unwrap_or_default()
808}
809
810#[cfg(test)]
811mod tests {
812    use super::*;
813
814    #[test]
815    fn maps_yard_types() {
816        assert_eq!(yard_to_ts("String, nil"), "string | undefined");
817        assert_eq!(yard_to_ts("Array<Integer>"), "int[]");
818        assert_eq!(yard_to_ts("Hash{String => Integer}"), "Record<string, int>");
819    }
820
821    #[test]
822    fn finds_module_functions() {
823        let src = "module Textkit\n  # Slug.\n  # @param text [String]\n  # @return [String]\n  \
824                   def self.slugify(text, sep = \"-\", max: nil)\n    text\n  end\n\n  \
825                   def self.each_word(text)\n    yield text\n  end\n\n  \
826                   module Nums\n    module_function\n\n    def clamp(v, lo = 0, hi = 10) = v\n\n    private\n\n    def helper = 1\n  end\n\n  \
827                   class Stack\n    def push(x) = x\n  end\nend\n";
828        let fns = exports("lib/textkit.rb", src);
829        let names: Vec<(String, String)> = fns.iter().map(receiver).collect();
830        assert_eq!(
831            names,
832            [
833                ("Textkit".to_string(), "slugify".to_string()),
834                ("Textkit".to_string(), "each_word".to_string()),
835                ("Textkit::Nums".to_string(), "clamp".to_string()),
836            ]
837        );
838        let slug = &fns[0];
839        assert_eq!(slug.params[0].ts_type, "string");
840        assert_eq!(slug.params[1].ts_type, "string");
841        assert!(slug.params[2].keyword_only);
842        assert_eq!(slug.params[2].ts_type, "unknown | undefined");
843        assert_eq!(slug.returns, "string");
844        assert_eq!(signature(slug), "text, sep = \"-\", max: nil");
845        assert!(fns[1].blocker.is_some());
846        assert_eq!(fns[2].params[1].ts_type, "int");
847    }
848
849    #[test]
850    fn module_function_with_names_and_inferred_numbers() {
851        let src = "module Shellwords\n  def shellsplit(line)\n    line\n  end\n  module_function :shellsplit\n\n  \
852                   def helper(x) = x\n\n  def scale(x, factor)\n    x * factor\n  end\n  module_function :scale\nend\n";
853        let fns = exports("lib/shellwords.rb", src);
854        let names: Vec<&str> = fns.iter().map(|f| f.name.as_str()).collect();
855        assert_eq!(names, ["shellsplit", "scale"]);
856        assert_eq!(fns[0].params[0].ts_type, "unknown");
857        assert_eq!(fns[1].params[0].ts_type, "number");
858    }
859}