diff --git a/crates/wit-parser/src/ast.rs b/crates/wit-parser/src/ast.rs index bf9da178b5..06543df063 100644 --- a/crates/wit-parser/src/ast.rs +++ b/crates/wit-parser/src/ast.rs @@ -1,17 +1,21 @@ -use crate::{Error, PackageNotFoundError, UnresolvedPackageGroup}; +use crate::ast::error::ParseError; +use crate::{ParseResult, UnresolvedPackage, UnresolvedPackageGroup}; use alloc::borrow::Cow; use alloc::boxed::Box; use alloc::format; use alloc::string::{String, ToString}; use alloc::vec::Vec; -use anyhow::{Context, Result, bail}; +#[cfg(feature = "std")] +use anyhow::Context as _; use core::fmt; use core::mem; +use core::result::Result; use lex::{Span, Token, Tokenizer}; use semver::Version; #[cfg(feature = "std")] use std::path::Path; +pub mod error; pub mod lex; pub use resolve::Resolver; @@ -33,7 +37,7 @@ impl<'a> PackageFile<'a> { /// /// This will optionally start with `package foo:bar;` and then will have a /// list of ast items after it. - fn parse(tokens: &mut Tokenizer<'a>) -> Result { + fn parse(tokens: &mut Tokenizer<'a>) -> ParseResult { let mut package_name_tokens_peek = tokens.clone(); let docs = parse_docs(&mut package_name_tokens_peek)?; @@ -62,10 +66,10 @@ impl<'a> PackageFile<'a> { tokens: &mut Tokenizer<'a>, docs: Docs<'a>, attributes: Vec>, - ) -> Result { + ) -> ParseResult { let span = tokens.expect(Token::Package)?; if !attributes.is_empty() { - bail!(Error::new( + return Err(ParseError::new_syntax( span, format!("cannot place attributes on nested packages"), )); @@ -121,7 +125,7 @@ pub struct DeclList<'a> { } impl<'a> DeclList<'a> { - fn parse_until(tokens: &mut Tokenizer<'a>, end: Option) -> Result> { + fn parse_until(tokens: &mut Tokenizer<'a>, end: Option) -> ParseResult> { let mut items = Vec::new(); let mut docs = parse_docs(tokens)?; loop { @@ -151,8 +155,8 @@ impl<'a> DeclList<'a> { &'b UsePath<'a>, Option<&'b [UseName<'a>]>, WorldOrInterface, - ) -> Result<()>, - ) -> Result<()> { + ) -> ParseResult<()>, + ) -> ParseResult<()> { for item in self.items.iter() { match item { AstItem::World(world) => { @@ -259,7 +263,7 @@ enum AstItem<'a> { } impl<'a> AstItem<'a> { - fn parse(tokens: &mut Tokenizer<'a>, docs: Docs<'a>) -> Result { + fn parse(tokens: &mut Tokenizer<'a>, docs: Docs<'a>) -> ParseResult { let attributes = Attribute::parse_list(tokens)?; match tokens.clone().next()? { Some((_span, Token::Interface)) => { @@ -285,7 +289,7 @@ struct PackageName<'a> { } impl<'a> PackageName<'a> { - fn parse(tokens: &mut Tokenizer<'a>, docs: Docs<'a>) -> Result { + fn parse(tokens: &mut Tokenizer<'a>, docs: Docs<'a>) -> ParseResult { let namespace = parse_id(tokens)?; tokens.expect(Token::Colon)?; let name = parse_id(tokens)?; @@ -322,7 +326,7 @@ struct ToplevelUse<'a> { } impl<'a> ToplevelUse<'a> { - fn parse(tokens: &mut Tokenizer<'a>, attributes: Vec>) -> Result { + fn parse(tokens: &mut Tokenizer<'a>, attributes: Vec>) -> ParseResult { let span = tokens.expect(Token::Use)?; let item = UsePath::parse(tokens)?; let as_ = if tokens.eat(Token::As)? { @@ -352,7 +356,7 @@ impl<'a> World<'a> { tokens: &mut Tokenizer<'a>, docs: Docs<'a>, attributes: Vec>, - ) -> Result { + ) -> ParseResult { tokens.expect(Token::World)?; let name = parse_id(tokens)?; let items = Self::parse_items(tokens)?; @@ -364,7 +368,7 @@ impl<'a> World<'a> { }) } - fn parse_items(tokens: &mut Tokenizer<'a>) -> Result>> { + fn parse_items(tokens: &mut Tokenizer<'a>) -> ParseResult>> { tokens.expect(Token::LeftBrace)?; let mut items = Vec::new(); loop { @@ -392,7 +396,7 @@ impl<'a> WorldItem<'a> { tokens: &mut Tokenizer<'a>, docs: Docs<'a>, attributes: Vec>, - ) -> Result> { + ) -> ParseResult> { match tokens.clone().next()? { Some((_span, Token::Import)) => { Import::parse(tokens, docs, attributes).map(WorldItem::Import) @@ -443,7 +447,7 @@ impl<'a> Import<'a> { tokens: &mut Tokenizer<'a>, docs: Docs<'a>, attributes: Vec>, - ) -> Result> { + ) -> ParseResult> { tokens.expect(Token::Import)?; let kind = ExternKind::parse(tokens)?; Ok(Import { @@ -465,7 +469,7 @@ impl<'a> Export<'a> { tokens: &mut Tokenizer<'a>, docs: Docs<'a>, attributes: Vec>, - ) -> Result> { + ) -> ParseResult> { tokens.expect(Token::Export)?; let kind = ExternKind::parse(tokens)?; Ok(Export { @@ -483,7 +487,7 @@ enum ExternKind<'a> { } impl<'a> ExternKind<'a> { - fn parse(tokens: &mut Tokenizer<'a>) -> Result> { + fn parse(tokens: &mut Tokenizer<'a>) -> ParseResult> { // Create a copy of the token stream to test out if this is a function // or an interface import. In those situations the token stream gets // reset to the state of the clone and we continue down those paths. @@ -540,7 +544,7 @@ impl<'a> Interface<'a> { tokens: &mut Tokenizer<'a>, docs: Docs<'a>, attributes: Vec>, - ) -> Result { + ) -> ParseResult { tokens.expect(Token::Interface)?; let name = parse_id(tokens)?; let items = Self::parse_items(tokens)?; @@ -552,7 +556,7 @@ impl<'a> Interface<'a> { }) } - pub(super) fn parse_items(tokens: &mut Tokenizer<'a>) -> Result>> { + pub(super) fn parse_items(tokens: &mut Tokenizer<'a>) -> ParseResult>> { tokens.expect(Token::LeftBrace)?; let mut items = Vec::new(); loop { @@ -593,7 +597,7 @@ enum UsePath<'a> { } impl<'a> UsePath<'a> { - fn parse(tokens: &mut Tokenizer<'a>) -> Result { + fn parse(tokens: &mut Tokenizer<'a>) -> ParseResult { let id = parse_id(tokens)?; if tokens.eat(Token::Colon)? { // `foo:bar/baz@1.0` @@ -632,7 +636,7 @@ struct UseName<'a> { } impl<'a> Use<'a> { - fn parse(tokens: &mut Tokenizer<'a>, attributes: Vec>) -> Result { + fn parse(tokens: &mut Tokenizer<'a>, attributes: Vec>) -> ParseResult { tokens.expect(Token::Use)?; let from = UsePath::parse(tokens)?; tokens.expect(Token::Period)?; @@ -674,7 +678,7 @@ struct IncludeName<'a> { } impl<'a> Include<'a> { - fn parse(tokens: &mut Tokenizer<'a>, attributes: Vec>) -> Result { + fn parse(tokens: &mut Tokenizer<'a>, attributes: Vec>) -> ParseResult { tokens.expect(Token::Include)?; let from = UsePath::parse(tokens)?; @@ -801,7 +805,7 @@ impl<'a> ResourceFunc<'a> { docs: Docs<'a>, attributes: Vec>, tokens: &mut Tokenizer<'a>, - ) -> Result { + ) -> ParseResult { match tokens.clone().next()? { Some((span, Token::Constructor)) => { tokens.expect(Token::Constructor)?; @@ -965,8 +969,11 @@ struct Func<'a> { } impl<'a> Func<'a> { - fn parse(tokens: &mut Tokenizer<'a>) -> Result> { - fn parse_params<'a>(tokens: &mut Tokenizer<'a>, left_paren: bool) -> Result> { + fn parse(tokens: &mut Tokenizer<'a>) -> ParseResult> { + fn parse_params<'a>( + tokens: &mut Tokenizer<'a>, + left_paren: bool, + ) -> ParseResult> { if left_paren { tokens.expect(Token::LeftParen)?; }; @@ -1001,7 +1008,7 @@ impl<'a> InterfaceItem<'a> { tokens: &mut Tokenizer<'a>, docs: Docs<'a>, attributes: Vec>, - ) -> Result> { + ) -> ParseResult> { match tokens.clone().next()? { Some((_span, Token::Type)) => { TypeDef::parse(tokens, docs, attributes).map(InterfaceItem::TypeDef) @@ -1035,7 +1042,7 @@ impl<'a> TypeDef<'a> { tokens: &mut Tokenizer<'a>, docs: Docs<'a>, attributes: Vec>, - ) -> Result { + ) -> ParseResult { tokens.expect(Token::Type)?; let name = parse_id(tokens)?; tokens.expect(Token::Equals)?; @@ -1053,7 +1060,7 @@ impl<'a> TypeDef<'a> { tokens: &mut Tokenizer<'a>, docs: Docs<'a>, attributes: Vec>, - ) -> Result { + ) -> ParseResult { tokens.expect(Token::Flags)?; let name = parse_id(tokens)?; let ty = Type::Flags(Flags { @@ -1080,7 +1087,7 @@ impl<'a> TypeDef<'a> { tokens: &mut Tokenizer<'a>, docs: Docs<'a>, attributes: Vec>, - ) -> Result { + ) -> ParseResult { tokens.expect(Token::Resource)?; let name = parse_id(tokens)?; let mut funcs = Vec::new(); @@ -1109,7 +1116,7 @@ impl<'a> TypeDef<'a> { tokens: &mut Tokenizer<'a>, docs: Docs<'a>, attributes: Vec>, - ) -> Result { + ) -> ParseResult { tokens.expect(Token::Record)?; let name = parse_id(tokens)?; let ty = Type::Record(Record { @@ -1138,7 +1145,7 @@ impl<'a> TypeDef<'a> { tokens: &mut Tokenizer<'a>, docs: Docs<'a>, attributes: Vec>, - ) -> Result { + ) -> ParseResult { tokens.expect(Token::Variant)?; let name = parse_id(tokens)?; let ty = Type::Variant(Variant { @@ -1172,7 +1179,7 @@ impl<'a> TypeDef<'a> { tokens: &mut Tokenizer<'a>, docs: Docs<'a>, attributes: Vec>, - ) -> Result { + ) -> ParseResult { tokens.expect(Token::Enum)?; let name = parse_id(tokens)?; let ty = Type::Enum(Enum { @@ -1201,7 +1208,7 @@ impl<'a> NamedFunc<'a> { tokens: &mut Tokenizer<'a>, docs: Docs<'a>, attributes: Vec>, - ) -> Result { + ) -> ParseResult { let name = parse_id(tokens)?; tokens.expect(Token::Colon)?; let func = Func::parse(tokens)?; @@ -1215,7 +1222,7 @@ impl<'a> NamedFunc<'a> { } } -fn parse_id<'a>(tokens: &mut Tokenizer<'a>) -> Result> { +fn parse_id<'a>(tokens: &mut Tokenizer<'a>) -> ParseResult> { match tokens.next()? { Some((span, Token::Id)) => Ok(Id { name: tokens.parse_id(span)?, @@ -1225,11 +1232,11 @@ fn parse_id<'a>(tokens: &mut Tokenizer<'a>) -> Result> { name: tokens.parse_explicit_id(span)?, span, }), - other => Err(err_expected(tokens, "an identifier or string", other).into()), + other => Err(err_expected(tokens, "an identifier or string", other)), } } -fn parse_opt_version(tokens: &mut Tokenizer<'_>) -> Result> { +fn parse_opt_version(tokens: &mut Tokenizer<'_>) -> ParseResult> { if tokens.eat(Token::At)? { parse_version(tokens).map(Some) } else { @@ -1237,7 +1244,7 @@ fn parse_opt_version(tokens: &mut Tokenizer<'_>) -> Result) -> Result<(Span, Version)> { +fn parse_version(tokens: &mut Tokenizer<'_>) -> ParseResult<(Span, Version)> { let start = tokens.expect(Token::Integer)?.start(); tokens.expect(Token::Period)?; tokens.expect(Token::Integer)?; @@ -1247,7 +1254,8 @@ fn parse_version(tokens: &mut Tokenizer<'_>) -> Result<(Span, Version)> { eat_ids(tokens, Token::Minus, &mut span)?; eat_ids(tokens, Token::Plus, &mut span)?; let string = tokens.get_span(span); - let version = Version::parse(string).map_err(|e| Error::new(span, e.to_string()))?; + let version = + Version::parse(string).map_err(|e| ParseError::new_syntax(span, e.to_string()))?; return Ok((span, version)); // According to `semver.org` this is what we're parsing: @@ -1303,7 +1311,11 @@ fn parse_version(tokens: &mut Tokenizer<'_>) -> Result<(Span, Version)> { // Note that this additionally doesn't try to return any first-class errors. // Instead this bails out on something unrecognized for something else in // the system to return an error. - fn eat_ids(tokens: &mut Tokenizer<'_>, prefix: Token, end: &mut Span) -> Result<()> { + fn eat_ids( + tokens: &mut Tokenizer<'_>, + prefix: Token, + end: &mut Span, + ) -> Result<(), lex::Error> { if !tokens.eat(prefix)? { return Ok(()); } @@ -1327,7 +1339,7 @@ fn parse_version(tokens: &mut Tokenizer<'_>) -> Result<(Span, Version)> { } } -fn parse_docs<'a>(tokens: &mut Tokenizer<'a>) -> Result> { +fn parse_docs<'a>(tokens: &mut Tokenizer<'a>) -> Result, lex::Error> { let mut docs = Docs::default(); let mut clone = tokens.clone(); let mut started = false; @@ -1356,7 +1368,7 @@ fn parse_docs<'a>(tokens: &mut Tokenizer<'a>) -> Result> { } impl<'a> Type<'a> { - fn parse(tokens: &mut Tokenizer<'a>) -> Result { + fn parse(tokens: &mut Tokenizer<'a>) -> ParseResult { match tokens.next()? { Some((span, Token::U8)) => Ok(Type::U8(span)), Some((span, Token::U16)) => Ok(Type::U16(span)), @@ -1392,7 +1404,9 @@ impl<'a> Type<'a> { let size = if tokens.eat(Token::Comma)? { let number = tokens.next()?; if let Some((span, Token::Integer)) = number { - let size: u32 = tokens.get_span(span).parse()?; + let size: u32 = tokens.get_span(span).parse().map_err(|e| { + ParseError::new_syntax(span, format!("invalid list size: {e}")) + })?; Some(size) } else { return Err(err_expected(tokens, "fixed-length", number).into()); @@ -1560,8 +1574,8 @@ fn parse_list<'a, T>( tokens: &mut Tokenizer<'a>, start: Token, end: Token, - parse: impl FnMut(Docs<'a>, &mut Tokenizer<'a>) -> Result, -) -> Result> { + parse: impl FnMut(Docs<'a>, &mut Tokenizer<'a>) -> ParseResult, +) -> ParseResult> { tokens.expect(start)?; parse_list_trailer(tokens, end, parse) } @@ -1569,8 +1583,8 @@ fn parse_list<'a, T>( fn parse_list_trailer<'a, T>( tokens: &mut Tokenizer<'a>, end: Token, - mut parse: impl FnMut(Docs<'a>, &mut Tokenizer<'a>) -> Result, -) -> Result> { + mut parse: impl FnMut(Docs<'a>, &mut Tokenizer<'a>) -> ParseResult, +) -> ParseResult> { let mut items = Vec::new(); loop { // get docs before we skip them to try to eat the end token @@ -1598,13 +1612,15 @@ fn err_expected( tokens: &Tokenizer<'_>, expected: &'static str, found: Option<(Span, Token)>, -) -> Error { +) -> ParseError { match found { - Some((span, token)) => Error::new( + Some((span, token)) => ParseError::new_syntax( span, format!("expected {}, found {}", expected, token.describe()), ), - None => Error::new(tokens.eof_span(), format!("expected {expected}, found eof")), + None => { + ParseError::new_syntax(tokens.eof_span(), format!("expected {expected}, found eof")) + } } } @@ -1615,7 +1631,7 @@ enum Attribute<'a> { } impl<'a> Attribute<'a> { - fn parse_list(tokens: &mut Tokenizer<'a>) -> Result>> { + fn parse_list(tokens: &mut Tokenizer<'a>) -> ParseResult>> { let mut ret = Vec::new(); while tokens.eat(Token::At)? { let id = parse_id(tokens)?; @@ -1654,7 +1670,10 @@ impl<'a> Attribute<'a> { } } other => { - bail!(Error::new(id.span, format!("unknown attribute `{other}`"),)) + return Err(ParseError::new_syntax( + id.span, + format!("unknown attribute `{other}`"), + )); } }; ret.push(attr); @@ -1671,10 +1690,10 @@ impl<'a> Attribute<'a> { } } -fn eat_id(tokens: &mut Tokenizer<'_>, expected: &str) -> Result { +fn eat_id(tokens: &mut Tokenizer<'_>, expected: &str) -> ParseResult { let id = parse_id(tokens)?; if id.name != expected { - bail!(Error::new( + return Err(ParseError::new_syntax( id.span, format!("expected `{expected}`, found `{}`", id.name), )); @@ -1708,7 +1727,7 @@ impl SourceMap { /// Reads the file `path` on the filesystem and appends its contents to this /// [`SourceMap`]. #[cfg(feature = "std")] - pub fn push_file(&mut self, path: &Path) -> Result<()> { + pub fn push_file(&mut self, path: &Path) -> anyhow::Result<()> { let contents = std::fs::read_to_string(path) .with_context(|| format!("failed to read file {path:?}"))?; self.push(path, contents); @@ -1768,90 +1787,80 @@ impl SourceMap { /// Parses the files added to this source map into a /// [`UnresolvedPackageGroup`]. - pub fn parse(self) -> Result { + /// + /// On failure returns `Err((self, e))` so the caller can use the source + /// map for error formatting if needed. + pub fn parse(self) -> Result { + match self.parse_inner() { + Ok((main, nested)) => Ok(UnresolvedPackageGroup { + main, + nested, + source_map: self, + }), + Err(e) => Err((self, e)), + } + } + + fn parse_inner(&self) -> ParseResult<(UnresolvedPackage, Vec)> { let mut nested = Vec::new(); - let main = self.rewrite_error(|| { - let mut resolver = Resolver::default(); - let mut srcs = self.sources.iter().collect::>(); - srcs.sort_by_key(|src| &src.path); - - // Parse each source file individually. A tokenizer is created here - // form settings and then `PackageFile` is used to parse the whole - // stream of tokens. - for src in srcs { - let mut tokens = Tokenizer::new( - // chop off the forcibly appended `\n` character when - // passing through the source to get tokenized. - &src.contents[..src.contents.len() - 1], - src.offset, - ) - .with_context(|| format!("failed to tokenize path: {}", src.path))?; - let mut file = PackageFile::parse(&mut tokens)?; - - // Filter out any nested packages and resolve them separately. - // Nested packages have only a single "file" so only one item - // is pushed into a `Resolver`. Note that a nested `Resolver` - // is used here, not the outer one. - // - // Note that filtering out `Package` items is required due to - // how the implementation of disallowing nested packages in - // nested packages currently works. - for item in mem::take(&mut file.decl_list.items) { - match item { - AstItem::Package(nested_pkg) => { - let mut resolve = Resolver::default(); - resolve.push(nested_pkg).with_context(|| { - format!("failed to handle nested package in: {}", src.path) - })?; - - nested.push(resolve.resolve()?); - } - other => file.decl_list.items.push(other), + let mut resolver = Resolver::default(); + let mut srcs = self.sources.iter().collect::>(); + srcs.sort_by_key(|src| &src.path); + + // Parse each source file individually. A tokenizer is created here + // from settings and then `PackageFile` is used to parse the whole + // stream of tokens. + for src in srcs { + let mut tokens = Tokenizer::new( + // chop off the forcibly appended `\n` character when + // passing through the source to get tokenized. + &src.contents[..src.contents.len() - 1], + src.offset, + )?; + let mut file = PackageFile::parse(&mut tokens)?; + + // Filter out any nested packages and resolve them separately. + // Nested packages have only a single "file" so only one item + // is pushed into a `Resolver`. Note that a nested `Resolver` + // is used here, not the outer one. + // + // Note that filtering out `Package` items is required due to + // how the implementation of disallowing nested packages in + // nested packages currently works. + for item in mem::take(&mut file.decl_list.items) { + match item { + AstItem::Package(nested_pkg) => { + let mut resolve = Resolver::default(); + resolve.push(nested_pkg)?; + nested.push(resolve.resolve()?); } + other => file.decl_list.items.push(other), } - - // With nested packages handled push this file into the - // resolver. - resolver - .push(file) - .with_context(|| format!("failed to start resolving path: {}", src.path))?; } - Ok(resolver.resolve()?) - })?; - Ok(UnresolvedPackageGroup { - main, - nested, - source_map: self, - }) + + // With nested packages handled push this file into the resolver. + resolver.push(file)?; + } + + Ok((resolver.resolve()?, nested)) } - pub(crate) fn rewrite_error(&self, f: F) -> Result + /// Runs `f` and, on error, attempts to add source highlighting to resolver + /// error types that still use `anyhow`. Only needed until the resolver is + /// migrated to structured errors. + pub(crate) fn rewrite_error(&self, f: F) -> anyhow::Result where - F: FnOnce() -> Result, + F: FnOnce() -> anyhow::Result, { let mut err = match f() { Ok(t) => return Ok(t), Err(e) => e, }; - if let Some(parse) = err.downcast_mut::() { - parse.highlight(self); - return Err(err); + if let Some(e) = err.downcast_mut::() { + e.highlight(self); + } else if let Some(e) = err.downcast_mut::() { + e.highlight(self); } - if let Some(notfound) = err.downcast_mut::() { - notfound.highlight(self); - return Err(err); - } - - if let Some(lex) = err.downcast_ref::() { - let pos = lex.position(); - let msg = self.highlight_err(pos, None, lex); - bail!("{msg}") - } - - if let Some(sort) = err.downcast_mut::() { - sort.highlight(self); - } - Err(err) } @@ -1960,11 +1969,11 @@ pub enum ParsedUsePath { Package(crate::PackageName, String), } -pub fn parse_use_path(s: &str) -> Result { +pub fn parse_use_path(s: &str) -> anyhow::Result { let mut tokens = Tokenizer::new(s, 0)?; let path = UsePath::parse(&mut tokens)?; if tokens.next()?.is_some() { - bail!("trailing tokens in path specifier"); + anyhow::bail!("trailing tokens in path specifier"); } Ok(match path { UsePath::Id(id) => ParsedUsePath::Name(id.name.to_string()), diff --git a/crates/wit-parser/src/ast/error.rs b/crates/wit-parser/src/ast/error.rs new file mode 100644 index 0000000000..55a3ffa959 --- /dev/null +++ b/crates/wit-parser/src/ast/error.rs @@ -0,0 +1,112 @@ +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use core::fmt; + +use crate::{SourceMap, Span, ast::lex}; + +pub type ParseResult = Result; + +#[non_exhaustive] +#[derive(Debug, PartialEq, Eq)] +pub enum ParseErrorKind { + /// Lexer error (invalid character, unterminated comment, etc.) + Lex(lex::Error), + /// Syntactic or semantic error within a single package (duplicate name, + /// invalid attribute, etc.) + Syntax { span: Span, message: String }, + /// A type/interface/world references a name that does not exist within + /// the same package. + ItemNotFound { + span: Span, + name: String, + kind: String, + hint: Option, + }, + /// A type/interface/world depends on itself. + TypeCycle { + span: Span, + name: String, + kind: String, + }, +} + +impl ParseErrorKind { + pub fn span(&self) -> Span { + match self { + ParseErrorKind::Lex(e) => Span::new(e.position(), e.position() + 1), + ParseErrorKind::Syntax { span, .. } + | ParseErrorKind::ItemNotFound { span, .. } + | ParseErrorKind::TypeCycle { span, .. } => *span, + } + } +} + +impl fmt::Display for ParseErrorKind { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + ParseErrorKind::Lex(e) => fmt::Display::fmt(e, f), + ParseErrorKind::Syntax { message, .. } => message.fmt(f), + ParseErrorKind::ItemNotFound { + kind, name, hint, .. + } => { + write!(f, "{kind} `{name}` does not exist")?; + if let Some(hint) = hint { + write!(f, "\n{hint}")?; + } + Ok(()) + } + ParseErrorKind::TypeCycle { kind, name, .. } => { + write!(f, "{kind} `{name}` depends on itself") + } + } + } +} + +#[derive(Debug, PartialEq, Eq)] +pub struct ParseError(Box); + +impl ParseError { + pub fn new_syntax(span: Span, message: impl Into) -> Self { + ParseErrorKind::Syntax { + span, + message: message.into(), + } + .into() + } + + pub fn kind(&self) -> &ParseErrorKind { + &self.0 + } + + pub fn kind_mut(&mut self) -> &mut ParseErrorKind { + &mut self.0 + } + + /// Format this error with source context (file:line:col + snippet) + pub fn highlight(&self, source_map: &SourceMap) -> String { + let e = self.kind(); + source_map + .highlight_span(e.span(), e) + .unwrap_or_else(|| e.to_string()) + } +} + +impl fmt::Display for ParseError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Display::fmt(self.kind(), f) + } +} + +impl core::error::Error for ParseError {} + +impl From for ParseError { + fn from(kind: ParseErrorKind) -> Self { + ParseError(Box::new(kind)) + } +} + +impl From for ParseError { + fn from(e: lex::Error) -> Self { + ParseErrorKind::Lex(e).into() + } +} diff --git a/crates/wit-parser/src/ast/resolve.rs b/crates/wit-parser/src/ast/resolve.rs index e77ac0f260..7c7f617e37 100644 --- a/crates/wit-parser/src/ast/resolve.rs +++ b/crates/wit-parser/src/ast/resolve.rs @@ -1,10 +1,11 @@ use super::{ParamList, WorldOrInterface}; +use crate::alloc::borrow::ToOwned; +use crate::ast::error::{ParseError, ParseErrorKind}; use crate::ast::toposort::toposort; use crate::*; use alloc::string::{String, ToString}; use alloc::vec::Vec; use alloc::{format, vec}; -use anyhow::bail; use core::mem; #[derive(Default)] @@ -105,7 +106,7 @@ enum TypeOrItem { } impl<'a> Resolver<'a> { - pub(super) fn push(&mut self, file: ast::PackageFile<'a>) -> Result<()> { + pub(super) fn push(&mut self, file: ast::PackageFile<'a>) -> ParseResult<()> { // As each WIT file is pushed into this resolver keep track of the // current package name assigned. Only one file needs to mention it, but // if multiple mention it then they must all match. @@ -113,13 +114,13 @@ impl<'a> Resolver<'a> { let cur_name = cur.package_name(); if let Some((prev, _)) = &self.package_name { if cur_name != *prev { - bail!(Error::new( + return Err(ParseError::new_syntax( cur.span, format!( "package identifier `{cur_name}` does not match \ - previous package name of `{prev}`" + previous package name of `{prev}`" ), - )) + )); } } self.package_name = Some((cur_name, cur.span)); @@ -128,10 +129,10 @@ impl<'a> Resolver<'a> { let docs = self.docs(&cur.docs); if docs.contents.is_some() { if self.package_docs.contents.is_some() { - bail!(Error::new( + return Err(ParseError::new_syntax( cur.docs.span, - "found doc comments on multiple 'package' items" - )) + "found doc comments on multiple 'package' items".to_owned(), + )); } self.package_docs = docs; } @@ -145,22 +146,25 @@ impl<'a> Resolver<'a> { ast::AstItem::Package(pkg) => pkg.package_id.as_ref().unwrap().span, _ => continue, }; - bail!(Error::new( + return Err(ParseError::new_syntax( span, - "nested packages must be placed at the top-level" - )) + "nested packages must be placed at the top-level".to_owned(), + )); } self.decl_lists.push(file.decl_list); Ok(()) } - pub(crate) fn resolve(&mut self) -> Result { + pub(crate) fn resolve(&mut self) -> ParseResult { // At least one of the WIT files must have a `package` annotation. let (name, package_name_span) = match &self.package_name { Some(name) => name.clone(), None => { - bail!("no `package` header was found in any WIT file for this package") + return Err(ParseError::new_syntax( + Span::default(), + "no `package` header was found in any WIT file for this package".to_owned(), + )); } }; @@ -336,7 +340,7 @@ impl<'a> Resolver<'a> { fn populate_ast_items( &mut self, decl_lists: &[ast::DeclList<'a>], - ) -> Result<(Vec, Vec)> { + ) -> ParseResult<(Vec, Vec)> { let mut package_items = IndexMap::default(); // Validate that all worlds and interfaces have unique names within this @@ -350,10 +354,10 @@ impl<'a> Resolver<'a> { match item { ast::AstItem::Interface(i) => { if package_items.insert(i.name.name, i.name.span).is_some() { - bail!(Error::new( + return Err(ParseError::new_syntax( i.name.span, format!("duplicate item named `{}`", i.name.name), - )) + )); } let prev = decl_list_ns.insert(i.name.name, ()); assert!(prev.is_none()); @@ -364,10 +368,10 @@ impl<'a> Resolver<'a> { } ast::AstItem::World(w) => { if package_items.insert(w.name.name, w.name.span).is_some() { - bail!(Error::new( + return Err(ParseError::new_syntax( w.name.span, format!("duplicate item named `{}`", w.name.name), - )) + )); } let prev = decl_list_ns.insert(w.name.name, ()); assert!(prev.is_none()); @@ -415,7 +419,7 @@ impl<'a> Resolver<'a> { ast::AstItem::Package(_) => unreachable!(), }; if decl_list_ns.insert(name.name, (name.span, src)).is_some() { - bail!(Error::new( + return Err(ParseError::new_syntax( name.span, format!("duplicate name `{}` in this file", name.name), )); @@ -446,13 +450,12 @@ impl<'a> Resolver<'a> { order[iface.name].push(used_name.clone()); } None => { - bail!(Error::new( - used_name.span, - format!( - "interface or world `{name}` not found in package", - name = used_name.name - ), - )) + return Err(ParseError::from(ParseErrorKind::ItemNotFound { + span: used_name.span, + name: used_name.name.to_string(), + kind: "interface or world".to_string(), + hint: None, + })); } }, } @@ -494,21 +497,20 @@ impl<'a> Resolver<'a> { let (name, ast_item) = match item { ast::AstItem::Use(u) => { if !u.attributes.is_empty() { - bail!(Error::new( + return Err(ParseError::new_syntax( u.span, format!("attributes not allowed on top-level use"), - )) + )); } let name = u.as_.as_ref().unwrap_or(u.item.name()); let item = match &u.item { ast::UsePath::Id(name) => *ids.get(name.name).ok_or_else(|| { - Error::new( - name.span, - format!( - "interface or world `{name}` does not exist", - name = name.name - ), - ) + ParseError::from(ParseErrorKind::ItemNotFound { + span: name.span, + name: name.name.to_string(), + kind: "interface or world".to_owned(), + hint: None, + }) })?, ast::UsePath::Package { id, name } => { self.foreign_deps[&id.package_name()][name.name].0 @@ -549,7 +551,7 @@ impl<'a> Resolver<'a> { /// This is done after all interfaces are generated so `self.resolve_path` /// can be used to determine if what's being imported from is a foreign /// interface or not. - fn populate_foreign_types(&mut self, decl_lists: &[ast::DeclList<'a>]) -> Result<()> { + fn populate_foreign_types(&mut self, decl_lists: &[ast::DeclList<'a>]) -> ParseResult<()> { for (i, decl_list) in decl_lists.iter().enumerate() { self.cur_ast_index = i; decl_list.for_each_path(&mut |_, attrs, path, names, _| { @@ -593,7 +595,7 @@ impl<'a> Resolver<'a> { Ok(()) } - fn resolve_world(&mut self, world_id: WorldId, world: &ast::World<'a>) -> Result { + fn resolve_world(&mut self, world_id: WorldId, world: &ast::World<'a>) -> ParseResult { let docs = self.docs(&world.docs); self.worlds[world_id].docs = docs; let stability = self.stability(&world.attributes)?; @@ -627,10 +629,10 @@ impl<'a> Resolver<'a> { WorldItem::Type { id, span: *span }, ); if prev.is_some() { - bail!(Error::new( + return Err(ParseError::new_syntax( *span, format!("import `{name}` conflicts with prior import of same name"), - )) + )); } } TypeOrItem::Item(_) => unreachable!(), @@ -704,10 +706,10 @@ impl<'a> Resolver<'a> { }; if let WorldItem::Interface { id, .. } = world_item { if !interfaces.insert(id) { - bail!(Error::new( + return Err(ParseError::new_syntax( kind.span(), format!("interface cannot be {desc}ed more than once"), - )) + )); } } let dst = if desc == "import" { @@ -726,10 +728,10 @@ impl<'a> Resolver<'a> { WorldKey::Name(name) => name, WorldKey::Interface(..) => unreachable!(), }; - bail!(Error::new( + return Err(ParseError::new_syntax( kind.span(), format!("{desc} `{name}` conflicts with prior {prev} of same name",), - )) + )); } } self.type_lookup.clear(); @@ -742,7 +744,7 @@ impl<'a> Resolver<'a> { docs: &ast::Docs<'a>, attrs: &[ast::Attribute<'a>], kind: &ast::ExternKind<'a>, - ) -> Result { + ) -> ParseResult { match kind { ast::ExternKind::Interface(name, items) => { let prev = mem::take(&mut self.type_lookup); @@ -790,7 +792,7 @@ impl<'a> Resolver<'a> { fields: &[ast::InterfaceItem<'a>], docs: &ast::Docs<'a>, attrs: &[ast::Attribute<'a>], - ) -> Result<()> { + ) -> ParseResult<()> { let docs = self.docs(docs); self.interfaces[interface_id].docs = docs; let stability = self.stability(attrs)?; @@ -866,7 +868,7 @@ impl<'a> Resolver<'a> { &mut self, owner: TypeOwner, fields: impl Iterator> + Clone, - ) -> Result<()> + ) -> ParseResult<()> where 'a: 'b, { @@ -893,10 +895,10 @@ impl<'a> Resolver<'a> { TypeItem::Def(t) => { let prev = type_defs.insert(t.name.name, Some(t)); if prev.is_some() { - bail!(Error::new( + return Err(ParseError::new_syntax( t.name.span, format!("name `{}` is defined more than once", t.name.name), - )) + )); } let mut deps = Vec::new(); collect_deps(&t.ty, &mut deps); @@ -932,28 +934,25 @@ impl<'a> Resolver<'a> { } return Ok(()); - fn attach_old_float_type_context(err: ast::toposort::Error) -> anyhow::Error { - let name = match &err { - ast::toposort::Error::NonexistentDep { name, .. } => name, - _ => return err.into(), - }; - let new = match name.as_str() { - "float32" => "f32", - "float64" => "f64", - _ => return err.into(), - }; - - let context = format!( - "the `{name}` type has been renamed to `{new}` and is \ - no longer accepted, but the `WIT_REQUIRE_F32_F64=0` \ - environment variable can be used to temporarily \ - disable this error" - ); - anyhow::Error::from(err).context(context) + fn attach_old_float_type_context(mut err: ParseError) -> ParseError { + if let ParseErrorKind::ItemNotFound { name, hint, .. } = err.kind_mut() { + let new = match name.as_str() { + "float32" => "f32", + "float64" => "f64", + _ => return err, + }; + *hint = Some(format!( + "the `{name}` type has been renamed to `{new}` and is \ + no longer accepted, but the `WIT_REQUIRE_F32_F64=0` \ + environment variable can be used to temporarily \ + disable this error" + )); + } + err } } - fn resolve_use(&mut self, owner: TypeOwner, u: &ast::Use<'a>) -> Result<()> { + fn resolve_use(&mut self, owner: TypeOwner, u: &ast::Use<'a>) -> ParseResult<()> { let (item, name, span) = self.resolve_ast_item_path(&u.from)?; let use_from = self.extract_iface_from_item(&item, &name, span)?; let stability = self.stability(&u.attributes)?; @@ -963,15 +962,19 @@ impl<'a> Resolver<'a> { let id = match lookup.get(name.name.name) { Some((TypeOrItem::Type(id), _)) => *id, Some((TypeOrItem::Item(s), _)) => { - bail!(Error::new( + return Err(ParseError::new_syntax( name.name.span, format!("cannot import {s} `{}`", name.name.name), - )) + )); + } + None => { + return Err(ParseError::from(ParseErrorKind::ItemNotFound { + span: name.name.span, + name: name.name.name.to_string(), + kind: "name".to_string(), + hint: None, + })); } - None => bail!(Error::new( - name.name.span, - format!("name `{}` is not defined", name.name.name), - )), }; let span = name.name.span; let name = name.as_.as_ref().unwrap_or(&name.name); @@ -989,7 +992,7 @@ impl<'a> Resolver<'a> { } /// For each name in the `include`, resolve the path of the include, add it to the self.includes - fn resolve_include(&mut self, world_id: WorldId, i: &ast::Include<'a>) -> Result<()> { + fn resolve_include(&mut self, world_id: WorldId, i: &ast::Include<'a>) -> ParseResult<()> { let stability = self.stability(&i.attributes)?; let (item, name, span) = self.resolve_ast_item_path(&i.from)?; let include_from = self.extract_world_from_item(&item, &name, span)?; @@ -1013,7 +1016,7 @@ impl<'a> Resolver<'a> { &mut self, func: &ast::ResourceFunc<'_>, resource: &ast::Id<'_>, - ) -> Result { + ) -> ParseResult { let resource_id = match self.type_lookup.get(resource.name) { Some((TypeOrItem::Type(id), _)) => *id, _ => panic!("type lookup for resource failed"), @@ -1062,7 +1065,7 @@ impl<'a> Resolver<'a> { name_span: Span, func: &ast::Func, kind: FunctionKind, - ) -> Result { + ) -> ParseResult { let docs = self.docs(docs); let stability = self.stability(attrs)?; let params = self.resolve_params(&func.params, &kind, func.span)?; @@ -1078,7 +1081,10 @@ impl<'a> Resolver<'a> { }) } - fn resolve_ast_item_path(&self, path: &ast::UsePath<'a>) -> Result<(AstItem, String, Span)> { + fn resolve_ast_item_path( + &self, + path: &ast::UsePath<'a>, + ) -> ParseResult<(AstItem, String, Span)> { match path { ast::UsePath::Id(id) => { let item = self.ast_items[self.cur_ast_index] @@ -1087,10 +1093,12 @@ impl<'a> Resolver<'a> { match item { Some(item) => Ok((*item, id.name.into(), id.span)), None => { - bail!(Error::new( - id.span, - format!("interface or world `{}` does not exist", id.name), - )) + return Err(ParseError::from(ParseErrorKind::ItemNotFound { + span: id.span, + name: id.name.to_string(), + kind: "interface or world".to_owned(), + hint: None, + })); } } } @@ -1107,37 +1115,42 @@ impl<'a> Resolver<'a> { item: &AstItem, name: &str, span: Span, - ) -> Result { + ) -> ParseResult { match item { AstItem::Interface(id) => Ok(*id), AstItem::World(_) => { - bail!(Error::new( + return Err(ParseError::new_syntax( span, format!("name `{name}` is defined as a world, not an interface"), - )) + )); } } } - fn extract_world_from_item(&self, item: &AstItem, name: &str, span: Span) -> Result { + fn extract_world_from_item( + &self, + item: &AstItem, + name: &str, + span: Span, + ) -> ParseResult { match item { AstItem::World(id) => Ok(*id), AstItem::Interface(_) => { - bail!(Error::new( + return Err(ParseError::new_syntax( span, format!("name `{name}` is defined as an interface, not a world"), - )) + )); } } } - fn define_interface_name(&mut self, name: &ast::Id<'a>, item: TypeOrItem) -> Result<()> { + fn define_interface_name(&mut self, name: &ast::Id<'a>, item: TypeOrItem) -> ParseResult<()> { let prev = self.type_lookup.insert(name.name, (item, name.span)); if prev.is_some() { - bail!(Error::new( + return Err(ParseError::new_syntax( name.span, format!("name `{}` is defined more than once", name.name), - )) + )); } else { Ok(()) } @@ -1147,7 +1160,7 @@ impl<'a> Resolver<'a> { &mut self, ty: &ast::Type<'_>, stability: &Stability, - ) -> Result { + ) -> ParseResult { Ok(match ty { ast::Type::Bool(_) => TypeDefKind::Type(Type::Bool), ast::Type::U8(_) => TypeDefKind::Type(Type::U8), @@ -1188,10 +1201,7 @@ impl<'a> Resolver<'a> { | Type::Char | Type::String => {} _ => { - bail!(Error::new( - map.span, - "invalid map key type: map keys must be bool, u8, u16, u32, u64, s8, s16, s32, s64, char, or string", - )) + return Err(ParseError::new_syntax(map.span, "invalid map key type: map keys must be bool, u8, u16, u32, u64, s8, s16, s32, s64, char, or string".to_owned())); } } @@ -1216,16 +1226,19 @@ impl<'a> Resolver<'a> { match func { ast::ResourceFunc::Method(f) | ast::ResourceFunc::Static(f) => { if !names.insert(&f.name.name) { - bail!(Error::new( + return Err(ParseError::new_syntax( f.name.span, format!("duplicate function name `{}`", f.name.name), - )) + )); } } ast::ResourceFunc::Constructor(f) => { ctors += 1; if ctors > 1 { - bail!(Error::new(f.name.span, "duplicate constructors")) + return Err(ParseError::new_syntax( + f.name.span, + "duplicate constructors".to_owned(), + )); } } } @@ -1245,7 +1258,7 @@ impl<'a> Resolver<'a> { span: field.name.span, }) }) - .collect::>>()?; + .collect::>>()?; TypeDefKind::Record(Record { fields }) } ast::Type::Flags(flags) => { @@ -1265,12 +1278,15 @@ impl<'a> Resolver<'a> { .types .iter() .map(|ty| self.resolve_type(ty, stability)) - .collect::>>()?; + .collect::>>()?; TypeDefKind::Tuple(Tuple { types }) } ast::Type::Variant(variant) => { if variant.cases.is_empty() { - bail!(Error::new(variant.span, "empty variant")) + return Err(ParseError::new_syntax( + variant.span, + "empty variant".to_owned(), + )); } let cases = variant .cases @@ -1283,12 +1299,12 @@ impl<'a> Resolver<'a> { span: case.name.span, }) }) - .collect::>>()?; + .collect::>>()?; TypeDefKind::Variant(Variant { cases }) } ast::Type::Enum(e) => { if e.cases.is_empty() { - bail!(Error::new(e.span, "empty enum")) + return Err(ParseError::new_syntax(e.span, "empty enum".to_owned())); } let cases = e .cases @@ -1300,7 +1316,7 @@ impl<'a> Resolver<'a> { span: case.name.span, }) }) - .collect::>>()?; + .collect::>>()?; TypeDefKind::Enum(Enum { cases }) } ast::Type::Option(ty) => TypeDefKind::Option(self.resolve_type(&ty.ty, stability)?), @@ -1317,21 +1333,27 @@ impl<'a> Resolver<'a> { }) } - fn resolve_type_name(&mut self, name: &ast::Id<'_>) -> Result { + fn resolve_type_name(&mut self, name: &ast::Id<'_>) -> ParseResult { match self.type_lookup.get(name.name) { Some((TypeOrItem::Type(id), _)) => Ok(*id), - Some((TypeOrItem::Item(s), _)) => bail!(Error::new( - name.span, - format!("cannot use {s} `{name}` as a type", name = name.name), - )), - None => bail!(Error::new( - name.span, - format!("name `{name}` is not defined", name = name.name), - )), + Some((TypeOrItem::Item(s), _)) => { + return Err(ParseError::new_syntax( + name.span, + format!("cannot use {s} `{name}` as a type", name = name.name), + )); + } + None => { + return Err(ParseError::from(ParseErrorKind::ItemNotFound { + span: name.span, + name: name.name.to_string(), + kind: "name".to_owned(), + hint: None, + })); + } } } - fn validate_resource(&mut self, name: &ast::Id<'_>) -> Result { + fn validate_resource(&mut self, name: &ast::Id<'_>) -> ParseResult { let id = self.resolve_type_name(name)?; let mut cur = id; loop { @@ -1342,10 +1364,12 @@ impl<'a> Resolver<'a> { self.required_resource_types.push((cur, name.span)); break Ok(id); } - _ => bail!(Error::new( - name.span, - format!("type `{}` used in a handle must be a resource", name.name), - )), + _ => { + return Err(ParseError::new_syntax( + name.span, + format!("type `{}` used in a handle must be a resource", name.name), + )); + } } } } @@ -1419,7 +1443,7 @@ impl<'a> Resolver<'a> { } } - fn resolve_type(&mut self, ty: &super::Type<'_>, stability: &Stability) -> Result { + fn resolve_type(&mut self, ty: &super::Type<'_>, stability: &Stability) -> ParseResult { // Resources must be declared at the top level to have their methods // processed appropriately, but resources also shouldn't show up // recursively so assert that's not happening here. @@ -1443,7 +1467,7 @@ impl<'a> Resolver<'a> { &mut self, ty: Option<&super::Type<'_>>, stability: &Stability, - ) -> Result> { + ) -> ParseResult> { match ty { Some(ty) => Ok(Some(self.resolve_type(ty, stability)?)), None => Ok(None), @@ -1549,7 +1573,7 @@ impl<'a> Resolver<'a> { Docs { contents } } - fn stability(&mut self, attrs: &[ast::Attribute<'_>]) -> Result { + fn stability(&mut self, attrs: &[ast::Attribute<'_>]) -> ParseResult { match attrs { [] => Ok(Stability::Unknown), @@ -1593,16 +1617,16 @@ impl<'a> Resolver<'a> { deprecated: Some(version.clone()), }), [ast::Attribute::Deprecated { span, .. }] => { - bail!(Error::new( + return Err(ParseError::new_syntax( *span, - "must pair @deprecated with either @since or @unstable", - )) + "must pair @deprecated with either @since or @unstable".to_owned(), + )); } [_, b, ..] => { - bail!(Error::new( + return Err(ParseError::new_syntax( b.span(), - "unsupported combination of attributes", - )) + "unsupported combination of attributes".to_owned(), + )); } } } @@ -1612,7 +1636,7 @@ impl<'a> Resolver<'a> { params: &ParamList<'_>, kind: &FunctionKind, span: Span, - ) -> Result> { + ) -> ParseResult> { let mut ret = Vec::new(); match *kind { // These kinds of methods don't have any adjustments to the @@ -1645,10 +1669,10 @@ impl<'a> Resolver<'a> { } for (name, ty) in params { if ret.iter().any(|p| p.name == name.name) { - bail!(Error::new( + return Err(ParseError::new_syntax( name.span, format!("param `{}` is defined more than once", name.name), - )) + )); } ret.push(Param { name: name.name.to_string(), @@ -1664,7 +1688,7 @@ impl<'a> Resolver<'a> { result: &Option>, kind: &FunctionKind, _span: Span, - ) -> Result> { + ) -> ParseResult> { match *kind { // These kinds of methods don't have any adjustments to the return // values, so plumb them through as-is. @@ -1696,7 +1720,7 @@ impl<'a> Resolver<'a> { &mut self, resource_id: TypeId, result_ast: &ast::Type<'_>, - ) -> Result { + ) -> ParseResult { let result = self.resolve_type(result_ast, &Stability::Unknown)?; let ok_type = match result { Type::Id(id) => match &self.types[id].kind { @@ -1706,9 +1730,9 @@ impl<'a> Resolver<'a> { _ => None, }; let Some(ok_type) = ok_type else { - bail!(Error::new( + return Err(ParseError::new_syntax( result_ast.span(), - "if a constructor return type is declared it must be a `result`", + "if a constructor return type is declared it must be a `result`".to_owned(), )); }; match ok_type { @@ -1720,9 +1744,9 @@ impl<'a> Resolver<'a> { } else { result_ast.span() }; - bail!(Error::new( + return Err(ParseError::new_syntax( ok_span, - "the `ok` type must be the resource being constructed", + "the `ok` type must be the resource being constructed".to_owned(), )); } } diff --git a/crates/wit-parser/src/ast/toposort.rs b/crates/wit-parser/src/ast/toposort.rs index b54b3f647b..9122ff8711 100644 --- a/crates/wit-parser/src/ast/toposort.rs +++ b/crates/wit-parser/src/ast/toposort.rs @@ -1,12 +1,10 @@ -use crate::IndexMap; -use crate::ast::{Id, Span}; +use super::error::ParseError; +use crate::ast::Id; +use crate::{IndexMap, ParseErrorKind, ParseResult}; use alloc::collections::BinaryHeap; -use alloc::format; -use alloc::string::{String, ToString}; +use alloc::string::ToString; use alloc::vec; use alloc::vec::Vec; -use anyhow::Result; -use core::fmt; use core::mem; #[derive(Default, Clone)] @@ -46,21 +44,21 @@ struct State { pub fn toposort<'a>( kind: &str, deps: &IndexMap<&'a str, Vec>>, -) -> Result, Error> { +) -> ParseResult> { // Initialize a `State` per-node with the number of outbound edges and // additionally filling out the `reverse_deps` array. let mut states = vec![State::default(); deps.len()]; for (i, (_, edges)) in deps.iter().enumerate() { states[i].outbound_remaining = edges.len(); for edge in edges { - let (j, _, _) = deps - .get_full(edge.name) - .ok_or_else(|| Error::NonexistentDep { + let (j, _, _) = deps.get_full(edge.name).ok_or_else(|| { + ParseError::from(ParseErrorKind::ItemNotFound { span: edge.span, name: edge.name.to_string(), kind: kind.to_string(), - highlighted: None, - })?; + hint: None, + }) + })?; states[j].reverse_deps.push(i); } } @@ -116,78 +114,18 @@ pub fn toposort<'a>( if states[j].outbound_remaining == 0 { continue; } - return Err(Error::Cycle { + return Err(ParseErrorKind::TypeCycle { span: dep.span, name: dep.name.to_string(), kind: kind.to_string(), - highlighted: None, - }); - } - } - - unreachable!() -} - -#[derive(Debug)] -pub enum Error { - NonexistentDep { - span: Span, - name: String, - kind: String, - highlighted: Option, - }, - Cycle { - span: Span, - name: String, - kind: String, - highlighted: Option, - }, -} - -impl Error { - pub(crate) fn highlighted(&self) -> Option<&str> { - match self { - Error::NonexistentDep { highlighted, .. } | Error::Cycle { highlighted, .. } => { - highlighted.as_deref() } + .into()); } } - /// Highlights this error using the given source map, if the span is known. - pub(crate) fn highlight(&mut self, source_map: &crate::ast::SourceMap) { - if self.highlighted().is_some() { - return; - } - let span = match self { - Error::NonexistentDep { span, .. } | Error::Cycle { span, .. } => *span, - }; - let msg = source_map.highlight_span(span, &format!("{self}")); - match self { - Error::NonexistentDep { highlighted, .. } | Error::Cycle { highlighted, .. } => { - *highlighted = msg; - } - } - } -} - -impl fmt::Display for Error { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - if let Some(s) = self.highlighted() { - return f.write_str(s); - } - match self { - Error::NonexistentDep { kind, name, .. } => { - write!(f, "{kind} `{name}` does not exist") - } - Error::Cycle { kind, name, .. } => { - write!(f, "{kind} `{name}` depends on itself") - } - } - } + unreachable!() } -impl core::error::Error for Error {} - #[cfg(test)] mod tests { use super::*; @@ -207,8 +145,8 @@ mod tests { let mut nonexistent = IndexMap::default(); nonexistent.insert("a", vec![id("b")]); assert!(matches!( - toposort("", &nonexistent), - Err(Error::NonexistentDep { .. }) + toposort("", &nonexistent).unwrap_err().kind(), + ParseErrorKind::ItemNotFound { .. } )); let mut one = IndexMap::default(); @@ -230,13 +168,19 @@ mod tests { fn cycles() { let mut cycle = IndexMap::default(); cycle.insert("a", vec![id("a")]); - assert!(matches!(toposort("", &cycle), Err(Error::Cycle { .. }))); + assert!(matches!( + toposort("", &cycle).unwrap_err().kind(), + ParseErrorKind::TypeCycle { .. } + )); let mut cycle = IndexMap::default(); cycle.insert("a", vec![id("b")]); cycle.insert("b", vec![id("c")]); cycle.insert("c", vec![id("a")]); - assert!(matches!(toposort("", &cycle), Err(Error::Cycle { .. }))); + assert!(matches!( + toposort("", &cycle).unwrap_err().kind(), + ParseErrorKind::TypeCycle { .. } + )); } #[test] diff --git a/crates/wit-parser/src/lib.rs b/crates/wit-parser/src/lib.rs index 742d75159d..76461df98c 100644 --- a/crates/wit-parser/src/lib.rs +++ b/crates/wit-parser/src/lib.rs @@ -46,6 +46,7 @@ pub use metadata::PackageMetadata; pub mod abi; mod ast; pub use ast::SourceMap; +pub use ast::error::*; pub use ast::lex::Span; pub use ast::{ParsedUsePath, parse_use_path}; mod sizealign; @@ -390,45 +391,10 @@ impl UnresolvedPackageGroup { .as_ref() .to_str() .ok_or_else(|| anyhow::anyhow!("path is not valid utf-8: {:?}", path.as_ref()))?; - Self::parse_str(path, contents) - } - - /// Parses the given string as a wit document. - /// - /// The `path` argument is used for error reporting. The `contents` provided - /// are considered to be the contents of `path`. This function does not read - /// the filesystem. - pub fn parse_str(path: &str, contents: &str) -> Result { let mut map = SourceMap::default(); map.push_str(path, contents); map.parse() - } - - /// Parse a WIT package at the provided path. - /// - /// The path provided is inferred whether it's a file or a directory. A file - /// is parsed with [`UnresolvedPackageGroup::parse_file`] and a directory is - /// parsed with [`UnresolvedPackageGroup::parse_dir`]. - #[cfg(feature = "std")] - pub fn parse_path(path: impl AsRef) -> Result { - let path = path.as_ref(); - if path.is_dir() { - UnresolvedPackageGroup::parse_dir(path) - } else { - UnresolvedPackageGroup::parse_file(path) - } - } - - /// Parses a WIT package from the file provided. - /// - /// The return value represents all packages found in the WIT file which - /// might be either one or multiple depending on the syntax used. - #[cfg(feature = "std")] - pub fn parse_file(path: impl AsRef) -> Result { - let path = path.as_ref(); - let contents = std::fs::read_to_string(path) - .with_context(|| format!("failed to read file {path:?}"))?; - Self::parse(path, &contents) + .map_err(|(map, e)| anyhow::anyhow!("{}", e.highlight(&map))) } /// Parses a WIT package from the directory provided. @@ -464,6 +430,7 @@ impl UnresolvedPackageGroup { map.push_file(&path)?; } map.parse() + .map_err(|(map, e)| anyhow::anyhow!("{}", e.highlight(&map))) } } diff --git a/crates/wit-parser/src/resolve/mod.rs b/crates/wit-parser/src/resolve/mod.rs index 88bba9db4a..c7d302c4c7 100644 --- a/crates/wit-parser/src/resolve/mod.rs +++ b/crates/wit-parser/src/resolve/mod.rs @@ -391,14 +391,18 @@ package {name} is defined in two different locations:\n\ Ok(pkg_id) } - /// Convenience method for combining [`UnresolvedPackageGroup::parse_str`] and - /// [`Resolve::push_group`]. + /// Convenience method for combining [`SourceMap`] and [`Resolve::push_group`]. /// /// The `path` provided is used for error messages but otherwise is not /// read. This method does not touch the filesystem. The `contents` provided /// are the contents of a WIT package. pub fn push_source(&mut self, path: &str, contents: &str) -> Result { - self.push_group(UnresolvedPackageGroup::parse_str(path, contents)?) + let mut map = SourceMap::default(); + map.push_str(path, contents); + self.push_group( + map.parse() + .map_err(|(map, e)| anyhow::anyhow!("{}", e.highlight(&map)))?, + ) } /// Renders a span as a human-readable location string (e.g., "file.wit:10:5"). diff --git a/crates/wit-parser/tests/ui/parse-fail/bad-function.wit.result b/crates/wit-parser/tests/ui/parse-fail/bad-function.wit.result index a2c71f1785..430d2e9b6e 100644 --- a/crates/wit-parser/tests/ui/parse-fail/bad-function.wit.result +++ b/crates/wit-parser/tests/ui/parse-fail/bad-function.wit.result @@ -1,4 +1,4 @@ -name `nonexistent` is not defined +name `nonexistent` does not exist --> tests/ui/parse-fail/bad-function.wit:6:18 | 6 | x: func(param: nonexistent); diff --git a/crates/wit-parser/tests/ui/parse-fail/bad-function2.wit.result b/crates/wit-parser/tests/ui/parse-fail/bad-function2.wit.result index 5cd183197e..83e5c52a3a 100644 --- a/crates/wit-parser/tests/ui/parse-fail/bad-function2.wit.result +++ b/crates/wit-parser/tests/ui/parse-fail/bad-function2.wit.result @@ -1,4 +1,4 @@ -name `nonexistent` is not defined +name `nonexistent` does not exist --> tests/ui/parse-fail/bad-function2.wit:6:16 | 6 | x: func() -> nonexistent; diff --git a/crates/wit-parser/tests/ui/parse-fail/bad-include1.wit.result b/crates/wit-parser/tests/ui/parse-fail/bad-include1.wit.result index fa417906bd..97d72c9331 100644 --- a/crates/wit-parser/tests/ui/parse-fail/bad-include1.wit.result +++ b/crates/wit-parser/tests/ui/parse-fail/bad-include1.wit.result @@ -1,5 +1,5 @@ -interface or world `non-existence` not found in package +interface or world `non-existence` does not exist --> tests/ui/parse-fail/bad-include1.wit:4:11 | 4 | include non-existence; - | ^------------ \ No newline at end of file + | ^------------ diff --git a/crates/wit-parser/tests/ui/parse-fail/bad-pkg1.wit.result b/crates/wit-parser/tests/ui/parse-fail/bad-pkg1.wit.result index ddc7c7c307..61fdb95c24 100644 --- a/crates/wit-parser/tests/ui/parse-fail/bad-pkg1.wit.result +++ b/crates/wit-parser/tests/ui/parse-fail/bad-pkg1.wit.result @@ -1,4 +1,4 @@ -failed to resolve directory while parsing WIT for path [tests/ui/parse-fail/bad-pkg1]: failed to parse package: tests/ui/parse-fail/bad-pkg1: interface or world `nonexistent` not found in package +failed to resolve directory while parsing WIT for path [tests/ui/parse-fail/bad-pkg1]: failed to parse package: tests/ui/parse-fail/bad-pkg1: interface or world `nonexistent` does not exist --> tests/ui/parse-fail/bad-pkg1/root.wit:4:7 | 4 | use nonexistent.{}; diff --git a/crates/wit-parser/tests/ui/parse-fail/conflicting-package.wit.result b/crates/wit-parser/tests/ui/parse-fail/conflicting-package.wit.result index dc9dcee416..04eca323f1 100644 --- a/crates/wit-parser/tests/ui/parse-fail/conflicting-package.wit.result +++ b/crates/wit-parser/tests/ui/parse-fail/conflicting-package.wit.result @@ -1,4 +1,4 @@ -failed to resolve directory while parsing WIT for path [tests/ui/parse-fail/conflicting-package]: failed to parse package: tests/ui/parse-fail/conflicting-package: failed to start resolving path: tests/ui/parse-fail/conflicting-package/b.wit: package identifier `foo:b` does not match previous package name of `foo:a` +failed to resolve directory while parsing WIT for path [tests/ui/parse-fail/conflicting-package]: failed to parse package: tests/ui/parse-fail/conflicting-package: package identifier `foo:b` does not match previous package name of `foo:a` --> tests/ui/parse-fail/conflicting-package/b.wit:1:9 | 1 | package foo:b; diff --git a/crates/wit-parser/tests/ui/parse-fail/multiple-package-docs.wit.result b/crates/wit-parser/tests/ui/parse-fail/multiple-package-docs.wit.result index fd70371f39..928beef7c1 100644 --- a/crates/wit-parser/tests/ui/parse-fail/multiple-package-docs.wit.result +++ b/crates/wit-parser/tests/ui/parse-fail/multiple-package-docs.wit.result @@ -1,4 +1,4 @@ -failed to resolve directory while parsing WIT for path [tests/ui/parse-fail/multiple-package-docs]: failed to parse package: tests/ui/parse-fail/multiple-package-docs: failed to start resolving path: tests/ui/parse-fail/multiple-package-docs/b.wit: found doc comments on multiple 'package' items +failed to resolve directory while parsing WIT for path [tests/ui/parse-fail/multiple-package-docs]: failed to parse package: tests/ui/parse-fail/multiple-package-docs: found doc comments on multiple 'package' items --> tests/ui/parse-fail/multiple-package-docs/b.wit:1:1 | 1 | /// Multiple package docs, B diff --git a/crates/wit-parser/tests/ui/parse-fail/old-float-types.wit.result b/crates/wit-parser/tests/ui/parse-fail/old-float-types.wit.result index e3a34fd62e..e98c3d74d5 100644 --- a/crates/wit-parser/tests/ui/parse-fail/old-float-types.wit.result +++ b/crates/wit-parser/tests/ui/parse-fail/old-float-types.wit.result @@ -1,4 +1,5 @@ -the `float32` type has been renamed to `f32` and is no longer accepted, but the `WIT_REQUIRE_F32_F64=0` environment variable can be used to temporarily disable this error: type `float32` does not exist +type `float32` does not exist +the `float32` type has been renamed to `f32` and is no longer accepted, but the `WIT_REQUIRE_F32_F64=0` environment variable can be used to temporarily disable this error --> tests/ui/parse-fail/old-float-types.wit:4:13 | 4 | type t1 = float32; diff --git a/crates/wit-parser/tests/ui/parse-fail/unresolved-use1.wit.result b/crates/wit-parser/tests/ui/parse-fail/unresolved-use1.wit.result index d61301e4a1..d735d177d0 100644 --- a/crates/wit-parser/tests/ui/parse-fail/unresolved-use1.wit.result +++ b/crates/wit-parser/tests/ui/parse-fail/unresolved-use1.wit.result @@ -1,4 +1,4 @@ -interface or world `bar` not found in package +interface or world `bar` does not exist --> tests/ui/parse-fail/unresolved-use1.wit:6:7 | 6 | use bar.{x}; diff --git a/crates/wit-parser/tests/ui/parse-fail/unresolved-use10.wit.result b/crates/wit-parser/tests/ui/parse-fail/unresolved-use10.wit.result index 8d36b21d13..2336a708b8 100644 --- a/crates/wit-parser/tests/ui/parse-fail/unresolved-use10.wit.result +++ b/crates/wit-parser/tests/ui/parse-fail/unresolved-use10.wit.result @@ -1,4 +1,4 @@ -failed to resolve directory while parsing WIT for path [tests/ui/parse-fail/unresolved-use10]: failed to parse package: tests/ui/parse-fail/unresolved-use10: name `thing` is not defined +failed to resolve directory while parsing WIT for path [tests/ui/parse-fail/unresolved-use10]: failed to parse package: tests/ui/parse-fail/unresolved-use10: name `thing` does not exist --> tests/ui/parse-fail/unresolved-use10/bar.wit:4:12 | 4 | use foo.{thing}; diff --git a/crates/wit-parser/tests/ui/parse-fail/unresolved-use2.wit.result b/crates/wit-parser/tests/ui/parse-fail/unresolved-use2.wit.result index 51349921de..68812f702f 100644 --- a/crates/wit-parser/tests/ui/parse-fail/unresolved-use2.wit.result +++ b/crates/wit-parser/tests/ui/parse-fail/unresolved-use2.wit.result @@ -1,4 +1,4 @@ -name `x` is not defined +name `x` does not exist --> tests/ui/parse-fail/unresolved-use2.wit:6:12 | 6 | use bar.{x}; diff --git a/crates/wit-parser/tests/ui/parse-fail/unresolved-use7.wit.result b/crates/wit-parser/tests/ui/parse-fail/unresolved-use7.wit.result index 917215b7cf..1cd4c4c449 100644 --- a/crates/wit-parser/tests/ui/parse-fail/unresolved-use7.wit.result +++ b/crates/wit-parser/tests/ui/parse-fail/unresolved-use7.wit.result @@ -1,4 +1,4 @@ -name `x` is not defined +name `x` does not exist --> tests/ui/parse-fail/unresolved-use7.wit:6:12 | 6 | use bar.{x}; diff --git a/crates/wit-parser/tests/ui/parse-fail/very-nested-packages.wit.result b/crates/wit-parser/tests/ui/parse-fail/very-nested-packages.wit.result index 3109de9582..16fd6ae435 100644 --- a/crates/wit-parser/tests/ui/parse-fail/very-nested-packages.wit.result +++ b/crates/wit-parser/tests/ui/parse-fail/very-nested-packages.wit.result @@ -1,4 +1,4 @@ -failed to handle nested package in: tests/ui/parse-fail/very-nested-packages.wit: nested packages must be placed at the top-level +nested packages must be placed at the top-level --> tests/ui/parse-fail/very-nested-packages.wit:4:11 | 4 | package a:c2 { diff --git a/crates/wit-parser/tests/ui/parse-fail/world-top-level-func2.wit.result b/crates/wit-parser/tests/ui/parse-fail/world-top-level-func2.wit.result index 9ebb6629b6..df292707c0 100644 --- a/crates/wit-parser/tests/ui/parse-fail/world-top-level-func2.wit.result +++ b/crates/wit-parser/tests/ui/parse-fail/world-top-level-func2.wit.result @@ -1,4 +1,4 @@ -name `b` is not defined +name `b` does not exist --> tests/ui/parse-fail/world-top-level-func2.wit:3:23 | 3 | import foo: func(a: b);