Skip to main content

codeint_lang_shell/
lib.rs

1#![forbid(unsafe_code)]
2
3mod commands;
4mod dialect;
5mod flagged;
6mod functions;
7mod hazards;
8mod lexer;
9mod source_set;
10
11use codeint_model::language::{FileModel, LowerError, Token, TokenKind};
12use codeint_model::scan::CoreReferenceRanges;
13use codeint_model::{path_file_name, token_text_hash};
14
15use crate::lexer::{ShellToken, ShellTokenKind};
16
17pub use dialect::{ShellDialect, detect_dialect};
18pub use flagged::{SHELL_FLAGGED_RULES, flagged_line_rules};
19pub use hazards::{SHELL_HAZARD_RULES, hazard_line_rules};
20
21const SHELL_KEYWORDS_AND_BUILTINS: &[&str] = &[
22    "!", "[", "[[", "]", "]]", "{", "}", "break", "case", "cd", "continue", "coproc", "declare",
23    "do", "done", "echo", "elif", "else", "esac", "eval", "exec", "exit", "export", "fi", "for",
24    "function", "if", "in", "local", "read", "readonly", "return", "select", "set", "setopt",
25    "shift", "source", "test", "then", "time", "trap", "typeset", "unset", "until", "while",
26];
27
28pub struct Shell;
29
30const SHELL_RANGES: CoreReferenceRanges = CoreReferenceRanges::new(
31    (0.364, 0.930),
32    (0.218, 0.828),
33    (0.000, 0.031),
34    (0.003, 0.713),
35    None,
36);
37
38fn lower_shell(
39    _plugin: &Shell,
40    path: &codeint_model::RepoPath,
41    text: &str,
42    _dialect: Option<&str>,
43) -> Result<FileModel, codeint_model::LowerError> {
44    lower_file(path.as_str(), text).map_err(codeint_model::LowerError::from)
45}
46
47codeint_model::impl_builtin_language_plugin!(
48    Shell,
49    ["sh", "bash", "zsh"],
50    lower_shell,
51    SHELL_RANGES.build(&codeint_model::scan::calibrated_source(
52        "100 Shell repositories",
53    )),
54    flagged_lines(flagged_line_rules()),
55    imports(none),
56    frameworks(none),
57    hazards(SHELL_HAZARD_RULES),
58);
59
60fn lower_file(path: &str, text: &str) -> Result<FileModel, LowerError> {
61    if !is_supported_path(path) {
62        return Err(LowerError::UnsupportedFile(format!(
63            "{path} is not a Shell source file"
64        )));
65    }
66    let dialect = detect_dialect(path, text);
67    let lexed = lexer::scan(text, dialect)?;
68    let source_lines = u32::try_from(lexed.code_lines.len()).map_err(|_| LowerError::TooLarge)?;
69    let extracted = functions::extract(&lexed.tokens, &lexed.code_lines, dialect);
70    let flagged_lines = flagged::evaluate(&lexed.tokens, &lexed.code_lines);
71    let hazard_lines =
72        hazards::evaluate(&lexed.tokens, &lexed.code_lines, &extracted, dialect, text);
73    let mut tokens = Vec::new();
74    append_duplication_tokens(&lexed.tokens, &mut tokens);
75    let source_set = source_set::classify(path, &lexed.header_comments);
76    Ok(FileModel {
77        flagged_lines,
78        hazard_lines,
79        tokens,
80        functions: extracted.functions,
81        source_lines,
82        ..codeint_model::empty_file_model(source_set)
83    })
84}
85
86fn is_supported_path(path: &str) -> bool {
87    let file_name = path_file_name(path);
88    if source_set::is_generated_filename(file_name) {
89        return true;
90    }
91    matches!(
92        file_name.rsplit_once('.'),
93        Some((stem, "sh" | "bash" | "zsh")) if !stem.is_empty()
94    )
95}
96
97fn append_duplication_tokens(raw: &[ShellToken], out: &mut Vec<Token>) {
98    for tok in raw {
99        if tok.is_newline() {
100            continue;
101        }
102        let kind = classify_duplication_kind(tok);
103        out.push(Token {
104            kind,
105            text_hash: token_text_hash(&tok.text),
106            line: tok.line,
107        });
108        for sub in &tok.sub_tokens {
109            append_duplication_tokens(sub, out);
110        }
111    }
112}
113
114fn classify_duplication_kind(tok: &ShellToken) -> TokenKind {
115    if matches!(
116        tok.kind,
117        ShellTokenKind::Operator | ShellTokenKind::ArithCmd
118    ) {
119        return TokenKind::Other;
120    }
121    if tok.is_fully_single_quoted || is_numeric_literal(&tok.text) {
122        return TokenKind::Literal;
123    }
124    if tok.has_quotes && !tok.has_var_expansion {
125        return TokenKind::Literal;
126    }
127    if !tok.has_quotes
128        && (tok.text.starts_with('-') || SHELL_KEYWORDS_AND_BUILTINS.contains(&tok.text.as_str()))
129    {
130        return TokenKind::Other;
131    }
132    TokenKind::Identifier
133}
134
135fn is_numeric_literal(text: &str) -> bool {
136    !text.is_empty() && text.bytes().all(|b| b.is_ascii_digit())
137}