Skip to content
Closed
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
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,13 @@

All notable milestones for the nera project are documented in this file.

## Included-header diagnostic locations

- `nera build`, `nera check` and the language server report lexer and
preprocessor errors in the header that contains them, with that header's
line and column. This also applies to nested `-include` and `-include_lib`
directives.

## Generated MIME tables compile with less memory

- The compiler reuses backend variable slots for block-local temporaries in
Expand Down
2 changes: 1 addition & 1 deletion crates/nera-ir/tests/verify_lowered.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ fn lower_fixture_with_atoms(relative_path: &str) -> (IrModule, AtomId, AtomId) {
let mut preproc = Preprocessor::new(&source, &path);
let tokens = preproc.process(tokens).unwrap();
let combined = preproc.take_combined_source();
let mut parser = Parser::with_tokens(&combined, tokens, Default::default());
let mut parser = Parser::with_preprocessed(&combined, tokens, Default::default());
let parsed = parser.parse_module();
assert!(!parsed.has_errors(), "{relative_path}: {:?}", parsed.errors);
let mut names = parser.atom_names();
Expand Down
22 changes: 22 additions & 0 deletions crates/nera-syntax/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,28 @@ impl ParseError {
}
}

pub(crate) fn map_span(&mut self, map: impl FnOnce(Span) -> Span) {
match self {
Self::UnexpectedEof { position } => {
*position = map(Span::new(*position, *position)).start;
}
Self::LexerError { position } => {
*position = map(Span::new(*position, *position + 1)).start;
}
Self::UnexpectedToken { span, .. }
| Self::InvalidInteger { span }
| Self::InvalidFloat { span }
| Self::InvalidBinaryUnit { span, .. }
| Self::UndefinedMacro { span, .. }
| Self::UnclosedConditional { span }
| Self::UnexpectedDirective { span, .. }
| Self::IncludeError { span, .. }
| Self::MacroRecursion { span, .. }
| Self::ReservedKeyword { span, .. }
| Self::HeadMismatch { span, .. } => *span = map(*span),
}
}

/// Return a short error label (used under the caret line).
pub fn label(&self) -> &str {
match self {
Expand Down
55 changes: 44 additions & 11 deletions crates/nera-syntax/src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ impl ParseResult {
/// Atom strings are interned via `string_interner::StringInterner`.
pub struct Parser<'src> {
source: &'src str,
expansions: Option<std::borrow::Cow<'src, crate::preproc::ExpansionSpans>>,
tokens: Vec<(Token, Span)>,
pos: usize,
interner: DefaultStringInterner,
Expand All @@ -109,6 +110,7 @@ impl<'src> Parser<'src> {
};
Self {
source,
expansions: None,
tokens,
pos: 0,
interner: DefaultStringInterner::default(),
Expand All @@ -131,6 +133,7 @@ impl<'src> Parser<'src> {
};
Self {
source,
expansions: None,
tokens,
pos: 0,
interner,
Expand All @@ -140,18 +143,16 @@ impl<'src> Parser<'src> {
}
}

/// Create a new parser from pre-lexed (and preprocessed) tokens.
///
/// This is used when the token stream has already been produced by the
/// lexer and processed by the preprocessor. The parser skips internal
/// lexing and operates directly on the provided token vector.
/// Create a parser from lexer tokens whose spelling is entirely in `source`.
/// Use `with_preprocessed` for output from the preprocessor.
pub fn with_tokens(
source: &'src str,
tokens: Vec<(Token, Span)>,
interner: DefaultStringInterner,
) -> Self {
Self {
source,
expansions: None,
tokens,
pos: 0,
interner,
Expand All @@ -161,6 +162,29 @@ impl<'src> Parser<'src> {
}
}

/// Parse preprocessor output using the same combined source that produced it.
pub fn with_preprocessed(
combined_source: &'src str,
processed: crate::preproc::PreprocessedTokens,
interner: DefaultStringInterner,
) -> Self {
let mut parser = Self::with_tokens(combined_source, processed.tokens, interner);
parser.expansions = Some(std::borrow::Cow::Owned(processed.expansions));
parser
}

pub(crate) fn with_expansion_spans(mut self, expansions: &'src crate::preproc::ExpansionSpans) -> Self {
self.expansions = Some(std::borrow::Cow::Borrowed(expansions));
self
}

fn map_error(&self, error: ParseError) -> ParseError {
match self.expansions.as_deref() {
Some(expansions) => expansions.map_error(error),
None => error,
}
}

/// Consume the parser and return the interner for reuse.
pub fn into_interner(self) -> DefaultStringInterner {
self.interner
Expand Down Expand Up @@ -329,7 +353,7 @@ impl<'src> Parser<'src> {
type_refs,
span: Span::new(start, end),
},
errors: self.errors.clone(),
errors: self.errors.iter().cloned().map(|error| self.map_error(error)).collect(),
}
}

Expand Down Expand Up @@ -746,8 +770,8 @@ impl<'src> Parser<'src> {
// Preserve the existing EUnit transform without interpreting arbitrary tuples.
if let Some(t) = self.tokens.get(self.pos..self.pos + 5) {
flags.eunit_autoexport |= t[0].0 == Token::LBrace && t[2].0 == Token::Comma && t[4].0 == Token::RBrace
&& self.source[t[1].1.start..t[1].1.end].trim_matches('\'') == "parse_transform"
&& self.source[t[3].1.start..t[3].1.end].trim_matches('\'') == "eunit_autoexport";
&& self.slice_at(self.pos + 1).trim_matches('\'') == "parse_transform"
&& self.slice_at(self.pos + 3).trim_matches('\'') == "eunit_autoexport";
}
self.skip_compile_term();
}
Expand Down Expand Up @@ -1136,7 +1160,7 @@ impl<'src> Parser<'src> {
///
/// Parses a single expression and optionally consumes a trailing dot.
pub fn parse_term(&mut self) -> Result<Expr, ParseError> {
let expr = self.parse_expr_bp(0)?;
let expr = self.parse_expr_bp(0).map_err(|error| self.map_error(error))?;
// Consume optional trailing dot (`.app` files end with `Term.`)
self.eat(&Token::Dot);
Ok(expr)
Expand Down Expand Up @@ -3493,15 +3517,24 @@ impl<'src> Parser<'src> {
if desc.starts_with('\'') {
desc.to_string()
} else {
format!("{} '{}'", desc, self.slice_at(self.pos))
let span = self.tokens[self.pos].1;
let spelling = match self.expansions.as_deref() {
Some(expansions) if expansions.spelling(span).is_some() => {
let origin = expansions.origin(span);
&self.source[origin.start..origin.end]
}
_ => self.slice_at(self.pos),
};
format!("{} '{}'", desc, spelling)
}
}
}

/// Get the source slice for the token at the given position.
fn slice_at(&self, pos: usize) -> &str {
let span = self.tokens[pos].1;
&self.source[span.start..span.end]
let spelling = self.expansions.as_deref().and_then(|expansions| expansions.spelling(span)).unwrap_or(span);
&self.source[spelling.start..spelling.end]
}

/// Expect an atom name (unquoted atom, quoted atom, or a keyword used as an
Expand Down
Loading
Loading