use std::path::Path;
use unicode_normalization::UnicodeNormalization;
use crate::span_lang;
const ISSUES: &str = "https://github.com/zifeo/silcrow/issues";
pub fn language_label(ext: &str) -> String {
match ext {
"go" => "Go".into(),
"java" => "Java".into(),
"kt" | "kts" => "Kotlin".into(),
"c" | "h" => "C".into(),
"cpp" | "cc" | "cxx" | "hpp" | "hh" | "hxx" => "C++".into(),
"rb" => "Ruby".into(),
"cedar" => "Cedar".into(),
other => format!(".{other}"),
}
}
pub fn notice(path: &Path, ext: &str) -> String {
let lang = language_label(ext);
let title = format!("Add tested grammar: {lang}");
let search = format!("{ISSUES}?q={}", query_encode(&format!("is:issue {title}")));
let new = format!("{ISSUES}/new?title={}", query_encode(&title));
let tested: Vec<String> = span_lang::PINNED
.iter()
.map(|lang| {
let exts: Vec<String> = lang.extensions.iter().map(|e| format!(".{e}")).collect();
format!("{} ({})", lang.id, exts.join(", "))
})
.collect();
format!(
"{}: `{lang}` has no tested grammar, so its pins use a fallback heuristic. Each span runs to the end of the file, or to its `§ end` line, so a pin is coarse and will drift often. Tested languages: {}. Search existing requests: {search} Request support: {new}",
path.display(),
tested.join(", ")
)
}
fn query_encode(input: &str) -> String {
let mut out = String::new();
for b in input.bytes() {
match b {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' => out.push(b as char),
b' ' => out.push('+'),
_ => out.push_str(&format!("%{b:02X}")),
}
}
out
}
#[cfg(test)]
pub fn mint(
ext: &str,
source: &str,
start_line: usize,
end_line: usize,
punch: &[(usize, usize)],
) -> String {
mint_clause(ext, source, start_line, end_line, punch, "")
}
pub fn mint_clause(
ext: &str,
source: &str,
start_line: usize,
end_line: usize,
punch: &[(usize, usize)],
clause: &str,
) -> String {
let stream = prepare(ext, source, start_line, end_line, punch);
span_lang::encode_digest(&format!("{stream}\n§{clause}"))
}
pub fn is_empty(
ext: &str,
source: &str,
(start_line, end_line): (usize, usize),
nested: &[(usize, usize)],
) -> bool {
prepare(ext, source, start_line, end_line, nested).is_empty()
}
fn prepare(
ext: &str,
source: &str,
start_line: usize,
end_line: usize,
punch: &[(usize, usize)],
) -> String {
let mut kept = String::new();
let mut holes = vec![false; punch.len()];
for (idx, line) in source.lines().enumerate() {
let line_no = idx + 1;
if line_no < start_line || line_no >= end_line {
continue;
}
if let Some(at) = punched_line(line_no, punch) {
if !std::mem::replace(&mut holes[at], true) {
kept.push_str(HOLE);
kept.push('\n');
}
continue;
}
kept.push_str(line);
kept.push('\n');
}
let stripped = strip_comments(&kept, ext);
let nfc: String = stripped.nfc().collect();
let mut words: Vec<&str> = nfc
.split([' ', '\t', '\n', '\r', '\x0c'])
.filter(|word| !word.is_empty())
.collect();
while words.last() == Some(&HOLE) {
words.pop();
}
words.join(" ")
}
const HOLE: &str = "\u{1}hole";
fn punched_line(line: usize, punch: &[(usize, usize)]) -> Option<usize> {
punch
.iter()
.position(|(start, end)| line >= *start && line < *end)
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Comment {
Line,
Block,
Hash,
DashDash,
Html,
LuaLong,
}
fn comment_syntax(ext: &str) -> &'static [Comment] {
use Comment::*;
match ext {
"go" | "java" | "kt" | "kts" | "c" | "h" | "cpp" | "cc" | "cxx" | "hpp" | "hh" | "hxx"
| "cs" | "swift" | "scala" | "sc" | "dart" | "groovy" | "gradle" | "proto" | "sol"
| "php" | "m" | "mm" | "v" | "sv" => &[Line, Block],
"cedar" => &[Line],
"rb" | "pl" | "pm" | "r" | "yaml" | "yml" | "toml" | "cmake" | "ex" | "exs" | "jl"
| "ps1" | "psm1" | "tcl" | "awk" | "zsh" | "fish" | "ksh" | "mk" | "nim" | "cr"
| "coffee" => &[Hash],
"nix" => &[Hash, Block],
"lua" => &[LuaLong, DashDash],
"sql" | "hs" | "elm" | "ada" | "adb" | "ads" | "vhd" | "vhdl" => &[DashDash],
"xml" | "svg" | "xhtml" | "xsl" | "xslt" | "plist" => &[Html],
_ => &[],
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Literal {
TripleDouble,
TripleSingle,
RawTripleDouble,
RawTripleSingle,
CsVerbatim,
LuaLong,
CppRaw,
NixIndented,
}
fn literal_syntax(ext: &str) -> &'static [Literal] {
use Literal::*;
match ext {
"groovy" | "gradle" | "dart" | "ex" | "exs" | "coffee" => &[TripleDouble, TripleSingle],
"toml" => &[TripleDouble, RawTripleSingle],
"java" | "swift" | "jl" | "elm" => &[TripleDouble],
"kt" | "kts" | "scala" | "sc" | "nim" => &[RawTripleDouble],
"cs" => &[RawTripleDouble, CsVerbatim],
"lua" => &[LuaLong],
"cpp" | "cc" | "cxx" | "hpp" | "hh" | "hxx" | "h" => &[CppRaw],
"nix" => &[NixIndented],
_ => &[],
}
}
fn strip_comments(input: &str, ext: &str) -> String {
let mut out = String::with_capacity(input.len());
for (piece, start, end) in pieces(ext, input) {
if piece != Piece::Comment {
out.push_str(&input[start..end]);
}
}
out
}
pub fn literal_ranges(ext: &str, text: &str) -> Vec<(usize, usize)> {
pieces(ext, text)
.into_iter()
.filter(|(piece, _, _)| *piece == Piece::Literal)
.map(|(_, start, end)| (start, end))
.collect()
}
pub fn literal_lines(ext: &str, text: &str) -> Vec<bool> {
let mut out = vec![false; text.lines().count()];
let mut line = 0;
let mut at = 0;
for (piece, start, end) in pieces(ext, text) {
for (rel, _) in text[at..end].match_indices('\n') {
line += 1;
let opens = at + rel + 1;
if piece == Piece::Literal && opens > start && opens < end && line < out.len() {
out[line] = true;
}
}
at = end;
}
out
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Piece {
Code,
Comment,
Literal,
}
fn pieces(ext: &str, input: &str) -> Vec<(Piece, usize, usize)> {
let syntax = comment_syntax(ext);
let literal = literal_syntax(ext);
let mut out: Vec<(Piece, usize, usize)> = Vec::new();
let mut push = |piece: Piece, start: usize, end: usize| match out.last_mut() {
Some((Piece::Code, _, e)) if piece == Piece::Code && *e == start => *e = end,
_ => out.push((piece, start, end)),
};
let after_space = |i: usize| {
input[..i]
.chars()
.next_back()
.is_none_or(char::is_whitespace)
};
let mut i = 0;
while i < input.len() {
let rest = &input[i..];
let comment_like = syntax.is_empty()
&& (rest.starts_with("//") || rest.starts_with('#') || rest.starts_with("-- "))
&& input[..i]
.rsplit('\n')
.next()
.is_none_or(|before| before.trim().is_empty());
if comment_like {
let end = rest.find('\n').map_or(input.len(), |rel| i + rel);
push(Piece::Code, i, end);
i = end;
continue;
}
if let Some(len) = literal_len(literal, input, i) {
push(Piece::Literal, i, i + len);
i += len;
continue;
}
let lua_long = syntax.contains(&Comment::LuaLong)
&& rest.starts_with("--")
&& after_space(i)
&& long_bracket(&rest[2..]).is_some();
if lua_long {
let len = 2 + long_bracket_len(&rest[2..]);
push(Piece::Comment, i, i + len);
i += len;
continue;
}
let block = if syntax.contains(&Comment::Html) && rest.starts_with("<!--") {
Some(("<!--", "-->"))
} else if syntax.contains(&Comment::Block) && rest.starts_with("/*") {
Some(("/*", "*/"))
} else {
None
};
if let Some((open, close)) = block {
let end = input[i + open.len()..]
.find(close)
.map_or(input.len(), |rel| i + open.len() + rel + close.len());
push(Piece::Comment, i, end);
i = end;
continue;
}
let dash_dash = rest.starts_with("--")
&& after_space(i)
&& rest[2..].chars().next().is_none_or(char::is_whitespace);
let directive = ext == "go"
&& input[..i].chars().next_back().is_none_or(|c| c == '\n')
&& (rest.starts_with("//go:") || rest.starts_with("// +build"));
let line = (syntax.contains(&Comment::Line) && rest.starts_with("//") && !directive)
|| (syntax.contains(&Comment::Hash) && rest.starts_with('#') && after_space(i))
|| (syntax.contains(&Comment::DashDash) && dash_dash);
if line {
let end = rest.find('\n').map_or(input.len(), |rel| i + rel);
push(Piece::Comment, i, end);
i = end;
continue;
}
let ch = rest.chars().next().expect("non-empty rest");
if matches!(ch, '"' | '\'' | '`') {
let len = quoted_len(ext, rest, ch);
push(Piece::Literal, i, i + len);
i += len;
continue;
}
push(Piece::Code, i, i + ch.len_utf8());
i += ch.len_utf8();
}
out
}
fn literal_len(syntax: &[Literal], input: &str, at: usize) -> Option<usize> {
let rest = &input[at..];
syntax.iter().find_map(|form| match form {
Literal::TripleDouble => triple_len(rest, b'"', true),
Literal::TripleSingle => triple_len(rest, b'\'', true),
Literal::RawTripleDouble => triple_len(rest, b'"', false),
Literal::RawTripleSingle => triple_len(rest, b'\'', false),
Literal::CsVerbatim => cs_verbatim_len(rest),
Literal::LuaLong => long_bracket(rest).map(|_| long_bracket_len(rest)),
Literal::CppRaw => cpp_raw_len(input, at),
Literal::NixIndented => rest.starts_with("''").then(|| nix_indented_len(rest)),
})
}
fn triple_len(rest: &str, quote: u8, escapes: bool) -> Option<usize> {
let bytes = rest.as_bytes();
if !bytes.starts_with(&[quote; 3]) {
return None;
}
let mut i = 3;
while i + 3 <= bytes.len() {
if escapes && bytes[i] == b'\\' {
i += 2;
continue;
}
if bytes[i..i + 3] == [quote; 3] {
let end = i + 3;
return Some(end + bytes[end..].iter().take_while(|&&b| b == quote).count());
}
i += 1;
}
Some(rest.len())
}
fn cs_verbatim_len(rest: &str) -> Option<usize> {
let prefix = ["@\"", "$@\"", "@$\""]
.into_iter()
.find(|p| rest.starts_with(p))?;
let bytes = rest.as_bytes();
let mut i = prefix.len();
while i < bytes.len() {
if bytes[i] == b'"' {
if bytes.get(i + 1) == Some(&b'"') {
i += 2;
continue;
}
return Some(i + 1);
}
i += 1;
}
Some(rest.len())
}
fn long_bracket(rest: &str) -> Option<usize> {
let level = rest
.strip_prefix('[')?
.bytes()
.take_while(|&b| b == b'=')
.count();
(rest.as_bytes().get(1 + level) == Some(&b'[')).then_some(level)
}
fn long_bracket_len(rest: &str) -> usize {
let level = long_bracket(rest).unwrap_or(0);
let close = format!("]{}]", "=".repeat(level));
let open = level + 2;
rest[open..]
.find(&close)
.map_or(rest.len(), |rel| open + rel + close.len())
}
fn cpp_raw_len(input: &str, at: usize) -> Option<usize> {
let ident = |c: char| c.is_ascii_alphanumeric() || c == '_';
if input[..at].chars().next_back().is_some_and(ident) {
return None;
}
let rest = &input[at..];
let prefix = ["u8R\"", "uR\"", "UR\"", "LR\"", "R\""]
.into_iter()
.find(|p| rest.starts_with(p))?;
let body = &rest[prefix.len()..];
let open = body.find('(')?;
let delim = &body[..open];
if delim.len() > 16 || delim.contains([' ', ')', '\\', '\n', '\t', '"']) {
return None;
}
let close = format!("){delim}\"");
let from = prefix.len() + open + 1;
Some(
rest[from..]
.find(&close)
.map_or(rest.len(), |rel| from + rel + close.len()),
)
}
fn nix_indented_len(rest: &str) -> usize {
let bytes = rest.as_bytes();
let mut i = 2;
while i + 1 < bytes.len() {
if bytes[i] == b'\'' && bytes[i + 1] == b'\'' {
match bytes.get(i + 2) {
Some(b'\'' | b'$') => i += 3,
Some(b'\\') => i += 4,
_ => return i + 2,
}
continue;
}
i += 1;
}
rest.len()
}
struct Quotes {
lines: &'static [char],
raw: &'static [char],
}
fn quote_rules(ext: &str) -> Option<Quotes> {
let (lines, raw): (&[char], &[char]) = match ext {
"go" | "java" | "kt" | "kts" | "c" | "h" | "cpp" | "cc" | "cxx" | "hpp" | "hh" | "hxx"
| "cs" | "swift" | "scala" | "sc" | "dart" | "groovy" | "gradle" | "proto" | "sol"
| "mm" | "sv" | "awk" | "nim" | "hs" | "elm" | "ada" | "adb" | "ads" | "vhd" | "vhdl"
| "lua" | "mk" | "cedar" => (&[], &[]),
"toml" => (&[], &['\'']),
"rb" | "pl" | "pm" | "r" | "php" | "ex" | "exs" | "fish" | "coffee" => (&['"', '\''], &[]),
"zsh" | "ksh" => (&['"', '\''], &['\'']),
"jl" | "cr" | "nix" | "cmake" => (&['"'], &[]),
_ => return None,
};
Some(Quotes { lines, raw })
}
fn quoted_len(ext: &str, rest: &str, quote: char) -> usize {
let rules = quote_rules(ext);
let escapes =
!(ext == "go" && quote == '`') && rules.as_ref().is_none_or(|q| !q.raw.contains("e));
let lines = quote == '`' || rules.as_ref().is_none_or(|q| q.lines.contains("e));
let mut chars = rest.char_indices().skip(1);
while let Some((at, c)) = chars.next() {
match c {
'\\' if escapes => {
chars.next();
}
'\n' if !lines => return at,
c if c == quote => return at + c.len_utf8(),
_ => {}
}
}
rest.len()
}
pub fn undecided_lines(ext: &str, text: &str) -> Vec<usize> {
if quote_rules(ext).is_some() || !text.contains('§') {
return Vec::new();
}
literal_lines(ext, text)
.into_iter()
.zip(text.lines())
.enumerate()
.filter(|(_, (literal, line))| {
*literal && crate::marker::opens_like_a_marker(line.trim_start())
})
.map(|(idx, _)| idx + 1)
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
fn token(body: &str) -> String {
token_in("go", body)
}
#[test]
fn an_apostrophe_in_a_line_comment_opens_no_string() {
let text = "// Staff can't read drafts.\npermit (principal, action, resource)\n// § abcdefgh1\nwhen { resource.owner == \"it's\" };\n";
for ext in ["cedar", "xyz"] {
assert_eq!(literal_lines(ext, text), vec![false; 4], "{ext}");
assert!(undecided_lines(ext, text).is_empty(), "{ext}");
}
assert_ne!(
token_in("cedar", text),
token_in("cedar", &text.replace("\"it's\"", "\"its\""))
);
assert_eq!(
token_in("cedar", text),
token_in(
"cedar",
&text.replace("// Staff can't read drafts.", "// Other prose.")
)
);
}
fn token_in(ext: &str, body: &str) -> String {
mint(ext, body, 1, body.lines().count() + 1, &[])
}
#[test]
fn the_readme_language_table_and_fallback_warning_match_the_tested_grammars() {
let readme =
std::fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join("README.md"))
.unwrap();
let section = readme
.split("\n## Languages\n")
.nth(1)
.and_then(|rest| rest.split("\n## ").next())
.expect("README has a Languages section");
let rows: Vec<(String, Vec<String>)> = section
.lines()
.filter(|line| line.starts_with("| ") && !line.starts_with("| Language"))
.filter(|line| !line.starts_with("| ---"))
.map(|line| {
let cells: Vec<&str> = line.trim_matches('|').split('|').map(str::trim).collect();
let grammar = cells[0].split(',').next().unwrap().to_lowercase();
let exts = cells[1]
.split(", ")
.map(|e| e.trim_matches('`').trim_start_matches('.').to_string())
.collect();
(grammar, exts)
})
.collect();
let pinned: Vec<(String, Vec<String>)> = span_lang::PINNED
.iter()
.map(|lang| {
let exts = lang.extensions.iter().map(|e| e.to_string()).collect();
(lang.id.to_string(), exts)
})
.collect();
assert_eq!(rows, pinned);
let warning = format!("WRN {}", notice(Path::new("svc/pay.go"), "go"));
assert!(
section.lines().any(|line| line == warning),
"the README fallback warning reads otherwise than:\n{warning}"
);
}
#[test]
fn a_trailing_separator_is_a_byte_of_a_fallback_span() {
assert_ne!(token("f(\"a, )\");\n"), token("f(\"a)\");\n"));
assert_ne!(token("f(a, b,\n);\n"), token("f(a, b);\n"));
assert_ne!(token_in("jl", "t = (1,)\n"), token_in("jl", "t = (1)\n"));
assert_ne!(token_in("hs", "u = (,)\n"), token_in("hs", "u = ()\n"));
assert_eq!(
token_in("jl", "t = (1, )\n"),
token_in("jl", "t = (1, )\n")
);
assert_eq!(token("f(a,\n b);\n"), token("f(a, b);\n"));
}
#[test]
fn only_ascii_whitespace_collapses() {
assert_ne!(token("p(\"a\u{a0}b\")\n"), token("p(\"a b\")\n"));
assert_ne!(token("p(\"a\u{3000}b\")\n"), token("p(\"a b\")\n"));
assert_eq!(token("p(\"a \t\x0c b\")\n"), token("p(\"a b\")\n"));
}
#[test]
fn a_multi_line_string_is_a_literal() {
let toml = |q: &str, word: &str| format!("s = {q}\n# {word}\n{q}\n");
for q in ["\"\"\"", "'''"] {
assert_ne!(
token_in("toml", &toml(q, "allow")),
token_in("toml", &toml(q, "deny"))
);
assert_eq!(
literal_lines("toml", &toml(q, "§ abcdefgh1")),
[false, true, true]
);
}
assert_eq!(
token_in("toml", "p = '''C:\\''' # one\nq = 'C:\\' # one\n"),
token_in("toml", "p = '''C:\\''' # two\nq = 'C:\\' # two\n")
);
let rb = |word: &str| format!("s = \"a\n# {word}\nb\" # note\n");
assert_ne!(token_in("rb", &rb("allow")), token_in("rb", &rb("deny")));
assert_eq!(
token_in("rb", "s = \"a\nb\" # one\n"),
token_in("rb", "s = \"a\nb\" # two\n")
);
assert_eq!(literal_lines("rb", &rb("§ abcdefgh1")), [false, true, true]);
assert_eq!(
literal_lines("go", "s := \"a\n// § abcdefgh1\n"),
[false, false]
);
}
#[test]
fn a_marker_where_the_string_rules_are_unknown_is_undecided() {
let open = "a = 'x\n# § abcdefgh1\n'\n";
assert_eq!(literal_lines("conf", open), [false, true, true]);
assert_eq!(undecided_lines("conf", open), [2]);
assert_eq!(undecided_lines("yaml", open), [2]);
assert!(undecided_lines("rb", open).is_empty());
assert!(undecided_lines("conf", "a = 'x'\n# § abcdefgh1\n").is_empty());
}
#[test]
fn comments_and_whitespace_do_not_move() {
let clean = "save(x);\n";
assert_eq!(token(clean), token("save(x); // line\n"));
assert_eq!(token(clean), token("save(x); /* block */\n"));
assert_eq!(token_in("rb", clean), token_in("rb", "save(x); # hash\n"));
assert_eq!(
token_in("sql", clean),
token_in("sql", "save(x); -- dash\n")
);
assert_eq!(
token_in("xml", clean),
token_in("xml", "save(x); <!-- html -->\n")
);
assert_eq!(token(clean), token("save(x); \n"));
assert_eq!(token("save( x );\n"), token("save( x );\n"));
}
#[test]
fn a_go_directive_is_code() {
assert_ne!(
token("//go:build linux\npackage a\n"),
token("//go:build darwin\npackage a\n")
);
assert_ne!(token("//go:generate a\npackage a\n"), token("package a\n"));
assert_ne!(
token("// +build a\npackage a\n"),
token("// +build b\npackage a\n")
);
assert_eq!(token("// note\npackage a\n"), token("package a\n"));
}
#[test]
fn a_wrapper_the_language_does_not_use_is_code() {
assert_ne!(
token_in("c", "#define LIMIT 10\n"),
token_in("c", "#define LIMIT 1000\n")
);
assert_ne!(
token("for n--; n > 0; {charge()}\n"),
token("for n--; n > 0; {refund()}\n")
);
assert_ne!(
token_in("yaml", "run: x --dry-run\n"),
token_in("yaml", "run: x --force\n")
);
assert_ne!(
token_in("pl", "print $#a;\n"),
token_in("pl", "print $#b;\n")
);
assert_ne!(token_in("hs", "a --> b\n"), token_in("hs", "a --> c\n"));
assert_ne!(
token_in("conf", "a = 1 # x\n"),
token_in("conf", "a = 1 # y\n")
);
}
#[test]
fn nfc_normalizes() {
let nfd = "cafe\u{0301}\n";
let nfc = "caf\u{e9}\n";
assert_eq!(token(nfd), token(nfc));
}
#[test]
fn body_change_moves() {
assert_ne!(token("save(x);\n"), token("save(x + 1);\n"));
}
#[test]
fn a_fallback_pin_is_one_token() {
assert_eq!(mint_clause("go", "save(x);\n", 1, 2, &[], "").len(), 5);
}
#[test]
fn notice_links_github_search_and_new_issue() {
let n = notice(Path::new("main.go"), "go");
assert!(n.contains("fallback heuristic"), "{n}");
assert!(n.contains("runs to the end of the file"), "{n}");
assert!(n.contains("or to its `§ end` line"), "{n}");
assert!(n.contains("rust (.rs)"), "{n}");
assert!(n.contains("github.com/zifeo/silcrow/issues?q="), "{n}");
assert!(n.contains("issues/new?title="), "{n}");
assert!(n.contains("Add+tested+grammar"), "{n}");
assert!(n.contains("Go"), "{n}");
}
#[test]
fn punch_drops_inner_span() {
let src = "aaa\ninner\nbbb\n";
let full = mint("go", src, 1, 4, &[]);
let punched = mint("go", src, 1, 4, &[(2, 3)]);
assert_ne!(full, punched);
assert_ne!(
punched,
mint("go", "aaa\nbbb\n", 1, 3, &[]),
"the hole is a token"
);
assert_eq!(punched, mint("go", "aaa\nother\nbbb\n", 1, 4, &[(2, 3)]));
assert_ne!(punched, mint("go", "inner\naaa\nbbb\n", 1, 4, &[(1, 2)]));
}
#[test]
fn per_language_literals_and_operators_are_code() {
assert_ne!(
token_in("nix", "cfg // { enable = true; }\n"),
token_in("nix", "cfg // { enable = false; }\n")
);
assert_eq!(
token_in("nix", "x = 1; # one\n/* two */\n"),
token_in("nix", "x = 1;\n")
);
assert_ne!(
token_in("nix", "s = ''\n # a\n'';\n"),
token_in("nix", "s = ''\n # b\n'';\n")
);
assert_ne!(
token_in("kt", "val u = \"\"\"\nhttps://pay.example.com/v1\n\"\"\"\n"),
token_in("kt", "val u = \"\"\"\nhttps://pay.example.com/v2\n\"\"\"\n")
);
assert_ne!(
token_in("lua", "local s = [[\n-- allow\n]]\n"),
token_in("lua", "local s = [[\n-- deny\n]]\n")
);
assert_ne!(
token_in("lua", "local s = [==[\n]] -- allow\n]==]\n"),
token_in("lua", "local s = [==[\n]] -- deny\n]==]\n")
);
assert_eq!(
token_in("lua", "--[[ one\ntwo ]]\nx = 1\n"),
token_in("lua", "x = 1\n")
);
assert_ne!(
token_in("cpp", "auto s = R\"x(\n// allow\n)x\";\n"),
token_in("cpp", "auto s = R\"x(\n// deny\n)x\";\n")
);
assert_eq!(token_in("cpp", "f(); // one\n"), token_in("cpp", "f();\n"));
}
#[test]
fn a_crlf_file_hashes_as_its_lf_form() {
let src = "u := `a\nb`\ns := \"\"\"\nc\n\"\"\" // d\n";
assert_eq!(token(src), token(&src.replace('\n', "\r\n")));
assert_eq!(
token_in("kt", src),
token_in("kt", &src.replace('\n', "\r\n"))
);
}
#[test]
fn a_raw_string_ends_at_its_quote_whatever_precedes_it() {
let go = |host: &str| format!("d := `C:\\`\nu := `https://{host}/v1`\n");
assert_ne!(
token(&go("pay.example.com")),
token(&go("evil.example.net"))
);
let kt = |host: &str| {
format!("val d = \"\"\"C:\\\"\"\"\nval u = \"\"\"https://{host}/v1\"\"\"\n")
};
assert_ne!(
token_in("kt", &kt("pay.example.com")),
token_in("kt", &kt("evil.example.net"))
);
let cs = |host: &str| format!("var d = @\"C:\\\";\nvar u = \"https://{host}/v1\";\n");
assert_ne!(
token_in("cs", &cs("pay.example.com")),
token_in("cs", &cs("evil.example.net"))
);
assert_ne!(
token_in("cs", "f(@\"a\"\" // x\");\n"),
token_in("cs", "f(@\"a\"\" // y\");\n")
);
let java = |host: &str| {
format!("var s = \"\"\"\n a \\\"\"\" b\n https://{host}/v1\n \"\"\";\n")
};
assert_ne!(
token_in("java", &java("pay.example.com")),
token_in("java", &java("evil.example.net"))
);
assert_eq!(
literal_lines("go", "d := `C:\\`\n// § abcdefgh1\n"),
[false, false]
);
}
#[test]
fn a_line_inside_a_multi_line_literal_is_named() {
let kt = "val a = 1\nval s = \"\"\"\n// § abcdefgh1\n\"\"\"\n// § abcdefgh2\n";
assert_eq!(literal_lines("kt", kt), [false, false, true, true, false]);
let go = "x := `\n// § abcdefgh1\n`\n";
assert_eq!(literal_lines("go", go), [false, true, true]);
assert_eq!(
literal_lines("go", "a // `\n// § abcdefgh1\n"),
[false, false]
);
}
#[test]
fn comment_wrappers_inside_strings_are_kept() {
assert_ne!(
token("post(\"https://pay.example.com/v1/retry\")\n"),
token("post(\"https://pay.example.com/v2/charge-anyway\")\n")
);
assert_ne!(
token_in("sql", "q('a -- b')\n"),
token_in("sql", "q('a -- c')\n")
);
assert_ne!(
token_in("rb", "p(`x # y`)\n"),
token_in("rb", "p(`x # z`)\n")
);
assert_ne!(token("p(\"\\\" // a\")\n"), token("p(\"\\\" // b\")\n"));
assert_eq!(token("p(\"a\") // one\n"), token("p(\"a\") // two\n"));
assert_eq!(
token_in("rb", "p(\"it's\") # one\n"),
token_in("rb", "p(\"it's\") # two\n")
);
}
}