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
52        .build("codeint stratified panel of 100 Shell repositories, ADR 0035, codeint 0.8.0"),
53    flagged_lines(flagged_line_rules()),
54    imports(none),
55    frameworks(none),
56    hazards(SHELL_HAZARD_RULES),
57);
58
59fn lower_file(path: &str, text: &str) -> Result<FileModel, LowerError> {
60    if !is_supported_path(path) {
61        return Err(LowerError::UnsupportedFile(format!(
62            "{path} is not a Shell source file"
63        )));
64    }
65    let dialect = detect_dialect(path, text);
66    let lexed = lexer::scan(text, dialect)?;
67    let source_lines = u32::try_from(lexed.code_lines.len()).map_err(|_| LowerError::TooLarge)?;
68    let extracted = functions::extract(&lexed.tokens, &lexed.code_lines, dialect);
69    let flagged_lines = flagged::evaluate(&lexed.tokens, &lexed.code_lines);
70    let hazard_lines =
71        hazards::evaluate(&lexed.tokens, &lexed.code_lines, &extracted, dialect, text);
72    let mut tokens = Vec::new();
73    append_duplication_tokens(&lexed.tokens, &mut tokens);
74    let source_set = source_set::classify(path, &lexed.header_comments);
75    Ok(FileModel {
76        flagged_lines,
77        hazard_lines,
78        tokens,
79        functions: extracted.functions,
80        source_lines,
81        ..codeint_model::empty_file_model(source_set)
82    })
83}
84
85fn is_supported_path(path: &str) -> bool {
86    let file_name = path_file_name(path);
87    if source_set::is_generated_filename(file_name) {
88        return true;
89    }
90    matches!(
91        file_name.rsplit_once('.'),
92        Some((stem, "sh" | "bash" | "zsh")) if !stem.is_empty()
93    )
94}
95
96fn append_duplication_tokens(raw: &[ShellToken], out: &mut Vec<Token>) {
97    for tok in raw {
98        if tok.is_newline() {
99            continue;
100        }
101        let kind = classify_duplication_kind(tok);
102        out.push(Token {
103            kind,
104            text_hash: token_text_hash(&tok.text),
105            line: tok.line,
106        });
107        for sub in &tok.sub_tokens {
108            append_duplication_tokens(sub, out);
109        }
110    }
111}
112
113fn classify_duplication_kind(tok: &ShellToken) -> TokenKind {
114    if matches!(
115        tok.kind,
116        ShellTokenKind::Operator | ShellTokenKind::ArithCmd
117    ) {
118        return TokenKind::Other;
119    }
120    if tok.is_fully_single_quoted || is_numeric_literal(&tok.text) {
121        return TokenKind::Literal;
122    }
123    if tok.has_quotes && !tok.has_var_expansion {
124        return TokenKind::Literal;
125    }
126    if !tok.has_quotes
127        && (tok.text.starts_with('-') || SHELL_KEYWORDS_AND_BUILTINS.contains(&tok.text.as_str()))
128    {
129        return TokenKind::Other;
130    }
131    TokenKind::Identifier
132}
133
134fn is_numeric_literal(text: &str) -> bool {
135    !text.is_empty() && text.bytes().all(|b| b.is_ascii_digit())
136}