Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 41 additions & 5 deletions crates/celox-sv-analyzer/src/syntax.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,39 @@ pub fn preprocess_source(
macros: &[(String, Option<String>)],
includes: &[&Path],
) -> Result<String, AnalyzerError> {
preprocessor(macros, includes)?
.preprocess(code, path)
.map(|source| source.text())
.map_err(|error| AnalyzerError::Parse(error.to_string()))
}

/// Expand ordered source files as one compilation unit (IEEE 1800-2023 3.12.1).
/// Macros, including definitions and undefinitions in headers, survive between
/// files. Each call starts a fresh unit with the supplied command-line macros.
/// The returned text retains file boundaries through `line directives.
pub fn preprocess_sources(
sources: &[(&str, &Path)],
macros: &[(String, Option<String>)],
includes: &[&Path],
) -> Result<String, AnalyzerError> {
let mut preprocessor = preprocessor(macros, includes)?;
let mut expanded = String::new();
for (code, path) in sources {
let source = preprocessor
.preprocess(code, path)
.map_err(|error| AnalyzerError::Parse(error.to_string()))?;
// A newline also separates files ending in a line comment or token.
expanded.push_str(&format!("\n`line 1 {:?} 0\n", path.to_string_lossy()));
expanded.push_str(&source.text());
Comment thread
tignear marked this conversation as resolved.
Resolved
expanded.push('\n');
}
Ok(expanded)
}

fn preprocessor(
macros: &[(String, Option<String>)],
includes: &[&Path],
) -> Result<celox_sv_syntax::Preprocessor, AnalyzerError> {
let mut preprocessor = celox_sv_syntax::Preprocessor::new(celox_sv_syntax::Options {
include_paths: includes.iter().map(|path| path.to_path_buf()).collect(),
..Default::default()
Expand All @@ -27,10 +60,7 @@ pub fn preprocess_source(
.preprocess(&definition, Path::new("<command-line>"))
.map_err(|error| AnalyzerError::Parse(error.to_string()))?;
}
preprocessor
.preprocess(code, path)
.map(|source| source.text())
.map_err(|error| AnalyzerError::Parse(error.to_string()))
Ok(preprocessor)
}

/// Parse native source syntax with authored tokens and original source origins.
Expand Down Expand Up @@ -209,7 +239,13 @@ mod tests {
&[],
)
.unwrap();
assert!(expanded.contains("N=7+1"), "{expanded}");
assert!(
expanded
.split_whitespace()
.collect::<String>()
.contains("N=7+1"),
"{expanded}"
);
let separate = preprocess_source(
"`ifdef LOCAL\nmodule Leaked; endmodule\n`else\nmodule Separate; endmodule\n`endif\n",
path,
Expand Down
91 changes: 91 additions & 0 deletions crates/celox-sv-analyzer/tests/compilation_units.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
use celox_sv_analyzer::syntax::{parse_source, preprocess_sources};
use std::path::Path;

#[test]
fn ordered_files_share_macros_and_directives_but_separate_calls_do_not() {
let sources = [
(
"`define WIDTH 8\n`define PLUS(x) ((x)+1)\n`default_nettype none\n",
Path::new("defs.sv"),
),
(
"module M(output logic [`WIDTH-1:0] q); assign q=`PLUS(40); endmodule\n`undef WIDTH\n",
Path::new("consumer.sv"),
),
(
"`ifdef WIDTH\ninvalid\n`endif\nmodule N; endmodule // no trailing newline",
Path::new("last.sv"),
),
];
let text = preprocess_sources(&sources, &[], &[]).unwrap();
assert!(
text.split_whitespace()
.collect::<String>()
.contains("[8-1:0]"),
"{text}"
);
assert!(
text.split_whitespace()
.collect::<String>()
.contains("((40)+1)"),
"{text}"
);
assert!(!text.contains("invalid"), "{text}");
let parsed = parse_source(&text, Path::new("unit.sv")).unwrap();
assert_eq!(parsed.units.len(), 2);
assert!(
preprocess_sources(
&[(
"module M; localparam N=`PLUS(0); endmodule",
Path::new("separate.sv")
)],
&[],
&[]
)
.is_err()
);
assert!(preprocess_sources(&sources[1..], &[], &[]).is_err());
}

#[test]
fn later_files_retain_builtin_locations_and_preprocessing_diagnostics() {
let sources = [
("`define VALUE 42\n", Path::new("defs.sv")),
(
"module M;\nlocalparam int N=`__LINE__;\ninitial $display(\"%s %d\", `__FILE__, `VALUE); endmodule",
Path::new("later.sv"),
),
];
let text = preprocess_sources(&sources, &[], &[]).unwrap();
assert!(
text.split_whitespace().collect::<String>().contains("N=2"),
"{text}"
);
assert!(text.contains("\"later.sv\""), "{text}");
parse_source(&text, Path::new("defs.sv")).unwrap();
let error = preprocess_sources(&[("`MISSING", Path::new("bad.sv"))], &[], &[])
.unwrap_err()
.to_string();
assert!(error.contains("bad.sv"), "{error}");
}

#[test]
fn serialized_macro_operators_remain_distinct_tokens() {
for sources in [
vec![(
"`define NEG -\nmodule M(output int y); assign y=`NEG-1; endmodule",
Path::new("one.sv"),
)],
vec![
("`define NEG -\n", Path::new("defs.h")),
(
"module M(output int y); assign y=`NEG-1; endmodule",
Path::new("two.sv"),
),
],
] {
let expanded = preprocess_sources(&sources, &[], &[]).unwrap();
assert!(!expanded.contains("--1"), "{expanded}");
parse_source(&expanded, Path::new("unit.sv")).unwrap();
}
}
100 changes: 95 additions & 5 deletions crates/celox-sv-syntax/src/preprocess.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,11 +80,45 @@ impl Preprocessed {

/// A compatibility view for text-based consumers. Syntax consumers should
/// use tokens and their original origins instead of parsing this text again.
/// Separators at expansion boundaries prevent adjacent tokens from merging.
pub fn text(&self) -> String {
self.tokens
.iter()
.map(|token| token.text.as_str())
.collect()
let mut text = String::new();
let mut previous: Option<&Token> = None;
for token in &self.tokens {
if let Some(left) = previous {
// Authored adjacent tokens already have the right lexical
// boundaries. Expansion/argument boundaries need a separator:
// for example, a macro's `-` followed by `-1` must not become
// a decrement. Explicit token pastes remain a single token.
let authored_adjacent = left.origin.expansion == token.origin.expansion
&& left.origin.spelling.file == token.origin.spelling.file
&& left.origin.spelling.end == token.origin.spelling.start
&& left.contributors.is_empty()
&& token.contributors.is_empty();
// Retained compiler directives require the name immediately
// after the backtick, even when a macro supplied that name.
let directive_name = left.text == "`" && token.identifier().is_some();
// Comments are not terminating whitespace for escaped
// identifiers (IEEE 1800-2023 5.6.1), and a preceding slash
// can also join their opening delimiter. Only actual white
// space safely separates every token kind.
let whitespace = matches!(token.kind, TokenKind::Whitespace | TokenKind::Newline);
if left.kind == TokenKind::Comment
&& left.text.starts_with("//")
&& token.kind != TokenKind::Newline
{
// An included file may end in a line comment without a
// newline; terminate it before rendering its caller.
text.push('\n');
} else if !left.is_trivia() && !whitespace && !authored_adjacent && !directive_name
{
text.push(' ');
}
}
text.push_str(&token.text);
previous = Some(token);
}
text
}
}

Expand Down Expand Up @@ -1498,7 +1532,13 @@ mod tests {
..Options::default()
});
let output = pp.preprocess(code, directory.join("top.sv")).unwrap();
assert!(output.text().contains("wire included = 19;"));
assert!(
output
.text()
.split_whitespace()
.collect::<String>()
.contains("wireincluded=19;")
);
assert_eq!(output.tokens.iter().filter(|t| t.text == "19").count(), 2);
let wire = output.tokens.iter().find(|t| t.text == "wire").unwrap();
assert_eq!(
Expand Down Expand Up @@ -1567,3 +1607,53 @@ mod tests {
);
}
}

#[cfg(test)]
mod serialization_tests {
use super::*;

#[test]
fn serialized_file_end_comments_cannot_consume_following_tokens() {
let mut pp = Preprocessor::default();
let mut source = pp
.preprocess("// header without final newline", "header.svh")
.unwrap();
source.merge(pp.preprocess("module M; endmodule", "caller.sv").unwrap());
let text = source.text();
let mut files = SourceMap::default();
let file = files.add("serialized.sv", text.as_str());
let tokens = lex(&files, file).unwrap();
assert_eq!(
tokens
.iter()
.filter(|t| !t.is_trivia())
.map(|t| t.text.as_str())
.collect::<Vec<_>>(),
["module", "M", ";", "endmodule"],
"{text}"
);
}

#[test]
fn text_round_trip_preserves_expansion_token_boundaries() {
let code = "`define NEG -\n`define POS +\n`define LT <\n`define SLASH /\n`define EMPTY()\n`define NUM() 1\n`define ESC \\escaped\n`define CAT(a,b) a``b\n`NEG-1; `POS+1; `LT<=1; `SLASH*2; `SLASH/*block*/2; `SLASH//line\n2; `NUM().2; `NUM()e+2; `ESC+1; `ESC/*block*/ ; `ESC//line\n; \\literal/*part*/ ; `CAT(foo,bar); 1`EMPTY().2;";
let mut pp = Preprocessor::default();
let source = pp.preprocess(code, "tokens.sv").unwrap();
let text = source.text();
let mut files = SourceMap::default();
let file = files.add("serialized.sv", text.as_str());
let tokens = lex(&files, file).unwrap();
let significant = |tokens: &[Token]| {
tokens
.iter()
.filter(|t| !t.is_trivia())
.map(|t| (t.kind, t.text.clone()))
.collect::<Vec<_>>()
};
assert_eq!(significant(&tokens), significant(&source.tokens), "{text}");
assert!(
text.contains("foobar"),
"explicit pasting must stay intact: {text}"
);
}
}
Loading
Loading