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