use super::dialect::{Dialect, Import};
use super::prose::Prose;
pub(super) struct Zig;
const PROSE: Prose = Prose {
line_comment: "//",
block_comment: None,
line_string: Some("\\\\"),
quotes: b"\"'",
};
impl Dialect for Zig {
fn name(&self) -> &'static str {
"zig"
}
fn extensions(&self) -> &'static [&'static str] {
&["zig"]
}
fn prose(&self) -> &Prose {
&PROSE
}
fn imports(&self, source: &str, code: &[u8]) -> Vec<Import> {
let raw = source.as_bytes();
let mut out = Vec::new();
let mut i = 0;
while let Some(k) = find(&code[i..], b"@import") {
let head = i + k;
let mut j = head + b"@import".len();
while matches!(code.get(j), Some(b' ' | b'\t')) {
j += 1;
}
i = head + 1;
if code.get(j) != Some(&b'(') {
continue;
}
if let Some(spec) = literal(raw, j + 1) {
out.push(Import { offset: head, spec });
i = j;
}
}
out
}
#[allow(clippy::case_sensitive_file_extension_comparisons, reason = "import specs are literal")]
fn is_local(&self, spec: &str) -> bool {
spec.ends_with(".zig")
}
fn escape_remedy(&self) -> &'static str {
"Zig cannot follow a path across a module boundary; declare the dependency \
as a named module in build.zig"
}
}
fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
haystack.windows(needle.len()).position(|w| w == needle)
}
fn literal(raw: &[u8], from: usize) -> Option<String> {
let mut i = from;
while raw.get(i).is_some_and(u8::is_ascii_whitespace) {
i += 1;
}
if raw.get(i) != Some(&b'"') {
return None;
}
i += 1;
let mut out = Vec::new();
while let Some(&ch) = raw.get(i) {
match ch {
b'\\' if i + 1 < raw.len() => {
out.push(raw[i + 1]);
i += 2;
}
b'"' => return String::from_utf8(out).ok(),
b'\n' => return None,
_ => {
out.push(ch);
i += 1;
}
}
}
None
}
#[cfg(test)]
mod tests {
use super::*;
fn specs(source: &str) -> Vec<String> {
let code = PROSE.code_only(source);
Zig.imports(source, &code).into_iter().map(|i| i.spec).collect()
}
#[test]
fn reads_real_imports_and_ignores_quoted_ones() {
let src = "\
const std = @import(\"std\");
const a = @import(\"../a/b.zig\");
// const c = @import(\"comment.zig\");
const doc =
\\\\@import(\"prose.zig\")
;
const d = @import( \"spaced.zig\" );
const e = @import(comptime_value);
";
assert_eq!(specs(src), ["std", "../a/b.zig", "spaced.zig"]);
}
#[test]
fn a_named_module_is_not_a_path() {
assert!(Zig.is_local("a/b.zig"));
assert!(!Zig.is_local("std"));
assert!(!Zig.is_local("irregex"));
}
}