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