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            // YARD takes the name and the type in either order: `@param name [Type]` and
585            // `@param [Type] name`.
586            let (pname, types) = if rest.trim_start().starts_with('[') {
587                let close = rest.trim_start().find(']')?;
588                let types = &rest.trim_start()[1..close];
589                let after = rest.trim_start()[close + 1..].trim_start();
590                let pname = after.split_whitespace().next()?;
591                (pname, types)
592            } else {
593                let (pname, rest) = rest.split_once(' ')?;
594                let types = rest.trim().strip_prefix('[')?.split(']').next()?;
595                (pname, types)
596            };
597            if pname.trim_start_matches(':').trim_end_matches(':') != p {
598                return None;
599            }
600            Some(yard_to_ts(types))
601        })
602    };
603    let returns = doc
604        .iter()
605        .find_map(|l| {
606            let rest = l.strip_prefix("@return ")?.trim().strip_prefix('[')?;
607            Some(yard_to_ts(rest.split(']').next()?))
608        })
609        .unwrap_or_else(|| "unknown".into());
610    let mut blocker = None;
611    if name.ends_with('=')
612        || name.ends_with('!')
613        || !name
614            .chars()
615            .next()
616            .is_some_and(|c| c.is_lowercase() || c == '_')
617    {
618        blocker = Some(format!("`{name}` is not a plain method name"));
619    }
620    let mut params = Vec::new();
621    let mut signature = String::new();
622    if let Some(list) = node.child_by_field_name("parameters") {
623        signature = text(list, source)
624            .trim_matches(|c| c == '(' || c == ')')
625            .to_string();
626        for p in named_children(list) {
627            let pname = p.child_by_field_name("name").map_or_else(
628                || text(p, source).to_string(),
629                |n| text(n, source).to_string(),
630            );
631            let value = p
632                .child_by_field_name("value")
633                .map(|v| text(v, source).to_string());
634            let (keyword_only, optional) = match p.kind() {
635                "identifier" => (false, false),
636                "optional_parameter" => (false, true),
637                "keyword_parameter" => (true, value.is_some()),
638                "splat_parameter" => {
639                    blocker.get_or_insert_with(|| "takes `*args`".into());
640                    (false, true)
641                }
642                "hash_splat_parameter" => {
643                    blocker.get_or_insert_with(|| "takes `**options`".into());
644                    (false, true)
645                }
646                "block_parameter" => {
647                    blocker.get_or_insert_with(|| "takes a block".into());
648                    continue;
649                }
650                _ => {
651                    blocker.get_or_insert_with(|| format!("parameter `{}`", text(p, source)));
652                    continue;
653                }
654            };
655            let mut ts_type = yard_param(&pname)
656                .or_else(|| value.as_deref().and_then(literal_type).map(str::to_string))
657                .unwrap_or_else(|| "unknown".into());
658            if value.as_deref() == Some("nil") && !ts_type.contains("undefined") {
659                ts_type = format!("{ts_type} | undefined");
660            }
661            params.push(Param {
662                name: pname,
663                ts_type,
664                optional,
665                default: value,
666                keyword_only,
667                ..Default::default()
668            });
669        }
670    }
671    infer_numbers(&mut params, node, source);
672    // A method that yields takes a block, even without `&block`.
673    if let Some(body) = node.child_by_field_name("body") {
674        let mut yields = false;
675        syntax::walk(body, |n| yields |= n.kind() == "yield");
676        if yields {
677            blocker.get_or_insert_with(|| "yields to a block".into());
678        }
679    }
680    Some(ExportedFn {
681        name,
682        file: path.to_string(),
683        line: syntax::line(node),
684        params,
685        returns,
686        prototype: Some(format!(
687            "{module}.{}({signature})",
688            text(node.child_by_field_name("name")?, source)
689        )),
690        blocker,
691        ..Default::default()
692    })
693}
694
695/// Parameters without a YARD type that the body uses in arithmetic become `number`.
696fn infer_numbers(params: &mut [Param], node: Node, source: &str) {
697    let Some(body) = node.child_by_field_name("body") else {
698        return;
699    };
700    let mut numeric: Vec<String> = Vec::new();
701    syntax::walk(body, |n| {
702        if n.kind() != "binary" {
703            return;
704        }
705        let op = n
706            .child_by_field_name("operator")
707            .map_or("", |o| text(o, source));
708        let (Some(l), Some(r)) = (
709            n.child_by_field_name("left"),
710            n.child_by_field_name("right"),
711        ) else {
712            return;
713        };
714        let literal = |x: Node| matches!(x.kind(), "integer" | "float");
715        if matches!(op, "-" | "*" | "/" | "**")
716            || (matches!(op, "+" | "%" | "<" | ">" | "<=" | ">=") && (literal(l) || literal(r)))
717        {
718            for side in [l, r] {
719                if side.kind() == "identifier" {
720                    numeric.push(text(side, source).to_string());
721                }
722            }
723        }
724    });
725    for p in params
726        .iter_mut()
727        .filter(|p| p.ts_type == "unknown" && numeric.contains(&p.name))
728    {
729        p.ts_type = "number".into();
730    }
731}
732
733/// Module functions: `def self.name` in a module or class, and methods after `module_function`
734/// or inside `class << self`. The receiver goes into `prototype` as `Module::Path.name(...)`.
735pub fn exports(path: &str, source: &str) -> Vec<ExportedFn> {
736    if !path.ends_with(".rb") {
737        return Vec::new();
738    }
739    let Some(tree) = syntax::parse(&language(), source) else {
740        return Vec::new();
741    };
742    let lines: Vec<&str> = source.lines().collect();
743    let mut out = Vec::new();
744    for child in named_children(tree.root_node()) {
745        if matches!(child.kind(), "module" | "class") {
746            namespace(path, child, source, &lines, &mut Vec::new(), &mut out);
747        }
748    }
749    out.sort_by_key(|f| f.line);
750    out
751}
752
753/// The module functions of one `module` or `class`, and of the namespaces nested in it.
754fn namespace(
755    path: &str,
756    node: Node,
757    source: &str,
758    lines: &[&str],
759    scope: &mut Vec<String>,
760    out: &mut Vec<ExportedFn>,
761) {
762    let Some(name) = node.child_by_field_name("name") else {
763        return;
764    };
765    scope.push(text(name, source).to_string());
766    let receiver = scope.join("::");
767    let is_module = node.kind() == "module";
768    let mut module_function = false;
769    let mut private = false;
770    let mut hidden: Vec<String> = Vec::new();
771    let mut found = Vec::new();
772    // Instance methods so far, for `module_function :name` after them.
773    let mut instance: Vec<Node> = Vec::new();
774    for item in node
775        .child_by_field_name("body")
776        .map(named_children)
777        .unwrap_or_default()
778    {
779        match item.kind() {
780            "identifier" if text(item, source) == "module_function" && is_module => {
781                module_function = true;
782            }
783            "identifier" if matches!(text(item, source), "private" | "protected") => {
784                private = true;
785            }
786            "call" if text(item, source).starts_with("private_class_method") => {
787                hidden.push(text(item, source).to_string());
788            }
789            "call" if is_module && text(item, source).starts_with("module_function") => {
790                let call = text(item, source);
791                for m in &instance {
792                    let name = m
793                        .child_by_field_name("name")
794                        .map_or("", |n| text(n, source));
795                    if call.contains(&format!(":{name}")) {
796                        found.extend(method_fn(path, &receiver, *m, source, lines));
797                    }
798                }
799            }
800            "singleton_method"
801                if item
802                    .child_by_field_name("object")
803                    .is_some_and(|o| text(o, source) == "self") =>
804            {
805                found.extend(method_fn(path, &receiver, item, source, lines));
806            }
807            "method" if module_function && !private => {
808                found.extend(method_fn(path, &receiver, item, source, lines));
809            }
810            "method" if !private => instance.push(item),
811            "singleton_class" => {
812                let mut private_here = false;
813                for m in item
814                    .child_by_field_name("body")
815                    .map(named_children)
816                    .unwrap_or_default()
817                {
818                    if m.kind() == "identifier" && text(m, source) == "private" {
819                        private_here = true;
820                    }
821                    if m.kind() == "method" && !private_here {
822                        found.extend(method_fn(path, &receiver, m, source, lines));
823                    }
824                }
825            }
826            "module" | "class" => namespace(path, item, source, lines, scope, out),
827            _ => {}
828        }
829    }
830    found.retain(|f| !hidden.iter().any(|h| h.contains(&format!(":{}", f.name))));
831    found.sort_by_key(|f| f.line);
832    out.extend(found);
833    scope.pop();
834}
835
836/// The receiver and method name of an export: `("Textkit::Words", "slugify")`.
837pub fn receiver(f: &ExportedFn) -> (String, String) {
838    let proto = f.prototype.as_deref().unwrap_or(&f.name);
839    let head = proto.split('(').next().unwrap_or(proto);
840    match head.rsplit_once('.') {
841        Some((recv, name)) => (recv.to_string(), name.to_string()),
842        None => ("Object".into(), f.name.clone()),
843    }
844}
845
846/// The parameter list as written: `text, sep = "-", max: nil`.
847pub fn signature(f: &ExportedFn) -> String {
848    let proto = f.prototype.as_deref().unwrap_or("");
849    proto
850        .split_once('(')
851        .map(|(_, rest)| rest.strip_suffix(')').unwrap_or(rest).to_string())
852        .unwrap_or_default()
853}
854
855#[cfg(test)]
856mod tests {
857    use super::*;
858
859    #[test]
860    fn yard_takes_the_name_and_the_type_in_either_order() {
861        let src = "module Pad\n  # @param text [String] the text\n  # @param width [Integer] the width\n  # @return [String]\n  def self.left(text, width) = text.rjust(width)\n\n  # @param [String] text the text\n  # @param [Integer] width the width\n  # @return [String]\n  def self.right(text, width) = text.ljust(width)\nend\n";
862        let fns = exports("pad.rb", src);
863        assert_eq!(fns.len(), 2, "{fns:?}");
864        for f in &fns {
865            let types: Vec<&str> = f.params.iter().map(|p| p.ts_type.as_str()).collect();
866            assert_eq!(types, ["string", "int"], "{}: {:?}", f.name, f.params);
867            assert_eq!(f.returns, "string", "{}", f.name);
868        }
869    }
870
871    #[test]
872    fn maps_yard_types() {
873        assert_eq!(yard_to_ts("String, nil"), "string | undefined");
874        assert_eq!(yard_to_ts("Array<Integer>"), "int[]");
875        assert_eq!(yard_to_ts("Hash{String => Integer}"), "Record<string, int>");
876    }
877
878    #[test]
879    fn finds_module_functions() {
880        let src = "module Textkit\n  # Slug.\n  # @param text [String]\n  # @return [String]\n  \
881                   def self.slugify(text, sep = \"-\", max: nil)\n    text\n  end\n\n  \
882                   def self.each_word(text)\n    yield text\n  end\n\n  \
883                   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  \
884                   class Stack\n    def push(x) = x\n  end\nend\n";
885        let fns = exports("lib/textkit.rb", src);
886        let names: Vec<(String, String)> = fns.iter().map(receiver).collect();
887        assert_eq!(
888            names,
889            [
890                ("Textkit".to_string(), "slugify".to_string()),
891                ("Textkit".to_string(), "each_word".to_string()),
892                ("Textkit::Nums".to_string(), "clamp".to_string()),
893            ]
894        );
895        let slug = &fns[0];
896        assert_eq!(slug.params[0].ts_type, "string");
897        assert_eq!(slug.params[1].ts_type, "string");
898        assert!(slug.params[2].keyword_only);
899        assert_eq!(slug.params[2].ts_type, "unknown | undefined");
900        assert_eq!(slug.returns, "string");
901        assert_eq!(signature(slug), "text, sep = \"-\", max: nil");
902        assert!(fns[1].blocker.is_some());
903        assert_eq!(fns[2].params[1].ts_type, "int");
904    }
905
906    #[test]
907    fn module_function_with_names_and_inferred_numbers() {
908        let src = "module Shellwords\n  def shellsplit(line)\n    line\n  end\n  module_function :shellsplit\n\n  \
909                   def helper(x) = x\n\n  def scale(x, factor)\n    x * factor\n  end\n  module_function :scale\nend\n";
910        let fns = exports("lib/shellwords.rb", src);
911        let names: Vec<&str> = fns.iter().map(|f| f.name.as_str()).collect();
912        assert_eq!(names, ["shellsplit", "scale"]);
913        assert_eq!(fns[0].params[0].ts_type, "unknown");
914        assert_eq!(fns[1].params[0].ts_type, "number");
915    }
916}