use std::collections::HashMap;
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub enum SuppressionKind {
SameLine,
NextLine,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct SuppressionMeta {
pub kind: SuppressionKind,
pub matched_pattern: String,
pub directive_line: usize,
}
#[derive(Debug)]
enum RuleMatcher {
Exact(String),
WildcardSuffix(String),
}
impl RuleMatcher {
fn matches(&self, rule_id: &str) -> bool {
match self {
RuleMatcher::Exact(s) => s == rule_id,
RuleMatcher::WildcardSuffix(prefix) => {
rule_id.starts_with(prefix.as_str())
&& rule_id.len() > prefix.len()
&& rule_id.as_bytes()[prefix.len()] == b'.'
}
}
}
}
#[derive(Debug)]
struct LineDirective {
kind: SuppressionKind,
directive_line: usize,
matchers: Vec<RuleMatcher>,
}
pub struct SuppressionIndex {
directives: HashMap<usize, Vec<LineDirective>>,
}
impl SuppressionIndex {
pub fn check(&self, line: usize, rule_id: &str) -> Option<SuppressionMeta> {
let canon = canonical_rule_id(rule_id);
let dirs = self.directives.get(&line)?;
for dir in dirs {
for m in &dir.matchers {
if m.matches(canon) {
let display_pattern = match m {
RuleMatcher::Exact(s) => s.clone(),
RuleMatcher::WildcardSuffix(s) => format!("{s}.*"),
};
return Some(SuppressionMeta {
kind: dir.kind.clone(),
matched_pattern: display_pattern,
directive_line: dir.directive_line,
});
}
}
}
None
}
pub fn is_empty(&self) -> bool {
self.directives.is_empty()
}
}
pub fn canonical_rule_id(id: &str) -> &str {
let trimmed = id.trim();
if let Some(idx) = trimmed.find(" (") {
trimmed[..idx].trim_end()
} else {
trimmed
}
}
#[derive(Clone, Copy)]
enum CommentStyle {
CStyle,
Hash,
PhpStyle,
}
fn comment_style_for_ext(ext: &str) -> Option<CommentStyle> {
match ext {
"rs" | "c" | "cpp" | "java" | "go" | "ts" | "js" => Some(CommentStyle::CStyle),
"py" | "rb" => Some(CommentStyle::Hash),
"php" => Some(CommentStyle::PhpStyle),
_ => None,
}
}
fn comment_style_for_path(path: &std::path::Path) -> Option<CommentStyle> {
let ext = path.extension().and_then(|s| s.to_str())?;
let norm = match ext {
"RS" => "rs",
"c++" => "cpp",
"PY" => "py",
"TSX" | "tsx" => "ts",
other => other,
};
comment_style_for_ext(norm)
}
pub fn parse_inline_suppressions(path: &std::path::Path, source: &str) -> SuppressionIndex {
if !source.as_bytes().windows(10).any(|w| w == b"nyx:ignore") {
return SuppressionIndex {
directives: HashMap::new(),
};
}
let Some(style) = comment_style_for_path(path) else {
return SuppressionIndex {
directives: HashMap::new(),
};
};
let mut index: HashMap<usize, Vec<LineDirective>> = HashMap::new();
let total_lines = source.lines().count();
let mut in_block_comment = false;
let mut block_comment_start_line: usize = 0;
for (line_idx, raw_line) in source.lines().enumerate() {
let line_num = line_idx + 1; let line = raw_line.trim_end_matches('\r');
if in_block_comment {
if let Some(end_pos) = line.find("*/") {
let block_text = &line[..end_pos];
if let Some(dir) = try_parse_directive(block_text, line_num) {
let target = target_line(&dir, line_num, total_lines);
if let Some(t) = target {
index.entry(t).or_default().push(dir);
}
}
in_block_comment = false;
let rest = &line[end_pos + 2..];
if let Some(dir) = extract_from_line_rest(rest, line_num, style) {
let target = target_line(&dir, line_num, total_lines);
if let Some(t) = target {
index.entry(t).or_default().push(dir);
}
}
} else {
if let Some(dir) = try_parse_directive(line, line_num) {
let target = target_line(&dir, line_num, total_lines);
if let Some(t) = target {
index.entry(t).or_default().push(dir);
}
}
}
let _ = block_comment_start_line; continue;
}
if let Some(dir) = scan_line_for_directive(line, line_num, style, &mut in_block_comment) {
let target = target_line(&dir, line_num, total_lines);
if let Some(t) = target {
index.entry(t).or_default().push(dir);
}
}
if in_block_comment {
block_comment_start_line = line_num;
}
}
SuppressionIndex { directives: index }
}
fn target_line(dir: &LineDirective, line_num: usize, total_lines: usize) -> Option<usize> {
match dir.kind {
SuppressionKind::SameLine => Some(line_num),
SuppressionKind::NextLine => {
if line_num < total_lines {
Some(line_num + 1)
} else {
None }
}
}
}
fn scan_line_for_directive(
line: &str,
line_num: usize,
style: CommentStyle,
in_block_comment: &mut bool,
) -> Option<LineDirective> {
let bytes = line.as_bytes();
let len = bytes.len();
let mut i = 0;
let mut in_string: Option<u8> = None;
while i < len {
let ch = bytes[i];
if let Some(quote) = in_string {
if ch == b'\\' {
i += 2; continue;
}
if (quote == b'"' || quote == b'\'')
&& i + 2 < len
&& bytes[i] == quote
&& bytes[i + 1] == quote
&& bytes[i + 2] == quote
{
in_string = None;
i += 3;
continue;
}
if ch == quote {
in_string = None;
}
i += 1;
continue;
}
if ch == b'r' && i + 1 < len {
let next = bytes[i + 1];
if next == b'"' {
i += 2;
while i < len && bytes[i] != b'"' {
i += 1;
}
i += 1; continue;
}
if next == b'#' {
let hash_start = i + 1;
let mut j = i + 1;
while j < len && bytes[j] == b'#' {
j += 1;
}
let hash_count = j - hash_start;
if j < len && bytes[j] == b'"' {
let close_pat_len = 1 + hash_count; i = j + 1;
'raw: while i < len {
if bytes[i] == b'"' {
let mut k = 1;
while k <= hash_count && i + k < len && bytes[i + k] == b'#' {
k += 1;
}
if k > hash_count {
i += close_pat_len;
break 'raw;
}
}
i += 1;
}
continue;
}
}
}
if (ch == b'"' || ch == b'\'') && i + 2 < len && bytes[i + 1] == ch && bytes[i + 2] == ch {
in_string = Some(ch);
i += 3;
continue;
}
if ch == b'"' || ch == b'\'' || ch == b'`' {
in_string = Some(ch);
i += 1;
continue;
}
let has_slash_slash = matches!(style, CommentStyle::CStyle | CommentStyle::PhpStyle);
if has_slash_slash && ch == b'/' && i + 1 < len && bytes[i + 1] == b'/' {
let comment_body = &line[i + 2..];
return try_parse_directive(comment_body, line_num);
}
let has_block = matches!(style, CommentStyle::CStyle | CommentStyle::PhpStyle);
if has_block && ch == b'/' && i + 1 < len && bytes[i + 1] == b'*' {
let rest = &line[i + 2..];
if let Some(end) = rest.find("*/") {
let block_body = &rest[..end];
if let Some(dir) = try_parse_directive(block_body, line_num) {
return Some(dir);
}
i = i + 2 + end + 2;
continue;
} else {
*in_block_comment = true;
let block_body = rest;
return try_parse_directive(block_body, line_num);
}
}
let has_hash = matches!(style, CommentStyle::Hash | CommentStyle::PhpStyle);
if has_hash && ch == b'#' {
let comment_body = &line[i + 1..];
return try_parse_directive(comment_body, line_num);
}
i += 1;
}
None
}
fn extract_from_line_rest(
rest: &str,
line_num: usize,
style: CommentStyle,
) -> Option<LineDirective> {
let mut in_block = false;
scan_line_for_directive(rest, line_num, style, &mut in_block)
}
fn try_parse_directive(text: &str, line_num: usize) -> Option<LineDirective> {
let trimmed = text.trim();
let trimmed = trimmed
.strip_prefix("* ")
.or(trimmed.strip_prefix('*'))
.unwrap_or(trimmed)
.trim();
if let Some(rest) = strip_directive_prefix(trimmed, "nyx:ignore-next-line") {
let matchers = parse_rule_ids(rest);
if matchers.is_empty() {
return None;
}
return Some(LineDirective {
kind: SuppressionKind::NextLine,
directive_line: line_num,
matchers,
});
}
if let Some(rest) = strip_directive_prefix(trimmed, "nyx:ignore") {
let matchers = parse_rule_ids(rest);
if matchers.is_empty() {
return None;
}
return Some(LineDirective {
kind: SuppressionKind::SameLine,
directive_line: line_num,
matchers,
});
}
None
}
fn strip_directive_prefix<'a>(text: &'a str, prefix: &str) -> Option<&'a str> {
let rest = text.strip_prefix(prefix)?;
if rest.is_empty() || rest.starts_with(char::is_whitespace) {
Some(rest)
} else {
None
}
}
fn parse_rule_ids(text: &str) -> Vec<RuleMatcher> {
text.split(',')
.map(|s| s.trim())
.filter(|s| !s.is_empty())
.map(|s| {
if let Some(prefix) = s.strip_suffix(".*") {
RuleMatcher::WildcardSuffix(prefix.to_string())
} else {
RuleMatcher::Exact(s.to_string())
}
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::Path;
fn rust_path() -> &'static Path {
Path::new("test.rs")
}
fn py_path() -> &'static Path {
Path::new("test.py")
}
fn rb_path() -> &'static Path {
Path::new("test.rb")
}
fn php_path() -> &'static Path {
Path::new("test.php")
}
fn js_path() -> &'static Path {
Path::new("test.js")
}
#[test]
fn slash_slash_comment_suppresses() {
let src = "let x = 1; // nyx:ignore rule.a\n";
let idx = parse_inline_suppressions(rust_path(), src);
assert!(idx.check(1, "rule.a").is_some());
assert!(idx.check(1, "rule.b").is_none());
}
#[test]
fn hash_comment_suppresses() {
let src = "x = 1 # nyx:ignore rule.a\n";
let idx = parse_inline_suppressions(py_path(), src);
assert!(idx.check(1, "rule.a").is_some());
}
#[test]
fn block_comment_suppresses() {
let src = "let x = 1; /* nyx:ignore rule.a */\n";
let idx = parse_inline_suppressions(rust_path(), src);
assert!(idx.check(1, "rule.a").is_some());
}
#[test]
fn same_line_only_suppresses_own_line() {
let src = "line1\nlet x = 1; // nyx:ignore rule.a\nline3\n";
let idx = parse_inline_suppressions(rust_path(), src);
assert!(idx.check(1, "rule.a").is_none());
assert!(idx.check(2, "rule.a").is_some());
assert!(idx.check(3, "rule.a").is_none());
}
#[test]
fn next_line_suppresses_following_line() {
let src = "// nyx:ignore-next-line rule.a\nlet x = dangerous();\nline3\n";
let idx = parse_inline_suppressions(rust_path(), src);
assert!(idx.check(1, "rule.a").is_none());
assert!(idx.check(2, "rule.a").is_some());
assert!(idx.check(3, "rule.a").is_none());
}
#[test]
fn multiple_rule_ids() {
let src = "let x = 1; // nyx:ignore a.b.c, x.y.z\n";
let idx = parse_inline_suppressions(rust_path(), src);
assert!(idx.check(1, "a.b.c").is_some());
assert!(idx.check(1, "x.y.z").is_some());
assert!(idx.check(1, "other").is_none());
}
#[test]
fn wildcard_suffix_matching() {
let src = "let x = 1; // nyx:ignore rs.quality.*\n";
let idx = parse_inline_suppressions(rust_path(), src);
assert!(idx.check(1, "rs.quality.foo").is_some());
assert!(idx.check(1, "rs.quality.bar").is_some());
assert!(idx.check(1, "rs.other.foo").is_none());
assert!(idx.check(1, "rs.quality").is_none());
}
#[test]
fn string_literal_not_suppressed() {
let src = "let x = \"// nyx:ignore rule.a\";\n";
let idx = parse_inline_suppressions(rust_path(), src);
assert!(idx.check(1, "rule.a").is_none());
}
#[test]
fn rust_raw_string_not_suppressed() {
let src = "let x = r#\"// nyx:ignore rule.a\"#;\n";
let idx = parse_inline_suppressions(rust_path(), src);
assert!(idx.check(1, "rule.a").is_none());
}
#[test]
fn rule_id_mismatch() {
let src = "let x = 1; // nyx:ignore rule-a\n";
let idx = parse_inline_suppressions(rust_path(), src);
assert!(idx.check(1, "rule-a").is_some());
assert!(idx.check(1, "rule-b").is_none());
}
#[test]
fn taint_rule_id_canonicalization() {
let src = "let x = 1; // nyx:ignore taint-unsanitised-flow\n";
let idx = parse_inline_suppressions(rust_path(), src);
assert!(
idx.check(1, "taint-unsanitised-flow (source 5:1)")
.is_some()
);
assert!(idx.check(1, "taint-unsanitised-flow").is_some());
}
#[test]
fn multiple_directives_same_target() {
let src = "// nyx:ignore-next-line rule-a\n// nyx:ignore-next-line rule-b\nlet x = dangerous();\n";
let idx = parse_inline_suppressions(rust_path(), src);
assert!(idx.check(2, "rule-a").is_some());
assert!(idx.check(3, "rule-b").is_some());
}
#[test]
fn block_comment_next_line() {
let src = "/* nyx:ignore-next-line rule.a */\nlet x = dangerous();\n";
let idx = parse_inline_suppressions(rust_path(), src);
assert!(idx.check(2, "rule.a").is_some());
}
#[test]
fn eof_next_line_no_panic() {
let src = "// nyx:ignore-next-line rule.a";
let idx = parse_inline_suppressions(rust_path(), src);
assert!(idx.check(1, "rule.a").is_none());
assert!(idx.check(2, "rule.a").is_none());
}
#[test]
fn crlf_line_endings() {
let src = "let x = 1; // nyx:ignore rule.a\r\nlet y = 2;\r\n";
let idx = parse_inline_suppressions(rust_path(), src);
assert!(idx.check(1, "rule.a").is_some());
assert!(idx.check(2, "rule.a").is_none());
}
#[test]
fn whitespace_tolerance() {
let src = "let x = 1; // nyx:ignore rule.a, rule.b \n";
let idx = parse_inline_suppressions(rust_path(), src);
assert!(idx.check(1, "rule.a").is_some());
assert!(idx.check(1, "rule.b").is_some());
}
#[test]
fn php_multi_style() {
let src_hash = "<?php\n$x = 1; # nyx:ignore rule.a\n";
let src_slash = "<?php\n$x = 1; // nyx:ignore rule.b\n";
let idx_hash = parse_inline_suppressions(php_path(), src_hash);
let idx_slash = parse_inline_suppressions(php_path(), src_slash);
assert!(idx_hash.check(2, "rule.a").is_some());
assert!(idx_slash.check(2, "rule.b").is_some());
}
#[test]
fn canonical_strips_parenthetical() {
assert_eq!(
canonical_rule_id("taint-unsanitised-flow (source 5:1)"),
"taint-unsanitised-flow"
);
}
#[test]
fn canonical_no_parenthetical_unchanged() {
assert_eq!(canonical_rule_id("rs.quality.unwrap"), "rs.quality.unwrap");
}
#[test]
fn canonical_trims_whitespace() {
assert_eq!(canonical_rule_id(" rule.a "), "rule.a");
}
#[test]
fn ruby_hash_comment() {
let src = "x = dangerous # nyx:ignore rule.a\n";
let idx = parse_inline_suppressions(rb_path(), src);
assert!(idx.check(1, "rule.a").is_some());
}
#[test]
fn js_template_literal_not_suppressed() {
let src = "let x = `// nyx:ignore rule.a`;\n";
let idx = parse_inline_suppressions(js_path(), src);
assert!(idx.check(1, "rule.a").is_none());
}
#[test]
fn multiline_block_comment() {
let src = "/*\n * nyx:ignore rule.a\n */\nlet x = dangerous;\n";
let idx = parse_inline_suppressions(rust_path(), src);
assert!(idx.check(2, "rule.a").is_some());
}
}