1use 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;
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_go::LANGUAGE.into()
19}
20
21const SKIP_DIRS: &[&str] = &["vendor", "testdata", "node_modules", "target", ".git"];
22
23pub(crate) fn mod_directive<'a>(go_mod: &'a str, directive: &str) -> Option<&'a str> {
27 go_mod.lines().find_map(|line| {
28 let mut words = line.split_whitespace();
29 if words.next()? != directive {
30 return None;
31 }
32 words.next().filter(|word| !word.starts_with("//"))
33 })
34}
35
36pub fn module_path(go_mod: &str) -> Option<String> {
38 mod_directive(go_mod, "module").map(|path| path.trim_matches('"').to_string())
39}
40
41fn requirements(go_mod: &str) -> Vec<String> {
42 let mut out = Vec::new();
43 let mut in_block = false;
44 for line in go_mod.lines() {
45 let line = line.trim();
46 if line.starts_with("require (") {
47 in_block = true;
48 continue;
49 }
50 if in_block && line == ")" {
51 in_block = false;
52 continue;
53 }
54 let spec = if in_block {
55 Some(line)
56 } else {
57 line.strip_prefix("require ")
58 };
59 if let Some(spec) = spec
60 && !line.contains("// indirect")
61 && let Some(name) = spec.split_whitespace().next()
62 && !name.is_empty()
63 && !name.starts_with("//")
64 {
65 out.push(name.to_string());
66 }
67 }
68 out
69}
70
71pub fn discover(root: &Path) -> Result<Workspace> {
72 let mut modules = Vec::new();
73 let mut files = Vec::new();
74 let walker = crate::walk::filtered(root, |e| {
75 let name = e.file_name().to_string_lossy();
76 !(e.file_type().is_some_and(|t| t.is_dir())
77 && (SKIP_DIRS.contains(&name.as_ref()) || name.starts_with('_')))
78 })
79 .hidden(true)
80 .require_git(false)
81 .build();
82 for entry in walker.flatten() {
83 if !entry.file_type().is_some_and(|t| t.is_file()) {
84 continue;
85 }
86 let Ok(rel) = entry.path().strip_prefix(root) else {
87 continue;
88 };
89 let rel = rel.to_string_lossy().replace('\\', "/");
90 let name = rel.rsplit('/').next().unwrap_or(&rel);
91 let dir = rel
92 .rsplit_once('/')
93 .map_or(String::new(), |(d, _)| d.to_string());
94 if name == "go.mod" {
95 let text = std::fs::read_to_string(entry.path()).unwrap_or_default();
96 modules.push(Package {
97 name: module_path(&text).unwrap_or_else(|| dir.clone()),
98 src_root: dir.clone(),
99 dir,
100 deps: requirements(&text),
101 dev_deps: Vec::new(),
102 namespaces: Vec::new(),
103 });
104 } else if name.ends_with(".go") {
105 let kind = if name.ends_with("_test.go") {
106 FileKind::Test
107 } else {
108 FileKind::Source
109 };
110 files.push((rel, kind));
111 }
112 }
113 if modules.is_empty() {
114 modules.push(Package {
115 name: root
116 .file_name()
117 .map_or_else(|| "root".into(), |n| n.to_string_lossy().into_owned()),
118 dir: String::new(),
119 src_root: String::new(),
120 deps: Vec::new(),
121 dev_deps: Vec::new(),
122 namespaces: Vec::new(),
123 });
124 }
125 modules.sort_by(|a, b| a.dir.cmp(&b.dir));
126 files.sort_by(|a, b| a.0.cmp(&b.0));
127 let files = files
128 .into_iter()
129 .map(|(path, kind)| {
130 let package = modules
131 .iter()
132 .enumerate()
133 .filter(|(_, p)| p.dir.is_empty() || path.starts_with(&format!("{}/", p.dir)))
134 .max_by_key(|(_, p)| p.dir.len())
135 .map_or(0, |(i, _)| i);
136 SourceFile {
137 path,
138 package,
139 kind,
140 }
141 })
142 .collect();
143 Ok(Workspace {
144 packages: modules,
145 files,
146 })
147}
148
149pub fn scan(source: &str) -> FileFacts {
152 let mut facts = FileFacts {
153 loc: syntax::loc(source, crate::lang::Lang::Go),
154 ..FileFacts::default()
155 };
156 let Some(tree) = syntax::parse(&language(), source) else {
157 return facts;
158 };
159 let root = tree.root_node();
160 facts.parse_errors = usize::from(root.has_error());
161 let add = |facts: &mut FileFacts, risk: Risk, node: Node| {
162 facts
163 .risks
164 .entry(risk)
165 .or_default()
166 .push(syntax::line(node))
167 };
168 syntax::walk(root, |node| match node.kind() {
169 "import_spec" => {
170 if let Some(path) = node.child_by_field_name("path") {
171 let spec = text(path, source).trim_matches(|c| c == '"' || c == '`');
172 match spec {
173 "unsafe" => add(&mut facts, Risk::Pointers, node),
174 "reflect" => add(&mut facts, Risk::Reflection, node),
175 "sync" | "sync/atomic" => add(&mut facts, Risk::Concurrency, node),
176 "regexp" => add(&mut facts, Risk::RegexSyntax, node),
177 "encoding/json" => add(&mut facts, Risk::Json, node),
178 _ => {}
179 }
180 facts.imports.push(Import {
181 specifier: spec.to_string(),
182 type_only: false,
183 dynamic: false,
184 });
185 }
186 }
187 "go_statement" | "channel_type" | "send_statement" | "select_statement" => {
188 add(&mut facts, Risk::Concurrency, node)
189 }
190 "pointer_type" | "unary_expression" if text(node, source).starts_with('&') => {
191 add(&mut facts, Risk::Pointers, node)
192 }
193 "pointer_type" => add(&mut facts, Risk::Pointers, node),
194 "slice_expression" => add(&mut facts, Risk::StringOffsets, node),
195 "binary_expression" => {
196 let op = node
197 .child_by_field_name("operator")
198 .map_or("", |o| text(o, source));
199 match op {
200 "/" | "%" => add(&mut facts, Risk::DivisionSemantics, node),
201 "<<" | ">>" => add(&mut facts, Risk::IntegerSemantics, node),
202 _ => {}
203 }
204 }
205 "type_conversion_expression" => add(&mut facts, Risk::IntegerSemantics, node),
206 "call_expression" => {
207 let callee = node
208 .child_by_field_name("function")
209 .map_or("", |f| text(f, source));
210 match callee {
211 "panic" | "recover" => add(&mut facts, Risk::Exceptions, node),
212 "int" | "int32" | "int64" | "uint" | "uint32" | "uint64" | "uint8" | "byte"
213 | "float64" => add(&mut facts, Risk::IntegerSemantics, node),
214 _ => {}
215 }
216 }
217 "nil" => add(&mut facts, Risk::NullReferences, node),
218 "interface_type" | "type_switch_statement" | "type_assertion_expression" => {
219 add(&mut facts, Risk::DynamicTyping, node)
220 }
221 "func_literal" | "function_type" => add(&mut facts, Risk::Callbacks, node),
222 "defer_statement" => add(&mut facts, Risk::Exceptions, node),
223 "range_clause" => {
224 facts.loops += 1;
225 if node
226 .child_by_field_name("right")
227 .is_some_and(|r| text(r, source).contains("map"))
228 {
229 add(&mut facts, Risk::UnorderedIteration, node);
230 }
231 }
232 "for_statement" => facts.loops += 1,
233 _ => {}
234 });
235 facts
236}
237
238fn is_stdlib(spec: &str) -> bool {
240 !spec.split('/').next().unwrap_or("").contains('.')
241}
242
243pub fn resolve(spec: &str, index: &HashMap<&str, usize>, ws: &Workspace) -> super::Resolution {
244 if let Some(module) = ws
246 .packages
247 .iter()
248 .filter(|p| spec == p.name || spec.starts_with(&format!("{}/", p.name)))
249 .max_by_key(|p| p.name.len())
250 {
251 let sub = spec[module.name.len()..].trim_start_matches('/');
252 let dir = match (module.dir.as_str(), sub) {
253 ("", s) => s.to_string(),
254 (d, "") => d.to_string(),
255 (d, s) => format!("{d}/{s}"),
256 };
257 let mut best: Option<(&str, usize)> = None;
258 for (path, i) in index {
259 let parent = path.rsplit_once('/').map_or("", |(d, _)| d);
260 if parent == dir
261 && path.ends_with(".go")
262 && !path.ends_with("_test.go")
263 && best.is_none_or(|(p, _)| *path < p)
264 {
265 best = Some((path, *i));
266 }
267 }
268 return best.map_or(super::Resolution::Unresolved, |(_, i)| {
269 super::Resolution::File(i)
270 });
271 }
272 if is_stdlib(spec) {
273 return super::Resolution::Stdlib;
274 }
275 super::Resolution::External(spec.to_string())
276}
277
278pub fn lookup(module: &str) -> Option<CrateMatch> {
280 crate::crates::find("go", module)
281}
282
283fn builtin(t: &str) -> Option<&'static str> {
287 Some(match t {
288 "string" => "string",
289 "bool" => "boolean",
290 "int" | "int8" | "int16" | "int32" | "int64" | "uint" | "uint8" | "uint16" | "uint32"
291 | "uint64" | "uintptr" | "byte" | "rune" => "int",
292 "float32" | "float64" => "number",
293 _ => return None,
294 })
295}
296
297fn direct_struct_fields(struct_type: Node<'_>) -> Vec<Node<'_>> {
298 named_children(struct_type)
299 .into_iter()
300 .find(|node| node.kind() == "field_declaration_list")
301 .map(|list| {
302 named_children(list)
303 .into_iter()
304 .filter(|field| field.kind() == "field_declaration")
305 .collect()
306 })
307 .unwrap_or_default()
308}
309
310fn structs(root: Node, source: &str) -> HashMap<String, String> {
312 let mut out = HashMap::new();
313 for decl in named_children(root)
314 .into_iter()
315 .filter(|n| n.kind() == "type_declaration")
316 {
317 for spec in named_children(decl)
318 .into_iter()
319 .filter(|n| n.kind() == "type_spec")
320 {
321 let (Some(name), Some(ty)) = (
322 spec.child_by_field_name("name"),
323 spec.child_by_field_name("type"),
324 ) else {
325 continue;
326 };
327 if ty.kind() != "struct_type" {
328 continue;
329 }
330 let mut fields = Vec::new();
331 let mut ok = true;
332 for n in direct_struct_fields(ty) {
333 let field_type = n
334 .child_by_field_name("type")
335 .map_or("", |t| text(t, source));
336 let tag = n.child_by_field_name("tag").map_or("", |t| text(t, source));
337 let json_name = tag
338 .split("json:\"")
339 .nth(1)
340 .and_then(|r| r.split('"').next())
341 .map(|r| r.split(',').next().unwrap_or("").to_string());
342 let mut cursor = n.walk();
343 let names: Vec<String> = n
344 .children_by_field_name("name", &mut cursor)
345 .map(|f| text(f, source).to_string())
346 .collect();
347 if names.is_empty() {
348 ok = false; }
350 for field in names {
351 if !field.starts_with(char::is_uppercase) || json_name.as_deref() == Some("-") {
352 continue;
353 }
354 match go_to_ts(field_type, &HashMap::new()) {
355 Ok(t) => {
356 let key = json_name.clone().filter(|j| !j.is_empty()).unwrap_or(field);
357 fields.push(format!("{key}: {t}"));
358 }
359 Err(_) => ok = false,
360 }
361 }
362 }
363 if ok {
364 out.insert(
365 text(name, source).to_string(),
366 format!("{{ {} }}", fields.join("; ")),
367 );
368 }
369 }
370 }
371 out
372}
373
374pub fn go_to_ts(t: &str, structs: &HashMap<String, String>) -> Result<String, String> {
376 let t = t.trim();
377 if let Some(b) = builtin(t) {
378 return Ok(b.to_string());
379 }
380 if let Some(inner) = t.strip_prefix("[]") {
381 return go_to_ts(inner, structs).map(|i| {
382 if i.contains(' ') || i.contains('|') {
383 format!("({i})[]")
384 } else {
385 format!("{i}[]")
386 }
387 });
388 }
389 if let Some(rest) = t.strip_prefix("map[") {
390 let mut depth = 1;
391 let close = rest.char_indices().find_map(|(i, c)| {
392 match c {
393 '[' => depth += 1,
394 ']' => depth -= 1,
395 _ => {}
396 }
397 (depth == 0).then_some(i)
398 });
399 if let Some(close) = close {
400 let (key, value) = (&rest[..close], &rest[close + 1..]);
401 if key.trim() != "string" {
402 return Err(format!("`{t}`: JSON object keys are strings"));
403 }
404 return go_to_ts(value, structs).map(|v| format!("Record<string, {v}>"));
405 }
406 }
407 if t.starts_with('*') {
408 return Err(format!("takes or returns a pointer (`{t}`)"));
409 }
410 if t.starts_with("func") {
411 return Err("takes or returns a function".into());
412 }
413 if t.starts_with("chan") || t.starts_with("<-chan") {
414 return Err("takes or returns a channel".into());
415 }
416 if t == "any" || t.starts_with("interface") {
417 return Err(format!("`{t}`: values of any type"));
418 }
419 if t.starts_with('[') {
420 return Err(format!("`{t}`: fixed-size array"));
421 }
422 if t == "error" {
423 return Err("takes an `error` value".into());
424 }
425 if t.contains('.') {
426 return Err(format!("uses `{t}` from another package"));
427 }
428 if !t.starts_with(char::is_uppercase) {
429 return Err(format!("uses the unexported type `{t}`"));
430 }
431 Ok(structs.get(t).cloned().unwrap_or_else(|| "unknown".into()))
432}
433
434pub fn exports(path: &str, source: &str) -> Vec<ExportedFn> {
436 if !path.ends_with(".go") || path.ends_with("_test.go") {
437 return Vec::new();
438 }
439 let Some(tree) = syntax::parse(&language(), source) else {
440 return Vec::new();
441 };
442 let root = tree.root_node();
443 let structs = structs(root, source);
444 let mut out = Vec::new();
445 for node in named_children(root) {
446 if node.kind() != "function_declaration" {
447 continue;
448 }
449 let name = node
450 .child_by_field_name("name")
451 .map(|n| text(n, source).to_string())
452 .unwrap_or_default();
453 if !name.starts_with(char::is_uppercase) {
454 continue;
455 }
456 let mut blocker = None;
457 if node.child_by_field_name("type_parameters").is_some() {
458 blocker = Some("generic: Go instantiates it per type".to_string());
459 }
460 let mut params = Vec::new();
461 if let Some(list) = node.child_by_field_name("parameters") {
462 for (i, p) in named_children(list).into_iter().enumerate() {
463 if p.kind() == "variadic_parameter_declaration" {
464 blocker.get_or_insert_with(|| "is variadic".into());
465 }
466 let go_type = p
467 .child_by_field_name("type")
468 .map_or("", |t| text(t, source))
469 .to_string();
470 let ts_type = go_to_ts(&go_type, &structs).unwrap_or_else(|reason| {
471 blocker.get_or_insert(reason);
472 "unknown".into()
473 });
474 let mut cursor = p.walk();
475 let mut names: Vec<String> = p
476 .children_by_field_name("name", &mut cursor)
477 .map(|n| text(n, source).to_string())
478 .collect();
479 if names.is_empty() {
480 names.push(format!("arg{i}"));
481 }
482 for n in names {
483 let n = if n == "_" {
484 format!("arg{}", params.len())
485 } else {
486 n
487 };
488 params.push(Param {
489 name: n,
490 ts_type: ts_type.clone(),
491 native_type: Some(go_type.clone()),
492 ..Default::default()
493 });
494 }
495 }
496 }
497 let mut results: Vec<String> = Vec::new();
499 if let Some(r) = node.child_by_field_name("result") {
500 if r.kind() == "parameter_list" {
501 for p in named_children(r) {
502 let t = p
503 .child_by_field_name("type")
504 .map_or("", |t| text(t, source))
505 .to_string();
506 let mut cursor = p.walk();
507 let count = p.children_by_field_name("name", &mut cursor).count().max(1);
508 results.extend(std::iter::repeat_n(t, count));
509 }
510 } else {
511 results.push(text(r, source).to_string());
512 }
513 }
514 let fallible = results.last().is_some_and(|r| r == "error");
515 if fallible {
516 results.pop();
517 }
518 let mut dialect = Vec::new();
519 for r in &results {
520 match go_to_ts(r, &structs) {
521 Ok(t) => dialect.push(t),
522 Err(reason) => {
523 blocker.get_or_insert(reason);
524 dialect.push("unknown".into());
525 }
526 }
527 }
528 let returns = match dialect.len() {
529 0 => "void".to_string(),
530 1 => dialect.remove(0),
531 _ => format!("[{}]", dialect.join(", ")),
532 };
533 let signature = node.child_by_field_name("body").map_or_else(
534 || text(node, source),
535 |b| source[node.start_byte()..b.start_byte()].trim(),
536 );
537 out.push(ExportedFn {
538 name,
539 file: path.to_string(),
540 line: syntax::line(node),
541 params,
542 returns,
543 native_return: Some(format!(
544 "({}{})",
545 results.join(", "),
546 if fallible {
547 if results.is_empty() {
548 "error"
549 } else {
550 ", error"
551 }
552 } else {
553 ""
554 }
555 )),
556 prototype: Some(signature.split_whitespace().collect::<Vec<_>>().join(" ")),
557 blocker,
558 ..Default::default()
559 });
560 }
561 out
562}
563
564pub fn package_name(source: &str) -> Option<String> {
566 source.lines().find_map(|l| {
567 l.trim()
568 .strip_prefix("package ")
569 .map(|p| p.split_whitespace().next().unwrap_or("").to_string())
570 })
571}
572
573pub fn type_decls(sources: &[String], names: &[String]) -> Vec<String> {
575 let mut out = Vec::new();
576 for source in sources {
577 let Some(tree) = syntax::parse(&language(), source) else {
578 continue;
579 };
580 for decl in named_children(tree.root_node())
581 .into_iter()
582 .filter(|n| n.kind() == "type_declaration")
583 {
584 for spec in named_children(decl)
585 .into_iter()
586 .filter(|n| n.kind() == "type_spec")
587 {
588 if spec
589 .child_by_field_name("name")
590 .is_some_and(|n| names.iter().any(|w| w == text(n, source)))
591 {
592 out.push(format!("type {}", text(spec, source)));
593 }
594 }
595 }
596 }
597 out
598}
599
600pub fn struct_fields(sources: &[String], name: &str) -> Option<Vec<(String, String, String)>> {
603 for source in sources {
604 let Some(tree) = syntax::parse(&language(), source) else {
605 continue;
606 };
607 for decl in named_children(tree.root_node())
608 .into_iter()
609 .filter(|n| n.kind() == "type_declaration")
610 {
611 for spec in named_children(decl)
612 .into_iter()
613 .filter(|n| n.kind() == "type_spec")
614 {
615 if spec.child_by_field_name("name").map(|n| text(n, source)) != Some(name) {
616 continue;
617 }
618 let ty = spec.child_by_field_name("type")?;
619 if ty.kind() != "struct_type" {
620 return None;
621 }
622 let mut out = Vec::new();
623 let mut ok = true;
624 for n in direct_struct_fields(ty) {
625 let field_type = n
626 .child_by_field_name("type")
627 .map_or("", |t| text(t, source))
628 .to_string();
629 let tag = n.child_by_field_name("tag").map_or("", |t| text(t, source));
630 let json = tag
631 .split("json:\"")
632 .nth(1)
633 .and_then(|r| r.split('"').next())
634 .map(|r| r.split(',').next().unwrap_or("").to_string());
635 let mut cursor = n.walk();
636 let names: Vec<String> = n
637 .children_by_field_name("name", &mut cursor)
638 .map(|f| text(f, source).to_string())
639 .collect();
640 if names.is_empty() {
641 ok = false;
642 }
643 for field in names {
644 if !field.starts_with(char::is_uppercase) || json.as_deref() == Some("-") {
645 continue;
646 }
647 let key = json
648 .clone()
649 .filter(|j| !j.is_empty())
650 .unwrap_or_else(|| field.clone());
651 out.push((field, field_type.clone(), key));
652 }
653 }
654 return ok.then_some(out);
655 }
656 }
657 }
658 None
659}
660
661#[derive(Clone, Debug, PartialEq, Eq)]
663pub struct SentinelError {
664 pub name: String,
665 pub message: Option<String>,
668 pub alias_of: Option<String>,
671}
672
673pub fn sentinel_errors(sources: &[String]) -> Vec<SentinelError> {
675 let mut out: Vec<SentinelError> = Vec::new();
676 let mut pending_aliases: Vec<(String, String)> = Vec::new();
677 for source in sources {
678 let Some(tree) = syntax::parse(&language(), source) else {
679 continue;
680 };
681 let root = tree.root_node();
682 let imports = go_import_bindings(root, source);
683 for node in named_children(root) {
684 if node.kind() != "var_declaration" {
685 continue;
686 }
687 for child in named_children(node) {
688 if child.kind() == "var_spec" {
689 collect_var_spec(child, source, &imports, &mut out, &mut pending_aliases);
690 } else if child.kind() == "var_spec_list" {
691 for spec in named_children(child) {
692 if spec.kind() == "var_spec" {
693 collect_var_spec(
694 spec,
695 source,
696 &imports,
697 &mut out,
698 &mut pending_aliases,
699 );
700 }
701 }
702 }
703 }
704 }
705 }
706 for (name, target) in pending_aliases {
708 if out.iter().any(|s| s.name == name) {
709 continue;
710 }
711 if let Some(base) = out.iter().find(|s| s.name == target).cloned() {
712 out.push(SentinelError {
713 name,
714 message: base.message,
715 alias_of: Some(target),
716 });
717 }
718 }
719 out
720}
721
722fn go_import_bindings(root: Node, source: &str) -> HashMap<String, String> {
724 let mut out = HashMap::new();
725 for node in named_children(root) {
726 if node.kind() != "import_declaration" {
727 continue;
728 }
729 for child in named_children(node) {
730 if child.kind() == "import_spec" {
731 record_import_spec(child, source, &mut out);
732 } else if child.kind() == "import_spec_list" {
733 for spec in named_children(child) {
734 if spec.kind() == "import_spec" {
735 record_import_spec(spec, source, &mut out);
736 }
737 }
738 }
739 }
740 }
741 out
742}
743
744fn record_import_spec(spec: Node, source: &str, out: &mut HashMap<String, String>) {
745 let Some(path_node) = spec.child_by_field_name("path") else {
746 return;
747 };
748 let path = text(path_node, source).trim_matches(|c| c == '"' || c == '`');
749 let local = spec
750 .child_by_field_name("name")
751 .map(|n| text(n, source).trim().to_string())
752 .unwrap_or_else(|| path.rsplit('/').next().unwrap_or(path).to_string());
753 if local != "_" && local != "." && !local.is_empty() {
754 out.insert(local, path.to_string());
755 }
756}
757
758fn collect_var_spec(
759 spec: Node,
760 source: &str,
761 imports: &HashMap<String, String>,
762 out: &mut Vec<SentinelError>,
763 pending_aliases: &mut Vec<(String, String)>,
764) {
765 let mut cursor = spec.walk();
766 let names: Vec<&str> = spec
767 .children_by_field_name("name", &mut cursor)
768 .map(|n| text(n, source))
769 .collect();
770 let explicit_error = spec
771 .child_by_field_name("type")
772 .is_some_and(|t| text(t, source).trim() == "error");
773 let values: Vec<Node> = spec
774 .child_by_field_name("value")
775 .map(named_children)
776 .unwrap_or_default();
777 let multi_result = explicit_error && values.len() == 1 && names.len() > 1;
778 for (i, name) in names.into_iter().enumerate() {
779 if !name.starts_with(char::is_uppercase) || out.iter().any(|s| s.name == name) {
780 continue;
781 }
782 if multi_result {
783 out.push(SentinelError {
784 name: name.to_string(),
785 message: None,
786 alias_of: None,
787 });
788 continue;
789 }
790 let Some(&expr) = values.get(i) else {
791 continue;
792 };
793 if expr.kind() == "identifier" {
794 let target = text(expr, source).trim();
795 if target.starts_with(char::is_uppercase) && target != name {
796 if let Some(base) = out.iter().find(|s| s.name == target).cloned() {
797 out.push(SentinelError {
798 name: name.to_string(),
799 message: base.message,
800 alias_of: Some(target.to_string()),
801 });
802 } else {
803 pending_aliases.push((name.to_string(), target.to_string()));
804 }
805 continue;
806 }
807 }
808 if let Some(message) = error_initializer(expr, source, imports, explicit_error) {
809 out.push(SentinelError {
810 name: name.to_string(),
811 message,
812 alias_of: None,
813 });
814 }
815 }
816}
817
818fn error_initializer(
821 expr: Node,
822 source: &str,
823 imports: &HashMap<String, String>,
824 explicit_error: bool,
825) -> Option<Option<String>> {
826 if expr.kind() == "call_expression" {
827 let func = expr
828 .child_by_field_name("function")
829 .map(|n| text(n, source).trim())
830 .unwrap_or_default();
831 let args: Vec<Node> = expr
832 .child_by_field_name("arguments")
833 .map(named_children)
834 .unwrap_or_default();
835 if let Some((pkg_alias, fn_name)) = func.split_once('.') {
836 let pkg_path = imports
837 .get(pkg_alias.trim())
838 .map(String::as_str)
839 .unwrap_or(pkg_alias.trim());
840 if pkg_path == "errors" && fn_name.trim() == "New" {
841 let msg = args.first().and_then(|a| unquote_go_string(*a, source));
842 return Some(msg);
843 }
844 if pkg_path == "fmt" && fn_name.trim() == "Errorf" {
845 let msg = (args.len() == 1)
846 .then(|| unquote_go_string(args[0], source))
847 .flatten()
848 .filter(|s| !s.contains('%'));
849 return Some(msg);
850 }
851 }
852 }
853 if explicit_error {
854 return Some(None);
855 }
856 None
857}
858
859fn unquote_go_string(node: Node, source: &str) -> Option<String> {
860 let raw = text(node, source);
861 match node.kind() {
862 "raw_string_literal" => raw
863 .strip_prefix('`')
864 .and_then(|s| s.strip_suffix('`'))
865 .map(|s| s.replace('\r', "")),
866 "interpreted_string_literal" => {
867 let inner = raw.strip_prefix('"')?.strip_suffix('"')?;
868 let mut out = String::with_capacity(inner.len());
869 let mut chars = inner.chars();
870 while let Some(c) = chars.next() {
871 if c != '\\' {
872 out.push(c);
873 continue;
874 }
875 match chars.next()? {
876 '\\' => out.push('\\'),
877 '"' => out.push('"'),
878 'n' => out.push('\n'),
879 'r' => out.push('\r'),
880 't' => out.push('\t'),
881 _ => return None,
882 }
883 }
884 Some(out)
885 }
886 _ => None,
887 }
888}
889
890#[cfg(test)]
891mod tests {
892 use super::*;
893
894 #[test]
895 fn maps_types() {
896 let none = HashMap::new();
897 assert_eq!(go_to_ts("[]string", &none).unwrap(), "string[]");
898 assert_eq!(
899 go_to_ts("map[string][]int", &none).unwrap(),
900 "Record<string, int[]>"
901 );
902 assert!(go_to_ts("*Point", &none).is_err());
903 assert!(go_to_ts("map[int]string", &none).is_err());
904 }
905
906 #[test]
907 fn hidden_nested_struct_does_not_add_phantom_fields() {
908 let source = String::from(
909 r#"package x
910type Point struct {
911 hidden struct { Extra float64 }
912 X int `json:"x"`
913}
914func Echo(p Point) Point { return p }"#,
915 );
916 let exports = exports("x.go", &source);
917 assert_eq!(exports[0].params[0].ts_type, "{ x: int }");
918 assert_eq!(exports[0].returns, "{ x: int }");
919 assert_eq!(
920 struct_fields(&[source], "Point").unwrap(),
921 [("X".into(), "int".into(), "x".into())]
922 );
923 }
924
925 #[test]
926 fn finds_exports() {
927 let src = "package x\n\ntype Point struct {\n\tX int `json:\"x\"`\n\tY float64\n\tz int\n}\n\n\
928 func Add(a, b int) int { return a + b }\n\
929 func Div(a float64, b float64) (float64, error) { return a / b, nil }\n\
930 func Many(xs ...string) []string { return xs }\n\
931 func (p Point) Norm() float64 { return 0 }\n\
932 func Gen[T any](x T) T { return x }\n\
933 func Move(p Point) Point { return p }\n\
934 func hidden() {}\n";
935 let fns = exports("x/x.go", src);
936 let names: Vec<&str> = fns.iter().map(|f| f.name.as_str()).collect();
937 assert_eq!(names, ["Add", "Div", "Many", "Gen", "Move"]);
938 assert_eq!(fns[0].params.len(), 2);
939 assert_eq!(fns[0].params[1].ts_type, "int");
940 assert_eq!(fns[1].returns, "number");
941 assert_eq!(fns[1].native_return.as_deref(), Some("(float64, error)"));
942 assert!(fns[2].blocker.is_some() && fns[3].blocker.is_some());
943 assert_eq!(fns[4].params[0].ts_type, "{ x: int; Y: number }");
944 assert_eq!(
945 fns[4].prototype.as_deref(),
946 Some("func Move(p Point) Point")
947 );
948 }
949
950 #[test]
951 fn collects_exported_sentinel_errors() {
952 let src = String::from(
953 "package store\n\n\
954 import (\n\
955 \tstderrors \"errors\"\n\
956 \t\"fmt\"\n\
957 )\n\n\
958 var ErrNotFound = stderrors.New(\"not found\")\n\
959 var ErrAlias error = ErrNotFound\n\n\
960 var (\n\
961 \tErrEmpty = fmt.Errorf(\"\")\n\
962 \tErrRaw = stderrors.New(`line1\r\nline2`)\n\
963 \tErrDynamic = fmt.Errorf(\"bad %d\", 1)\n\
964 \tErrTyped error = customErr()\n\
965 \tErrM1, ErrM2 error = makeErrors()\n\
966 \tErrA, ErrB = stderrors.New(\"a\"), stderrors.New(\"b\")\n\
967 \terrPrivate = stderrors.New(\"private\")\n\
968 \tMaxItems = 100\n\
969 )\n",
970 );
971 assert_eq!(
972 sentinel_errors(&[src]),
973 vec![
974 SentinelError {
975 name: "ErrNotFound".into(),
976 message: Some("not found".into()),
977 alias_of: None,
978 },
979 SentinelError {
980 name: "ErrAlias".into(),
981 message: Some("not found".into()),
982 alias_of: Some("ErrNotFound".into()),
983 },
984 SentinelError {
985 name: "ErrEmpty".into(),
986 message: Some(String::new()),
987 alias_of: None,
988 },
989 SentinelError {
990 name: "ErrRaw".into(),
991 message: Some("line1\nline2".into()),
992 alias_of: None,
993 },
994 SentinelError {
995 name: "ErrDynamic".into(),
996 message: None,
997 alias_of: None,
998 },
999 SentinelError {
1000 name: "ErrTyped".into(),
1001 message: None,
1002 alias_of: None,
1003 },
1004 SentinelError {
1005 name: "ErrM1".into(),
1006 message: None,
1007 alias_of: None,
1008 },
1009 SentinelError {
1010 name: "ErrM2".into(),
1011 message: None,
1012 alias_of: None,
1013 },
1014 SentinelError {
1015 name: "ErrA".into(),
1016 message: Some("a".into()),
1017 alias_of: None,
1018 },
1019 SentinelError {
1020 name: "ErrB".into(),
1021 message: Some("b".into()),
1022 alias_of: None,
1023 },
1024 ]
1025 );
1026 }
1027}