Skip to main content

rust_anything/lang/
csharp.rs

1//! C#: .csproj projects and their NuGet packages, `using` directives, risks, the
2//! package-to-crate table, and `public static` methods of public classes with C# types mapped
3//! into the TS-like type dialect. A unit is a folder.
4
5use std::collections::HashMap;
6use std::path::Path;
7
8use anyhow::Result;
9use tree_sitter::Node;
10
11use super::syntax::{self, named_children, text};
12use crate::risks::{Risk, regex_needs_fancy};
13use crate::ts::deps::CrateMatch;
14use crate::ts::discover::{FileKind, Package, SourceFile, Workspace};
15use crate::ts::exports::{ExportedFn, Param};
16use crate::ts::scan::{FileFacts, Import};
17
18fn language() -> tree_sitter::Language {
19    tree_sitter_c_sharp::LANGUAGE.into()
20}
21
22const SKIP_DIRS: &[&str] = &[
23    "bin",
24    "obj",
25    ".vs",
26    "packages",
27    "TestResults",
28    "node_modules",
29    "artifacts",
30];
31
32/// Packages a test project references.
33const TEST_PACKAGES: &[&str] = &[
34    "xunit",
35    "NUnit",
36    "MSTest.TestFramework",
37    "Microsoft.NET.Test.Sdk",
38];
39
40// ---- discovery -------------------------------------------------------------------------------
41
42fn attribute(tag: &str, name: &str) -> Option<String> {
43    let start = tag.find(&format!("{name}=\""))? + name.len() + 2;
44    let end = tag[start..].find('"')?;
45    Some(tag[start..start + end].to_string())
46}
47
48/// `Include` of each `<PackageReference>` in a project file, outside `<!-- -->` comments.
49pub fn package_references(text: &str) -> Vec<String> {
50    let text = super::syntax::without_xml_comments(text);
51    text.split("<PackageReference")
52        .skip(1)
53        .filter_map(|tag| attribute(tag.split('>').next().unwrap_or(""), "Include"))
54        .collect()
55}
56
57fn element(text: &str, tag: &str) -> Option<String> {
58    let value = text
59        .split(&format!("<{tag}>"))
60        .nth(1)?
61        .split(&format!("</{tag}>"))
62        .next()?
63        .trim();
64    (!value.is_empty()).then(|| value.to_string())
65}
66
67/// A project of tests: it references a test framework or says `IsTestProject`.
68pub fn is_test_project(text: &str) -> bool {
69    let text = super::syntax::without_xml_comments(text);
70    package_references(&text)
71        .iter()
72        .any(|d| TEST_PACKAGES.iter().any(|t| d.starts_with(t)))
73        || element(&text, "IsTestProject").as_deref() == Some("true")
74}
75
76pub fn discover(root: &Path) -> Result<Workspace> {
77    let mut packages: Vec<Package> = Vec::new();
78    let mut tests: Vec<String> = Vec::new();
79    let mut files = Vec::new();
80    let walker = crate::walk::filtered(root, |e| {
81        !(e.file_type().is_some_and(|t| t.is_dir())
82            && SKIP_DIRS.contains(&e.file_name().to_string_lossy().as_ref()))
83    })
84    .hidden(true)
85    .require_git(false)
86    .build();
87    for entry in walker.flatten() {
88        if !entry.file_type().is_some_and(|t| t.is_file()) {
89            continue;
90        }
91        let Ok(rel) = entry.path().strip_prefix(root) else {
92            continue;
93        };
94        let rel = rel.to_string_lossy().replace('\\', "/");
95        let name = rel.rsplit('/').next().unwrap_or(&rel).to_string();
96        let dir = rel
97            .rsplit_once('/')
98            .map_or(String::new(), |(d, _)| d.to_string());
99        if let Some(stem) = name.strip_suffix(".csproj") {
100            let text = std::fs::read_to_string(entry.path()).unwrap_or_default();
101            let deps = package_references(&text);
102            let is_test = is_test_project(&text);
103            if is_test {
104                tests.push(dir.clone());
105            }
106            let (deps, dev_deps) = if is_test {
107                (Vec::new(), deps)
108            } else {
109                (deps, Vec::new())
110            };
111            packages.push(Package {
112                name: element(&text, "AssemblyName").unwrap_or_else(|| stem.to_string()),
113                src_root: dir.clone(),
114                dir,
115                deps,
116                dev_deps,
117                namespaces: Vec::new(),
118            });
119        } else if name.ends_with(".cs") {
120            files.push(rel);
121        }
122    }
123    if packages.is_empty() {
124        packages.push(Package {
125            name: root
126                .file_name()
127                .map_or_else(|| "root".into(), |n| n.to_string_lossy().into_owned()),
128            dir: String::new(),
129            src_root: String::new(),
130            deps: Vec::new(),
131            dev_deps: Vec::new(),
132            namespaces: Vec::new(),
133        });
134    }
135    packages.sort_by(|a, b| a.dir.cmp(&b.dir));
136    packages.dedup_by(|a, b| a.dir == b.dir);
137    files.sort();
138    let under = |path: &str, dir: &str| dir.is_empty() || path.starts_with(&format!("{dir}/"));
139    let files = files
140        .into_iter()
141        .map(|path| {
142            let package = packages
143                .iter()
144                .enumerate()
145                .filter(|(_, p)| under(&path, &p.dir))
146                .max_by_key(|(_, p)| p.dir.len())
147                .map_or(0, |(i, _)| i);
148            let file_name = path.rsplit('/').next().unwrap_or(&path);
149            let is_test = tests.contains(&packages[package].dir)
150                || file_name.ends_with("Tests.cs")
151                || file_name.ends_with("Test.cs");
152            SourceFile {
153                path,
154                package,
155                kind: if is_test {
156                    FileKind::Test
157                } else {
158                    FileKind::Source
159                },
160            }
161        })
162        .collect();
163    Ok(Workspace { packages, files })
164}
165
166// ---- risks and imports -----------------------------------------------------------------------
167
168fn regex_call(node: Node, source: &str) -> bool {
169    let callee = node
170        .child_by_field_name("function")
171        .map_or("", |f| text(f, source));
172    callee.starts_with("Regex.")
173        && ["IsMatch", "Match", "Matches", "Replace", "Split"]
174            .iter()
175            .any(|m| callee.ends_with(&format!(".{m}")))
176}
177
178fn pattern_risk(pattern: Option<Node>, source: &str) -> Option<Risk> {
179    let literal = match pattern.map(|p| (p.kind(), text(p, source))) {
180        Some(("string_literal", p)) => p.trim_matches('"').replace("\\\\", "\\"),
181        Some(("verbatim_string_literal", p)) => p.trim_start_matches('@').trim_matches('"').into(),
182        _ => return Some(Risk::DynamicRegex),
183    };
184    regex_needs_fancy(&literal, "").then_some(Risk::RegexSyntax)
185}
186
187pub fn scan(source: &str) -> FileFacts {
188    let mut facts = FileFacts {
189        loc: syntax::loc(source, crate::lang::Lang::Csharp),
190        ..FileFacts::default()
191    };
192    let Some(tree) = syntax::parse(&language(), source) else {
193        return facts;
194    };
195    let root = tree.root_node();
196    facts.parse_errors = usize::from(root.has_error());
197    let add = |facts: &mut FileFacts, risk: Risk, node: Node| {
198        facts
199            .risks
200            .entry(risk)
201            .or_default()
202            .push(syntax::line(node))
203    };
204    syntax::walk(root, |node| match node.kind() {
205        "using_directive" => {
206            let Some(name) = named_children(node)
207                .into_iter()
208                .rfind(|c| matches!(c.kind(), "qualified_name" | "identifier"))
209            else {
210                return;
211            };
212            let spec = text(name, source).to_string();
213            let is_static = text(node, source).contains("using static");
214            match spec.as_str() {
215                s if s.starts_with("System.Reflection") => add(&mut facts, Risk::Reflection, node),
216                s if s.starts_with("System.Threading") => add(&mut facts, Risk::Concurrency, node),
217                s if s.starts_with("System.Text.RegularExpressions") => {
218                    add(&mut facts, Risk::RegexSyntax, node)
219                }
220                _ => {}
221            }
222            if !is_static || spec.contains('.') {
223                facts.imports.push(Import {
224                    specifier: spec,
225                    type_only: false,
226                    dynamic: false,
227                });
228            }
229        }
230        "lock_statement" => add(&mut facts, Risk::Concurrency, node),
231        "modifier" if text(node, source) == "volatile" => add(&mut facts, Risk::Concurrency, node),
232        "modifier" if text(node, source) == "async" => add(&mut facts, Risk::Async, node),
233        "modifier" if text(node, source) == "unsafe" => add(&mut facts, Risk::Pointers, node),
234        "unsafe_statement" | "pointer_type" | "fixed_statement" => {
235            add(&mut facts, Risk::Pointers, node)
236        }
237        "await_expression" => add(&mut facts, Risk::Async, node),
238        "yield_statement" => add(&mut facts, Risk::Generators, node),
239        "query_expression" => add(&mut facts, Risk::Generators, node),
240        "null_literal" => add(&mut facts, Risk::NullReferences, node),
241        "is_pattern_expression" | "is_expression" | "as_expression" | "cast_expression" => {
242            add(&mut facts, Risk::DynamicTyping, node)
243        }
244        "identifier" if text(node, source) == "dynamic" => {
245            add(&mut facts, Risk::DynamicTyping, node)
246        }
247        "predefined_type" if text(node, source) == "decimal" => {
248            add(&mut facts, Risk::NumberSemantics, node)
249        }
250        "lambda_expression" | "anonymous_method_expression" => {
251            add(&mut facts, Risk::Callbacks, node)
252        }
253        "throw_statement" | "throw_expression" | "try_statement" | "catch_clause" => {
254            add(&mut facts, Risk::Exceptions, node)
255        }
256        "base_list" => add(&mut facts, Risk::ClassInheritance, node),
257        "binary_expression" => {
258            let op = node
259                .child_by_field_name("operator")
260                .map_or("", |o| text(o, source));
261            match op {
262                "/" | "%" => add(&mut facts, Risk::DivisionSemantics, node),
263                "<<" | ">>" | ">>>" | "*" => add(&mut facts, Risk::IntegerSemantics, node),
264                _ => {}
265            }
266        }
267        "object_creation_expression" => {
268            let ty = node
269                .child_by_field_name("type")
270                .map_or("", |t| text(t, source));
271            match ty {
272                "Regex" => {
273                    let pattern = node
274                        .child_by_field_name("arguments")
275                        .and_then(|a| named_children(a).into_iter().next())
276                        .and_then(|a| named_children(a).into_iter().next());
277                    if let Some(risk) = pattern_risk(pattern, source) {
278                        add(&mut facts, risk, node);
279                    }
280                }
281                "HashSet" | "Dictionary" => add(&mut facts, Risk::UnorderedIteration, node),
282                t if t.starts_with("HashSet<") || t.starts_with("Dictionary<") => {
283                    add(&mut facts, Risk::UnorderedIteration, node)
284                }
285                _ => {}
286            }
287        }
288        "invocation_expression" => {
289            if regex_call(node, source) {
290                let pattern = node
291                    .child_by_field_name("arguments")
292                    .and_then(|a| named_children(a).into_iter().nth(1))
293                    .and_then(|a| named_children(a).into_iter().next());
294                if let Some(risk) = pattern_risk(pattern, source) {
295                    add(&mut facts, risk, node);
296                }
297                return;
298            }
299            let callee = node
300                .child_by_field_name("function")
301                .map_or("", |f| text(f, source));
302            let method = callee.rsplit('.').next().unwrap_or(callee);
303            match method {
304                "Substring" | "IndexOf" | "LastIndexOf" | "Remove" | "Insert" | "PadLeft"
305                | "PadRight" => add(&mut facts, Risk::StringOffsets, node),
306                "GetType" | "GetMethod" | "GetProperty" | "Invoke" | "CreateInstance" => {
307                    add(&mut facts, Risk::Reflection, node)
308                }
309                "GetHashCode" => add(&mut facts, Risk::IntegerSemantics, node),
310                _ => {}
311            }
312        }
313        "for_statement" | "foreach_statement" | "while_statement" | "do_statement" => {
314            facts.loops += 1
315        }
316        _ => {}
317    });
318    facts
319}
320
321/// The file's `using` directives as written (`using static`, aliases and `global using` too).
322pub fn using_directives(source: &str) -> Vec<String> {
323    let Some(tree) = syntax::parse(&language(), source) else {
324        return Vec::new();
325    };
326    let mut out = Vec::new();
327    syntax::walk(tree.root_node(), |node| {
328        if node.kind() == "using_directive" {
329            out.push(text(node, source).trim().to_string());
330        }
331    });
332    out
333}
334
335/// The folder a namespace names, relative to a project: `Acme.Textkit.Text` in the project
336/// `Acme.Textkit` is its `Text/` folder.
337fn namespace_dir(namespace: &str, project: &str) -> String {
338    let rest = namespace
339        .strip_prefix(project)
340        .map_or(namespace, |r| r.trim_start_matches('.'));
341    rest.replace('.', "/")
342}
343
344pub fn resolve(spec: &str, index: &HashMap<&str, usize>, ws: &Workspace) -> super::Resolution {
345    let first = spec.split('.').next().unwrap_or("");
346    if first == "System"
347        || (first == "Microsoft"
348            && !spec.starts_with("Microsoft.Extensions")
349            && !spec.starts_with("Microsoft.AspNetCore")
350            && !spec.starts_with("Microsoft.EntityFrameworkCore"))
351    {
352        return super::Resolution::Stdlib;
353    }
354    for p in &ws.packages {
355        for dir in [namespace_dir(spec, &p.name), spec.replace('.', "/")] {
356            if dir.is_empty() {
357                continue;
358            }
359            let found = index
360                .iter()
361                .filter(|(f, _)| {
362                    let folder = f.rsplit_once('/').map_or("", |(d, _)| d);
363                    (p.dir.is_empty() || folder.starts_with(&format!("{}/", p.dir)))
364                        && (folder == dir || folder.ends_with(&format!("/{dir}")))
365                })
366                .min_by_key(|(f, _)| **f);
367            if let Some((_, i)) = found {
368                return super::Resolution::File(*i);
369            }
370        }
371    }
372    if ws.packages.iter().any(|p| spec == p.name) {
373        return super::Resolution::Stdlib;
374    }
375    super::Resolution::External(spec.split('.').take(2).collect::<Vec<_>>().join("."))
376}
377
378/// Rust counterparts of common NuGet packages, by package id or namespace.
379pub fn lookup(name: &str) -> Option<CrateMatch> {
380    crate::crates::find("csharp", name)
381}
382
383// ---- exports ---------------------------------------------------------------------------------
384
385fn split_top(text: &str) -> Vec<String> {
386    let mut out = Vec::new();
387    let mut depth = 0i32;
388    let mut current = String::new();
389    for c in text.chars() {
390        match c {
391            '<' | '(' => depth += 1,
392            '>' | ')' => depth -= 1,
393            ',' if depth == 0 => {
394                out.push(current.trim().to_string());
395                current.clear();
396                continue;
397            }
398            _ => {}
399        }
400        current.push(c);
401    }
402    if !current.trim().is_empty() {
403        out.push(current.trim().to_string());
404    }
405    out
406}
407
408/// A record's or plain class's `(property, C# type)` pairs; `None` when it cannot cross.
409type Members = Option<Vec<(String, String)>>;
410
411thread_local! {
412    static SHAPES: std::cell::RefCell<HashMap<String, Members>> =
413        std::cell::RefCell::new(HashMap::new());
414}
415
416fn shape_members(node: Node, source: &str) -> Members {
417    let mods = modifiers(node, source);
418    if !mods.iter().any(|m| m == "public")
419        || mods
420            .iter()
421            .any(|m| matches!(m.as_str(), "static" | "abstract"))
422    {
423        return None;
424    }
425    let children = named_children(node);
426    if children
427        .iter()
428        .any(|c| matches!(c.kind(), "type_parameter_list" | "base_list"))
429    {
430        return None;
431    }
432    let mut members = Vec::new();
433    let positional = children.iter().find(|c| c.kind() == "parameter_list");
434    if let Some(list) = positional {
435        if node.kind() != "record_declaration" {
436            return None;
437        }
438        for p in named_children(*list) {
439            let ty = p.child_by_field_name("type")?;
440            let name = p.child_by_field_name("name")?;
441            members.push((text(name, source).to_string(), text(ty, source).to_string()));
442        }
443    }
444    if let Some(body) = node.child_by_field_name("body") {
445        for m in named_children(body) {
446            let mods = modifiers(m, source);
447            let public = mods.iter().any(|m| m == "public") && !mods.iter().any(|m| m == "static");
448            match m.kind() {
449                "constructor_declaration" => {
450                    let takes = m
451                        .child_by_field_name("parameters")
452                        .is_some_and(|l| !named_children(l).is_empty());
453                    if takes {
454                        return None;
455                    }
456                }
457                "property_declaration" if public => {
458                    let Some(accessors) = m.child_by_field_name("accessors") else {
459                        continue;
460                    };
461                    let names: Vec<&str> = named_children(accessors)
462                        .into_iter()
463                        .filter_map(|a| a.child_by_field_name("name").map(|n| text(n, source)))
464                        .collect();
465                    let auto = named_children(accessors)
466                        .into_iter()
467                        .all(|a| a.child_by_field_name("body").is_none());
468                    if !(auto
469                        && names.contains(&"get")
470                        && names.iter().any(|n| matches!(*n, "set" | "init")))
471                    {
472                        continue;
473                    }
474                    let ty = m.child_by_field_name("type")?;
475                    let name = m.child_by_field_name("name")?;
476                    members.push((text(name, source).to_string(), text(ty, source).to_string()));
477                }
478                "field_declaration" if public => return None,
479                _ => {}
480            }
481        }
482    }
483    (!members.is_empty()).then_some(members)
484}
485
486fn collect_shapes(
487    node: Node,
488    source: &str,
489    out: &mut HashMap<String, Option<Vec<(String, String)>>>,
490) {
491    for child in named_children(node) {
492        match child.kind() {
493            "record_declaration" | "class_declaration" | "struct_declaration" => {
494                if let Some(name) = child.child_by_field_name("name") {
495                    let name = text(name, source).to_string();
496                    let members = shape_members(child, source);
497                    out.entry(name).and_modify(|e| *e = None).or_insert(members);
498                }
499                if let Some(body) = child.child_by_field_name("body") {
500                    collect_shapes(body, source, out);
501                }
502            }
503            "namespace_declaration" | "file_scoped_namespace_declaration" | "declaration_list" => {
504                collect_shapes(child, source, out);
505            }
506            _ => {}
507        }
508    }
509}
510
511/// Makes `exports` read the project's records and plain classes (public auto-properties, no
512/// constructor arguments) on this thread, so methods taking or returning them can cross as JSON
513/// objects.
514pub fn use_shapes(root: &Path) {
515    let mut shapes = HashMap::new();
516    if let Ok(ws) = discover(root) {
517        for file in ws.files.iter().filter(|f| f.kind == FileKind::Source) {
518            let Ok(source) = std::fs::read_to_string(root.join(&file.path)) else {
519                continue;
520            };
521            if let Some(tree) = syntax::parse(&language(), &source) {
522                collect_shapes(tree.root_node(), &source, &mut shapes);
523            }
524        }
525    }
526    SHAPES.with(|s| *s.borrow_mut() = shapes);
527}
528
529fn shape_ts(name: &str, depth: usize) -> Option<Result<String, String>> {
530    let members = SHAPES.with(|s| s.borrow().get(name).cloned())?;
531    let Some(members) = members else {
532        return Some(Err(format!(
533            "uses the type `{name}`, which is not a plain record or class (generic, inherited, \
534             with constructor arguments, public fields, or declared twice)"
535        )));
536    };
537    if depth > 8 {
538        return Some(Err(format!("uses the recursive type `{name}`")));
539    }
540    let mut fields = Vec::new();
541    for (field, ty) in members {
542        match to_ts(&ty, depth + 1) {
543            Ok(t) => fields.push(format!("{field}: {t}")),
544            Err(reason) => return Some(Err(format!("`{name}.{field}` {reason}"))),
545        }
546    }
547    Some(Ok(format!("{{ {} }}", fields.join("; "))))
548}
549
550/// A C# type in the TS-like dialect, or why the bridge cannot carry it.
551pub fn csharp_to_ts(t: &str) -> Result<String, String> {
552    to_ts(t, 0)
553}
554
555fn to_ts(t: &str, depth: usize) -> Result<String, String> {
556    let csharp_to_ts = |t: &str| to_ts(t, depth);
557    let t = t.trim();
558    if let Some(inner) = t.strip_suffix('?') {
559        return csharp_to_ts(inner).map(|i| format!("{i} | undefined"));
560    }
561    if let Some(inner) = t.strip_suffix("[]") {
562        return csharp_to_ts(inner).map(|i| {
563            if i.contains(' ') {
564                format!("({i})[]")
565            } else {
566                format!("{i}[]")
567            }
568        });
569    }
570    if t.starts_with('(') {
571        return Err("uses a tuple".into());
572    }
573    let (head, args) = match t.find('<') {
574        Some(i) if t.ends_with('>') => (&t[..i], split_top(&t[i + 1..t.len() - 1])),
575        _ => (t, Vec::new()),
576    };
577    let head = head.trim().rsplit('.').next().unwrap_or(head);
578    let arg = |i: usize| -> Result<String, String> {
579        args.get(i)
580            .map_or_else(|| Err(format!("raw `{head}`")), |a| csharp_to_ts(a))
581    };
582    Ok(match head {
583        "string" | "String" => "string".into(),
584        "int" | "long" | "short" | "byte" | "sbyte" | "uint" | "ushort" | "Int32" | "Int64"
585        | "Int16" | "Byte" | "SByte" | "UInt32" | "UInt16" => "int".into(),
586        "ulong" | "UInt64" | "nint" | "nuint" => {
587            return Err(format!("uses `{head}`, wider than a JSON-safe integer"));
588        }
589        "double" | "float" | "Double" | "Single" => "number".into(),
590        "decimal" | "Decimal" => {
591            return Err("uses `decimal`, a 128-bit decimal no JSON number keeps exactly".into());
592        }
593        "bool" | "Boolean" => "boolean".into(),
594        "void" => "void".into(),
595        "List"
596        | "IList"
597        | "IReadOnlyList"
598        | "ICollection"
599        | "IReadOnlyCollection"
600        | "IEnumerable"
601        | "HashSet"
602        | "ISet" => {
603            let inner = arg(0)?;
604            if inner.contains(' ') {
605                format!("({inner})[]")
606            } else {
607                format!("{inner}[]")
608            }
609        }
610        "Dictionary" | "IDictionary" | "IReadOnlyDictionary" | "SortedDictionary" => {
611            if arg(0)? != "string" {
612                return Err(format!("`{t}`: JSON object keys are strings"));
613            }
614            format!("Record<string, {}>", arg(1)?)
615        }
616        "Nullable" => format!("{} | undefined", arg(0)?),
617        "char" | "Char" => return Err("uses `char`, a UTF-16 code unit".into()),
618        "object" | "Object" | "dynamic" => {
619            return Err("takes or returns `object`: values of any type".into());
620        }
621        "Func" | "Action" | "Predicate" | "Comparison" | "Delegate" => {
622            return Err("takes or returns a delegate".into());
623        }
624        "Task" | "ValueTask" => return Err("is async (`Task`)".into()),
625        "IAsyncEnumerable" | "IEnumerator" | "Span" | "ReadOnlySpan" | "Memory" => {
626            return Err(format!("uses `{head}`"));
627        }
628        other => {
629            if args.is_empty()
630                && let Some(shape) = shape_ts(other, depth)
631            {
632                return shape;
633            }
634            return Err(format!("uses the type `{other}`"));
635        }
636    })
637}
638
639fn modifiers(node: Node, source: &str) -> Vec<String> {
640    named_children(node)
641        .into_iter()
642        .filter(|c| c.kind() == "modifier")
643        .map(|c| text(c, source).to_string())
644        .collect()
645}
646
647fn method_export(
648    method: Node,
649    qualified: &str,
650    path: &str,
651    source: &str,
652    out: &mut Vec<ExportedFn>,
653) {
654    let mods = modifiers(method, source);
655    if !(mods.iter().any(|m| m == "public") && mods.iter().any(|m| m == "static")) {
656        return;
657    }
658    let Some(name) = method
659        .child_by_field_name("name")
660        .map(|n| text(n, source).to_string())
661    else {
662        return;
663    };
664    let mut blocker = None;
665    if method.child_by_field_name("type_parameters").is_some() {
666        blocker = Some("generic".to_string());
667    }
668    let mut params = Vec::new();
669    let mut signature = Vec::new();
670    if let Some(list) = method.child_by_field_name("parameters") {
671        for p in named_children(list) {
672            if p.kind() != "parameter" {
673                blocker.get_or_insert_with(|| "is variadic (`params`)".into());
674                continue;
675            }
676            let all = text(p, source);
677            let words: Vec<&str> = all.split_whitespace().collect();
678            if words
679                .first()
680                .is_some_and(|w| matches!(*w, "ref" | "out" | "in"))
681            {
682                blocker.get_or_insert_with(|| "takes a parameter by reference".into());
683            }
684            if words.first() == Some(&"params") {
685                blocker.get_or_insert_with(|| "is variadic (`params`)".into());
686            }
687            let ty = p
688                .child_by_field_name("type")
689                .map_or("", |t| text(t, source))
690                .to_string();
691            let pname = p
692                .child_by_field_name("name")
693                .map_or("", |n| text(n, source))
694                .to_string();
695            let ts_type = csharp_to_ts(&ty).unwrap_or_else(|reason| {
696                blocker.get_or_insert(reason);
697                "unknown".into()
698            });
699            let after = p
700                .child_by_field_name("name")
701                .map_or(usize::MAX, |n| n.end_byte());
702            let default = named_children(p)
703                .into_iter()
704                .find(|c| c.start_byte() >= after)
705                .map(|d| text(d, source).to_string());
706            signature.push(format!("{ty} {pname}"));
707            params.push(Param {
708                name: pname,
709                ts_type,
710                optional: default.is_some(),
711                default,
712                native_type: Some(ty),
713                ..Default::default()
714            });
715        }
716    }
717    let ret = method
718        .child_by_field_name("returns")
719        .map_or("void", |t| text(t, source))
720        .to_string();
721    let returns = csharp_to_ts(&ret).unwrap_or_else(|reason| {
722        blocker.get_or_insert(reason);
723        "unknown".into()
724    });
725    out.push(ExportedFn {
726        prototype: Some(format!("{qualified}.{name}({})", signature.join(", "))),
727        name,
728        file: path.to_string(),
729        line: syntax::line(method),
730        params,
731        returns,
732        native_return: Some(ret),
733        blocker,
734        ..Default::default()
735    });
736}
737
738fn collect(node: Node, namespace: &str, path: &str, source: &str, out: &mut Vec<ExportedFn>) {
739    let mut namespace = namespace.to_string();
740    for child in named_children(node) {
741        match child.kind() {
742            "file_scoped_namespace_declaration" => {
743                namespace = child
744                    .child_by_field_name("name")
745                    .map_or(String::new(), |n| text(n, source).to_string());
746            }
747            "namespace_declaration" => {
748                let name = child
749                    .child_by_field_name("name")
750                    .map_or("", |n| text(n, source));
751                let inner = if namespace.is_empty() {
752                    name.to_string()
753                } else {
754                    format!("{namespace}.{name}")
755                };
756                if let Some(body) = child.child_by_field_name("body") {
757                    collect(body, &inner, path, source, out);
758                }
759            }
760            "class_declaration" => {
761                if !modifiers(child, source).iter().any(|m| m == "public") {
762                    continue;
763                }
764                let Some(class) = child
765                    .child_by_field_name("name")
766                    .map(|n| text(n, source).to_string())
767                else {
768                    continue;
769                };
770                let qualified = if namespace.is_empty() {
771                    class
772                } else {
773                    format!("{namespace}.{class}")
774                };
775                if let Some(body) = child.child_by_field_name("body") {
776                    for member in named_children(body) {
777                        if member.kind() == "method_declaration" {
778                            method_export(member, &qualified, path, source, out);
779                        }
780                    }
781                }
782            }
783            _ => {}
784        }
785    }
786}
787
788/// `public static` methods of the file's public classes. `prototype` holds the declaring class's
789/// fully qualified name and the signature: `Acme.Text.Slug.Slugify(string text)`.
790pub fn exports(path: &str, source: &str) -> Vec<ExportedFn> {
791    if !path.ends_with(".cs") {
792        return Vec::new();
793    }
794    let Some(tree) = syntax::parse(&language(), source) else {
795        return Vec::new();
796    };
797    let mut out = Vec::new();
798    collect(tree.root_node(), "", path, source, &mut out);
799    // The Rust side names each export by its name alone: an overload would pick one signature.
800    // Block every overload of a method, not just the later declaration, as Java and Kotlin do.
801    // Methods are told apart by class (the prototype up to `(`), so `Json.Parse` and
802    // `Xml.Parse` are not overloads; `bridge` reports such a clash itself.
803    let method = |f: &ExportedFn| -> String {
804        let prototype = f.prototype.as_deref().unwrap_or(&f.name);
805        prototype.split('(').next().unwrap_or(prototype).to_string()
806    };
807    let mut counts: std::collections::BTreeMap<String, usize> = std::collections::BTreeMap::new();
808    for f in &out {
809        *counts.entry(method(f)).or_default() += 1;
810    }
811    for f in &mut out {
812        if counts.get(&method(f)).copied().unwrap_or(0) > 1 {
813            f.blocker = Some(super::OVERLOADED.into());
814        }
815    }
816    out
817}
818
819#[cfg(test)]
820mod tests {
821    use super::*;
822
823    #[test]
824    fn every_overload_of_a_name_is_blocked() {
825        let src = "namespace Acme;\npublic static class Nums\n{\n\
826                   public static int Add(int a, int b) { return a + b; }\n\
827                   public static double Add(double a, double b) { return a + b; }\n\
828                   public static int One() { return 1; }\n}\n";
829        let fns = exports("src/Nums.cs", src);
830        let blocked: Vec<(&str, bool)> = fns
831            .iter()
832            .map(|f| (f.name.as_str(), f.blocker.is_some()))
833            .collect();
834        assert_eq!(blocked, [("Add", true), ("Add", true), ("One", false)]);
835    }
836
837    #[test]
838    fn methods_of_two_classes_are_not_overloads() {
839        let src = "namespace Acme;\npublic static class Json { public static int Parse(string s) { return 1; } }\n\
840                   public static class Xml { public static int Parse(string s) { return 2; } }\n";
841        let fns = exports("src/Parsers.cs", src);
842        assert_eq!(fns.len(), 2);
843        assert!(fns.iter().all(|f| f.blocker.is_none()), "{fns:?}");
844    }
845
846    #[test]
847    fn maps_types() {
848        assert_eq!(csharp_to_ts("List<string>").unwrap(), "string[]");
849        assert_eq!(
850            csharp_to_ts("Dictionary<string, List<int>>").unwrap(),
851            "Record<string, int[]>"
852        );
853        assert_eq!(csharp_to_ts("double[]").unwrap(), "number[]");
854        assert_eq!(csharp_to_ts("int?").unwrap(), "int | undefined");
855        assert!(csharp_to_ts("decimal").is_err());
856        assert!(csharp_to_ts("Task<int>").is_err());
857        assert!(csharp_to_ts("Point").is_err());
858    }
859
860    #[test]
861    fn finds_public_static_methods_in_namespaces() {
862        let src = "using System.Collections.Generic;\nnamespace Acme.Text;\n\
863                   public static class Slug {\n\
864                   public static string Slugify(string text, int max) => text;\n\
865                   public static List<string> Words(string text) { return new(); }\n\
866                   public static T Id<T>(T x) => x;\n\
867                   public static void Swap(ref int a, ref int b) {}\n\
868                   static int Hidden() => 1;\n\
869                   public int Instance() => 1;\n}\n\
870                   internal static class Private { public static int No() => 1; }\n";
871        let fns = exports("src/Text/Slug.cs", src);
872        let names: Vec<&str> = fns.iter().map(|f| f.name.as_str()).collect();
873        assert_eq!(names, ["Slugify", "Words", "Id", "Swap"]);
874        assert_eq!(fns[0].params[1].ts_type, "int");
875        assert_eq!(
876            fns[0].prototype.as_deref(),
877            Some("Acme.Text.Slug.Slugify(string text, int max)")
878        );
879        assert_eq!(fns[1].returns, "string[]");
880        assert!(fns[2].blocker.is_some());
881        assert!(
882            fns[3]
883                .blocker
884                .as_deref()
885                .is_some_and(|b| b.contains("reference"))
886        );
887
888        let block = "namespace Acme { namespace Text { public class A { public static bool B() => true; } } }";
889        let fns = exports("A.cs", block);
890        assert_eq!(fns[0].prototype.as_deref(), Some("Acme.Text.A.B()"));
891    }
892
893    #[test]
894    fn flags_risks_and_usings() {
895        let src = "using System.Text.RegularExpressions;\nusing Newtonsoft.Json;\n\
896                   class C { async Task<int> F(string s) { lock (this) {} \
897                   var r = Regex.IsMatch(s, @\"(?<=a)b\"); decimal d = 1m; \
898                   return s.Substring(1).Length / 2; } }";
899        let facts = scan(src);
900        let specs: Vec<&str> = facts.imports.iter().map(|i| i.specifier.as_str()).collect();
901        assert_eq!(specs, ["System.Text.RegularExpressions", "Newtonsoft.Json"]);
902        for risk in [
903            Risk::Async,
904            Risk::Concurrency,
905            Risk::RegexSyntax,
906            Risk::NumberSemantics,
907            Risk::StringOffsets,
908            Risk::DivisionSemantics,
909        ] {
910            assert!(
911                facts.risks.contains_key(&risk),
912                "{risk:?}: {:?}",
913                facts.risks
914            );
915        }
916    }
917
918    #[test]
919    fn classifies_test_sources_in_a_root_project_without_test_suffixes() {
920        let dir = std::env::temp_dir().join(format!(
921            "rust-anything-csharp-test-root-{}",
922            std::process::id()
923        ));
924        std::fs::create_dir_all(dir.join("src")).unwrap();
925        std::fs::write(
926            dir.join("Tests.csproj"),
927            "<Project><IsTestProject>true</IsTestProject></Project>",
928        )
929        .unwrap();
930        std::fs::write(dir.join("ValidatorCases.cs"), "class ValidatorCases {}").unwrap();
931        std::fs::write(dir.join("src/Library.csproj"), "<Project />").unwrap();
932        std::fs::write(dir.join("src/Library.cs"), "public class Library {}").unwrap();
933        let ws = discover(&dir).unwrap();
934        std::fs::remove_dir_all(dir).unwrap();
935        assert_eq!(ws.files[0].kind, FileKind::Test);
936        assert_eq!(ws.files[1].kind, FileKind::Source);
937    }
938
939    #[test]
940    fn resolves_records_and_plain_classes() {
941        let src = "namespace A;\n\
942                   public record Point(double X, double Y);\n\
943                   public class Box { public string Label { get; set; } = \"\"; public int[] Sizes { get; init; } }\n\
944                   public class Made { public Made(int n) {} public int N { get; set; } }\n\
945                   public class Kid : Box { public int Age { get; set; } }\n\
946                   public class Holder { public decimal Amount { get; set; } }\n";
947        let tree = syntax::parse(&language(), src).unwrap();
948        let mut shapes = HashMap::new();
949        collect_shapes(tree.root_node(), src, &mut shapes);
950        SHAPES.with(|s| *s.borrow_mut() = shapes);
951        assert_eq!(csharp_to_ts("Point").unwrap(), "{ X: number; Y: number }");
952        assert_eq!(
953            csharp_to_ts("List<Box>").unwrap(),
954            "({ Label: string; Sizes: int[] })[]"
955        );
956        assert!(
957            csharp_to_ts("Made")
958                .unwrap_err()
959                .contains("not a plain record")
960        );
961        assert!(
962            csharp_to_ts("Kid")
963                .unwrap_err()
964                .contains("not a plain record")
965        );
966        assert!(
967            csharp_to_ts("Holder")
968                .unwrap_err()
969                .contains("`Holder.Amount` uses `decimal`")
970        );
971        SHAPES.with(|s| s.borrow_mut().clear());
972    }
973
974    #[test]
975    fn reads_package_references() {
976        let proj = r#"<Project Sdk="Microsoft.NET.Sdk"><ItemGroup>
977            <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
978            <PackageReference Include="Serilog" Version="4.0.0"></PackageReference>
979            </ItemGroup></Project>"#;
980        assert_eq!(package_references(proj), ["Newtonsoft.Json", "Serilog"]);
981    }
982}