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, Fit};
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
437const fn m(crates: &'static str, fit: Fit, note: &'static str) -> CrateMatch {
438    CrateMatch { crates, fit, note }
439}
440
441/// Rust counterparts of common gems.
442pub fn lookup(gem: &str) -> Option<CrateMatch> {
443    Some(match gem {
444        "rails" | "sinatra" | "roda" | "hanami" => m(
445            "axum",
446            Fit::None,
447            "a web framework is an application rewrite, not a port",
448        ),
449        "activesupport" => m(
450            "chrono, heck, inflector",
451            Fit::Partial,
452            "core extensions have no single counterpart",
453        ),
454        "activerecord" | "sequel" => m(
455            "sqlx, diesel",
456            Fit::Partial,
457            "an ORM's dynamic queries need redesign",
458        ),
459        "nokogiri" => m("scraper, quick-xml", Fit::Partial, ""),
460        "json" | "oj" | "multi_json" => m("serde_json", Fit::Good, ""),
461        "httparty" | "faraday" | "rest-client" | "http" => m("reqwest", Fit::Good, ""),
462        "thor" | "optparse" | "slop" => m("clap", Fit::Good, ""),
463        "rspec" | "minitest" | "test-unit" => m("std test", Fit::Good, ""),
464        "rake" => m("cargo-make, just", Fit::Partial, ""),
465        "redis" => m("redis", Fit::Good, ""),
466        "pg" => m("tokio-postgres, sqlx", Fit::Good, ""),
467        "sqlite3" => m("rusqlite", Fit::Good, ""),
468        "dry-types" | "dry-struct" => m("serde", Fit::Partial, ""),
469        "nanoid" => m("nanoid", Fit::Good, ""),
470        "tzinfo" => m("chrono-tz", Fit::Good, ""),
471        "i18n" => m("rust-i18n, fluent", Fit::Partial, ""),
472        "kramdown" | "redcarpet" | "commonmarker" => m("pulldown-cmark, comrak", Fit::Good, ""),
473        "rouge" => m("syntect", Fit::Partial, ""),
474        "zeitwerk" | "bootsnap" => m("(none)", Fit::None, "Ruby loading machinery: drop it"),
475        _ => return None,
476    })
477}
478
479// ---- exports ---------------------------------------------------------------------------------
480
481/// A YARD type list (`String, nil`, `Array<Integer>`, `Hash{String => Integer}`) in the dialect.
482pub fn yard_to_ts(types: &str) -> String {
483    let parts = split_top(types, ',');
484    if parts.len() > 1 {
485        let mapped: Vec<String> = parts.iter().map(|p| yard_to_ts(p)).collect();
486        return mapped.join(" | ");
487    }
488    let t = types.trim();
489    if let Some(inner) = t.strip_prefix("Array<").and_then(|r| r.strip_suffix('>')) {
490        let inner = yard_to_ts(inner);
491        return if inner.contains(' ') {
492            format!("({inner})[]")
493        } else {
494            format!("{inner}[]")
495        };
496    }
497    if let Some(inner) = t.strip_prefix("Hash{").and_then(|r| r.strip_suffix('}'))
498        && let Some((k, v)) = inner.split_once("=>")
499    {
500        let key = yard_to_ts(k);
501        return if key == "string" {
502            format!("Record<string, {}>", yard_to_ts(v))
503        } else {
504            "unknown".into()
505        };
506    }
507    match t {
508        "String" => "string".into(),
509        "Integer" | "Fixnum" | "Bignum" => "int".into(),
510        "Float" | "Numeric" => "number".into(),
511        "Boolean" | "TrueClass" | "FalseClass" | "true" | "false" | "Bool" => "boolean".into(),
512        "nil" | "NilClass" | "void" => "undefined".into(),
513        "Array" => "unknown[]".into(),
514        "Symbol" => "string".into(),
515        _ => "unknown".into(),
516    }
517}
518
519fn split_top(text: &str, sep: char) -> Vec<String> {
520    let mut out = Vec::new();
521    let mut depth = 0i32;
522    let mut current = String::new();
523    for c in text.chars() {
524        match c {
525            '<' | '{' | '(' | '[' => depth += 1,
526            '>' | '}' | ')' | ']' => depth -= 1,
527            _ if c == sep && depth == 0 => {
528                out.push(current.trim().to_string());
529                current.clear();
530                continue;
531            }
532            _ => {}
533        }
534        current.push(c);
535    }
536    if !current.trim().is_empty() {
537        out.push(current.trim().to_string());
538    }
539    out
540}
541
542/// The comment lines right above line `row` (0-based), top to bottom.
543fn doc_above(lines: &[&str], row: usize) -> Vec<String> {
544    let mut out = Vec::new();
545    let mut i = row;
546    while i > 0 {
547        i -= 1;
548        let l = lines[i].trim();
549        if let Some(c) = l.strip_prefix('#') {
550            out.push(c.trim().to_string());
551        } else {
552            break;
553        }
554    }
555    out.reverse();
556    out
557}
558
559/// The dialect type of a literal default (`"-"`, `0`, `1.5`, `true`, `[]`).
560fn literal_type(value: &str) -> Option<&'static str> {
561    let v = value.trim();
562    if v.starts_with('"') || v.starts_with('\'') {
563        Some("string")
564    } else if v == "true" || v == "false" {
565        Some("boolean")
566    } else if v.parse::<i64>().is_ok() {
567        Some("int")
568    } else if v.parse::<f64>().is_ok() {
569        Some("number")
570    } else {
571        None
572    }
573}
574
575fn method_fn(
576    path: &str,
577    module: &str,
578    node: Node,
579    source: &str,
580    lines: &[&str],
581) -> Option<ExportedFn> {
582    let name = text(node.child_by_field_name("name")?, source).to_string();
583    let doc = doc_above(lines, node.start_position().row);
584    let yard_param = |p: &str| {
585        doc.iter().find_map(|l| {
586            let rest = l.strip_prefix("@param ")?;
587            let (pname, rest) = rest.split_once(' ')?;
588            if pname.trim_start_matches(':').trim_end_matches(':') != p {
589                return None;
590            }
591            let types = rest.trim().strip_prefix('[')?.split(']').next()?;
592            Some(yard_to_ts(types))
593        })
594    };
595    let returns = doc
596        .iter()
597        .find_map(|l| {
598            let rest = l.strip_prefix("@return ")?.trim().strip_prefix('[')?;
599            Some(yard_to_ts(rest.split(']').next()?))
600        })
601        .unwrap_or_else(|| "unknown".into());
602    let mut blocker = None;
603    if name.ends_with('=')
604        || name.ends_with('!')
605        || !name
606            .chars()
607            .next()
608            .is_some_and(|c| c.is_lowercase() || c == '_')
609    {
610        blocker = Some(format!("`{name}` is not a plain method name"));
611    }
612    let mut params = Vec::new();
613    let mut signature = String::new();
614    if let Some(list) = node.child_by_field_name("parameters") {
615        signature = text(list, source)
616            .trim_matches(|c| c == '(' || c == ')')
617            .to_string();
618        for p in named_children(list) {
619            let pname = p.child_by_field_name("name").map_or_else(
620                || text(p, source).to_string(),
621                |n| text(n, source).to_string(),
622            );
623            let value = p
624                .child_by_field_name("value")
625                .map(|v| text(v, source).to_string());
626            let (keyword_only, optional) = match p.kind() {
627                "identifier" => (false, false),
628                "optional_parameter" => (false, true),
629                "keyword_parameter" => (true, value.is_some()),
630                "splat_parameter" => {
631                    blocker.get_or_insert_with(|| "takes `*args`".into());
632                    (false, true)
633                }
634                "hash_splat_parameter" => {
635                    blocker.get_or_insert_with(|| "takes `**options`".into());
636                    (false, true)
637                }
638                "block_parameter" => {
639                    blocker.get_or_insert_with(|| "takes a block".into());
640                    continue;
641                }
642                _ => {
643                    blocker.get_or_insert_with(|| format!("parameter `{}`", text(p, source)));
644                    continue;
645                }
646            };
647            let mut ts_type = yard_param(&pname)
648                .or_else(|| value.as_deref().and_then(literal_type).map(str::to_string))
649                .unwrap_or_else(|| "unknown".into());
650            if value.as_deref() == Some("nil") && !ts_type.contains("undefined") {
651                ts_type = format!("{ts_type} | undefined");
652            }
653            params.push(Param {
654                name: pname,
655                ts_type,
656                optional,
657                default: value,
658                keyword_only,
659                ..Default::default()
660            });
661        }
662    }
663    infer_numbers(&mut params, node, source);
664    // A method that yields takes a block, even without `&block`.
665    if let Some(body) = node.child_by_field_name("body") {
666        let mut yields = false;
667        syntax::walk(body, |n| yields |= n.kind() == "yield");
668        if yields {
669            blocker.get_or_insert_with(|| "yields to a block".into());
670        }
671    }
672    Some(ExportedFn {
673        name,
674        file: path.to_string(),
675        line: syntax::line(node),
676        params,
677        returns,
678        prototype: Some(format!(
679            "{module}.{}({signature})",
680            text(node.child_by_field_name("name")?, source)
681        )),
682        blocker,
683        ..Default::default()
684    })
685}
686
687/// Parameters without a YARD type that the body uses in arithmetic become `number`.
688fn infer_numbers(params: &mut [Param], node: Node, source: &str) {
689    let Some(body) = node.child_by_field_name("body") else {
690        return;
691    };
692    let mut numeric: Vec<String> = Vec::new();
693    syntax::walk(body, |n| {
694        if n.kind() != "binary" {
695            return;
696        }
697        let op = n
698            .child_by_field_name("operator")
699            .map_or("", |o| text(o, source));
700        let (Some(l), Some(r)) = (
701            n.child_by_field_name("left"),
702            n.child_by_field_name("right"),
703        ) else {
704            return;
705        };
706        let literal = |x: Node| matches!(x.kind(), "integer" | "float");
707        if matches!(op, "-" | "*" | "/" | "**")
708            || (matches!(op, "+" | "%" | "<" | ">" | "<=" | ">=") && (literal(l) || literal(r)))
709        {
710            for side in [l, r] {
711                if side.kind() == "identifier" {
712                    numeric.push(text(side, source).to_string());
713                }
714            }
715        }
716    });
717    for p in params
718        .iter_mut()
719        .filter(|p| p.ts_type == "unknown" && numeric.contains(&p.name))
720    {
721        p.ts_type = "number".into();
722    }
723}
724
725/// Module functions: `def self.name` in a module or class, and methods after `module_function`
726/// or inside `class << self`. The receiver goes into `prototype` as `Module::Path.name(...)`.
727pub fn exports(path: &str, source: &str) -> Vec<ExportedFn> {
728    if !path.ends_with(".rb") {
729        return Vec::new();
730    }
731    let Some(tree) = syntax::parse(&language(), source) else {
732        return Vec::new();
733    };
734    let lines: Vec<&str> = source.lines().collect();
735    let mut out = Vec::new();
736    for child in named_children(tree.root_node()) {
737        if matches!(child.kind(), "module" | "class") {
738            namespace(path, child, source, &lines, &mut Vec::new(), &mut out);
739        }
740    }
741    out.sort_by_key(|f| f.line);
742    out
743}
744
745/// The module functions of one `module` or `class`, and of the namespaces nested in it.
746fn namespace(
747    path: &str,
748    node: Node,
749    source: &str,
750    lines: &[&str],
751    scope: &mut Vec<String>,
752    out: &mut Vec<ExportedFn>,
753) {
754    let Some(name) = node.child_by_field_name("name") else {
755        return;
756    };
757    scope.push(text(name, source).to_string());
758    let receiver = scope.join("::");
759    let is_module = node.kind() == "module";
760    let mut module_function = false;
761    let mut private = false;
762    let mut hidden: Vec<String> = Vec::new();
763    let mut found = Vec::new();
764    // Instance methods so far, for `module_function :name` after them.
765    let mut instance: Vec<Node> = Vec::new();
766    for item in node
767        .child_by_field_name("body")
768        .map(named_children)
769        .unwrap_or_default()
770    {
771        match item.kind() {
772            "identifier" if text(item, source) == "module_function" && is_module => {
773                module_function = true;
774            }
775            "identifier" if matches!(text(item, source), "private" | "protected") => {
776                private = true;
777            }
778            "call" if text(item, source).starts_with("private_class_method") => {
779                hidden.push(text(item, source).to_string());
780            }
781            "call" if is_module && text(item, source).starts_with("module_function") => {
782                let call = text(item, source);
783                for m in &instance {
784                    let name = m
785                        .child_by_field_name("name")
786                        .map_or("", |n| text(n, source));
787                    if call.contains(&format!(":{name}")) {
788                        found.extend(method_fn(path, &receiver, *m, source, lines));
789                    }
790                }
791            }
792            "singleton_method"
793                if item
794                    .child_by_field_name("object")
795                    .is_some_and(|o| text(o, source) == "self") =>
796            {
797                found.extend(method_fn(path, &receiver, item, source, lines));
798            }
799            "method" if module_function && !private => {
800                found.extend(method_fn(path, &receiver, item, source, lines));
801            }
802            "method" if !private => instance.push(item),
803            "singleton_class" => {
804                let mut private_here = false;
805                for m in item
806                    .child_by_field_name("body")
807                    .map(named_children)
808                    .unwrap_or_default()
809                {
810                    if m.kind() == "identifier" && text(m, source) == "private" {
811                        private_here = true;
812                    }
813                    if m.kind() == "method" && !private_here {
814                        found.extend(method_fn(path, &receiver, m, source, lines));
815                    }
816                }
817            }
818            "module" | "class" => namespace(path, item, source, lines, scope, out),
819            _ => {}
820        }
821    }
822    found.retain(|f| !hidden.iter().any(|h| h.contains(&format!(":{}", f.name))));
823    found.sort_by_key(|f| f.line);
824    out.extend(found);
825    scope.pop();
826}
827
828/// The receiver and method name of an export: `("Textkit::Words", "slugify")`.
829pub fn receiver(f: &ExportedFn) -> (String, String) {
830    let proto = f.prototype.as_deref().unwrap_or(&f.name);
831    let head = proto.split('(').next().unwrap_or(proto);
832    match head.rsplit_once('.') {
833        Some((recv, name)) => (recv.to_string(), name.to_string()),
834        None => ("Object".into(), f.name.clone()),
835    }
836}
837
838/// The parameter list as written: `text, sep = "-", max: nil`.
839pub fn signature(f: &ExportedFn) -> String {
840    let proto = f.prototype.as_deref().unwrap_or("");
841    proto
842        .split_once('(')
843        .map(|(_, rest)| rest.strip_suffix(')').unwrap_or(rest).to_string())
844        .unwrap_or_default()
845}
846
847#[cfg(test)]
848mod tests {
849    use super::*;
850
851    #[test]
852    fn maps_yard_types() {
853        assert_eq!(yard_to_ts("String, nil"), "string | undefined");
854        assert_eq!(yard_to_ts("Array<Integer>"), "int[]");
855        assert_eq!(yard_to_ts("Hash{String => Integer}"), "Record<string, int>");
856    }
857
858    #[test]
859    fn finds_module_functions() {
860        let src = "module Textkit\n  # Slug.\n  # @param text [String]\n  # @return [String]\n  \
861                   def self.slugify(text, sep = \"-\", max: nil)\n    text\n  end\n\n  \
862                   def self.each_word(text)\n    yield text\n  end\n\n  \
863                   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  \
864                   class Stack\n    def push(x) = x\n  end\nend\n";
865        let fns = exports("lib/textkit.rb", src);
866        let names: Vec<(String, String)> = fns.iter().map(receiver).collect();
867        assert_eq!(
868            names,
869            [
870                ("Textkit".to_string(), "slugify".to_string()),
871                ("Textkit".to_string(), "each_word".to_string()),
872                ("Textkit::Nums".to_string(), "clamp".to_string()),
873            ]
874        );
875        let slug = &fns[0];
876        assert_eq!(slug.params[0].ts_type, "string");
877        assert_eq!(slug.params[1].ts_type, "string");
878        assert!(slug.params[2].keyword_only);
879        assert_eq!(slug.params[2].ts_type, "unknown | undefined");
880        assert_eq!(slug.returns, "string");
881        assert_eq!(signature(slug), "text, sep = \"-\", max: nil");
882        assert!(fns[1].blocker.is_some());
883        assert_eq!(fns[2].params[1].ts_type, "int");
884    }
885
886    #[test]
887    fn module_function_with_names_and_inferred_numbers() {
888        let src = "module Shellwords\n  def shellsplit(line)\n    line\n  end\n  module_function :shellsplit\n\n  \
889                   def helper(x) = x\n\n  def scale(x, factor)\n    x * factor\n  end\n  module_function :scale\nend\n";
890        let fns = exports("lib/shellwords.rb", src);
891        let names: Vec<&str> = fns.iter().map(|f| f.name.as_str()).collect();
892        assert_eq!(names, ["shellsplit", "scale"]);
893        assert_eq!(fns[0].params[0].ts_type, "unknown");
894        assert_eq!(fns[1].params[0].ts_type, "number");
895    }
896}