Skip to main content

codeint_lang_go/
lib.rs

1#![forbid(unsafe_code)]
2
3mod dependencies;
4mod entry_points;
5mod functions;
6mod go_mod;
7mod imports;
8mod lexer;
9mod resolution;
10mod rules;
11mod source_set;
12mod workspaces;
13
14use std::collections::BTreeSet;
15
16use codeint_model::language::{FileModel, LowerError, Token, TokenKind};
17use codeint_model::scan::CoreReferenceRanges;
18use codeint_model::token_text_hash;
19
20use crate::lexer::{GoKind, GoToken};
21
22pub use rules::flagged_line_rules;
23
24pub struct Go;
25
26fn lower_file(path: &str, text: &str) -> Result<FileModel, LowerError> {
27    if !path.ends_with(".go") {
28        return Err(LowerError::UnsupportedFile(format!(
29            "{path} is not a Go source file"
30        )));
31    }
32    let scanned = lexer::scan(text)?;
33    let source_lines = u32::try_from(scanned.code_lines.len()).map_err(|_| LowerError::TooLarge)?;
34    let scanned_imports = imports::scan(&scanned.tokens);
35    let extracted = functions::extract(&scanned.tokens, &scanned.code_lines);
36    let flagged_lines = rules::evaluate(&scanned.tokens, &extracted.spans, &scanned.code_lines);
37    let tokens = build_duplication_tokens(&scanned.tokens, &scanned_imports.marked_indices);
38    let source_set = source_set::classify(path, &scanned.header_line_comments);
39    Ok(FileModel {
40        runtime_imports: scanned_imports
41            .specifiers
42            .into_iter()
43            .map(Into::into)
44            .collect(),
45        flagged_lines,
46        tokens,
47        functions: extracted.functions,
48        source_lines,
49        program_start: scanned_imports.is_package_main,
50        ..codeint_model::empty_file_model(source_set)
51    })
52}
53
54fn build_duplication_tokens(raw: &[GoToken], import_indices: &BTreeSet<usize>) -> Vec<Token> {
55    raw.iter()
56        .enumerate()
57        .filter(|(_, tok)| tok.kind != GoKind::AutoSemi)
58        .map(|(idx, tok)| {
59            let kind = if import_indices.contains(&idx) {
60                TokenKind::ImportOrExport
61            } else if tok.kind == GoKind::Ident {
62                TokenKind::Identifier
63            } else if matches!(
64                tok.kind,
65                GoKind::StringLit | GoKind::RuneLit | GoKind::NumberLit
66            ) {
67                TokenKind::Literal
68            } else {
69                TokenKind::Other
70            };
71            Token {
72                kind,
73                text_hash: token_text_hash(&tok.text),
74                line: tok.line,
75            }
76        })
77        .collect()
78}
79
80fn lower_go(
81    _plugin: &Go,
82    path: &codeint_model::RepoPath,
83    text: &str,
84    _dialect: Option<&str>,
85) -> Result<FileModel, codeint_model::LowerError> {
86    lower_file(path.as_str(), text).map_err(codeint_model::LowerError::from)
87}
88
89const GO_RANGES: CoreReferenceRanges = CoreReferenceRanges::new(
90    (0.304, 0.746),
91    (0.306, 0.671),
92    (0.000, 0.004),
93    (0.034, 0.243),
94    Some((0.000, 0.000)),
95);
96
97codeint_model::impl_builtin_language_plugin!(
98    Go,
99    ["go"],
100    lower_go,
101    GO_RANGES.build_calibrated("100 Go repositories"),
102    flagged_lines(flagged_line_rules()),
103    imports(
104        resolution::find_go_mods,
105        workspaces::analyze_manifests,
106        |paths, manifests, requests, _| resolution::resolve_all(paths, manifests, requests, &[]),
107        entry_points::discover,
108    ),
109    frameworks(none),
110    hazards(none),
111);