fix(parser): only show flow error if it's a flow file (#5069)

Otherwise we get a mixture of confusing error messages.
This commit is contained in:
Boshen 2024-08-22 12:19:45 +00:00
parent 96f57984eb
commit efbdced597

View file

@ -303,9 +303,9 @@ impl<'a> ParserImpl<'a> {
let (program, panicked) = match self.parse_program() { let (program, panicked) = match self.parse_program() {
Ok(program) => (program, false), Ok(program) => (program, false),
Err(error) => { Err(error) => {
self.error( let error =
self.flow_error().unwrap_or_else(|| self.overlong_error().unwrap_or(error)), self.flow_error().unwrap_or_else(|| self.overlong_error().unwrap_or(error));
); self.error(error);
let program = self.ast.program( let program = self.ast.program(
Span::default(), Span::default(),
self.source_type, self.source_type,
@ -359,12 +359,17 @@ impl<'a> ParserImpl<'a> {
/// Check for Flow declaration if the file cannot be parsed. /// Check for Flow declaration if the file cannot be parsed.
/// The declaration must be [on the first line before any code](https://flow.org/en/docs/usage/#toc-prepare-your-code-for-flow) /// The declaration must be [on the first line before any code](https://flow.org/en/docs/usage/#toc-prepare-your-code-for-flow)
fn flow_error(&self) -> Option<OxcDiagnostic> { fn flow_error(&mut self) -> Option<OxcDiagnostic> {
if !self.source_type.is_javascript() { if !self.source_type.is_javascript() {
return None; return None;
}; };
let span = self.lexer.trivia_builder.comments.first()?.span; let span = self.lexer.trivia_builder.comments.first()?.span;
span.source_text(self.source_text).contains("@flow").then(|| diagnostics::flow(span)) if span.source_text(self.source_text).contains("@flow") {
self.errors.clear();
Some(diagnostics::flow(span))
} else {
None
}
} }
/// Check if source length exceeds MAX_LEN, if the file cannot be parsed. /// Check if source length exceeds MAX_LEN, if the file cannot be parsed.
@ -447,6 +452,7 @@ mod test {
for source in sources { for source in sources {
let ret = Parser::new(&allocator, source, source_type).parse(); let ret = Parser::new(&allocator, source, source_type).parse();
assert!(ret.program.is_empty()); assert!(ret.program.is_empty());
assert_eq!(ret.errors.len(), 1);
assert_eq!(ret.errors.first().unwrap().to_string(), "Flow is not supported"); assert_eq!(ret.errors.first().unwrap().to_string(), "Flow is not supported");
} }
} }