diff --git a/crates/wit-parser/src/ast.rs b/crates/wit-parser/src/ast.rs index bf9da178b5..2d4d045fd5 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::UnresolvedPackageGroup; +use crate::ast::error::{ParseErrorKind, ParseErrors}; 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>) -> Result { let mut package_name_tokens_peek = tokens.clone(); let docs = parse_docs(&mut package_name_tokens_peek)?; @@ -62,13 +66,13 @@ impl<'a> PackageFile<'a> { tokens: &mut Tokenizer<'a>, docs: Docs<'a>, attributes: Vec>, - ) -> Result { + ) -> Result { let span = tokens.expect(Token::Package)?; if !attributes.is_empty() { - bail!(Error::new( - span, - format!("cannot place attributes on nested packages"), - )); + return Err(ParseErrors::from(ParseErrorKind::Syntax { + span: span, + message: format!("cannot place attributes on nested packages"), + })); } let package_id = PackageName::parse(tokens, docs)?; tokens.expect(Token::LeftBrace)?; @@ -121,7 +125,10 @@ 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, + ) -> Result, ParseErrors> { let mut items = Vec::new(); let mut docs = parse_docs(tokens)?; loop { @@ -151,8 +158,8 @@ impl<'a> DeclList<'a> { &'b UsePath<'a>, Option<&'b [UseName<'a>]>, WorldOrInterface, - ) -> Result<()>, - ) -> Result<()> { + ) -> Result<(), ParseErrors>, + ) -> Result<(), ParseErrors> { for item in self.items.iter() { match item { AstItem::World(world) => { @@ -259,7 +266,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>) -> Result { let attributes = Attribute::parse_list(tokens)?; match tokens.clone().next()? { Some((_span, Token::Interface)) => { @@ -285,7 +292,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>) -> Result { let namespace = parse_id(tokens)?; tokens.expect(Token::Colon)?; let name = parse_id(tokens)?; @@ -322,7 +329,10 @@ struct ToplevelUse<'a> { } impl<'a> ToplevelUse<'a> { - fn parse(tokens: &mut Tokenizer<'a>, attributes: Vec>) -> Result { + fn parse( + tokens: &mut Tokenizer<'a>, + attributes: Vec>, + ) -> Result { let span = tokens.expect(Token::Use)?; let item = UsePath::parse(tokens)?; let as_ = if tokens.eat(Token::As)? { @@ -352,7 +362,7 @@ impl<'a> World<'a> { tokens: &mut Tokenizer<'a>, docs: Docs<'a>, attributes: Vec>, - ) -> Result { + ) -> Result { tokens.expect(Token::World)?; let name = parse_id(tokens)?; let items = Self::parse_items(tokens)?; @@ -364,7 +374,7 @@ impl<'a> World<'a> { }) } - fn parse_items(tokens: &mut Tokenizer<'a>) -> Result>> { + fn parse_items(tokens: &mut Tokenizer<'a>) -> Result>, ParseErrors> { tokens.expect(Token::LeftBrace)?; let mut items = Vec::new(); loop { @@ -392,7 +402,7 @@ impl<'a> WorldItem<'a> { tokens: &mut Tokenizer<'a>, docs: Docs<'a>, attributes: Vec>, - ) -> Result> { + ) -> Result, ParseErrors> { match tokens.clone().next()? { Some((_span, Token::Import)) => { Import::parse(tokens, docs, attributes).map(WorldItem::Import) @@ -443,7 +453,7 @@ impl<'a> Import<'a> { tokens: &mut Tokenizer<'a>, docs: Docs<'a>, attributes: Vec>, - ) -> Result> { + ) -> Result, ParseErrors> { tokens.expect(Token::Import)?; let kind = ExternKind::parse(tokens)?; Ok(Import { @@ -465,7 +475,7 @@ impl<'a> Export<'a> { tokens: &mut Tokenizer<'a>, docs: Docs<'a>, attributes: Vec>, - ) -> Result> { + ) -> Result, ParseErrors> { tokens.expect(Token::Export)?; let kind = ExternKind::parse(tokens)?; Ok(Export { @@ -483,7 +493,7 @@ enum ExternKind<'a> { } impl<'a> ExternKind<'a> { - fn parse(tokens: &mut Tokenizer<'a>) -> Result> { + fn parse(tokens: &mut Tokenizer<'a>) -> Result, ParseErrors> { // 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 +550,7 @@ impl<'a> Interface<'a> { tokens: &mut Tokenizer<'a>, docs: Docs<'a>, attributes: Vec>, - ) -> Result { + ) -> Result { tokens.expect(Token::Interface)?; let name = parse_id(tokens)?; let items = Self::parse_items(tokens)?; @@ -552,7 +562,9 @@ impl<'a> Interface<'a> { }) } - pub(super) fn parse_items(tokens: &mut Tokenizer<'a>) -> Result>> { + pub(super) fn parse_items( + tokens: &mut Tokenizer<'a>, + ) -> Result>, ParseErrors> { tokens.expect(Token::LeftBrace)?; let mut items = Vec::new(); loop { @@ -593,7 +605,7 @@ enum UsePath<'a> { } impl<'a> UsePath<'a> { - fn parse(tokens: &mut Tokenizer<'a>) -> Result { + fn parse(tokens: &mut Tokenizer<'a>) -> Result { let id = parse_id(tokens)?; if tokens.eat(Token::Colon)? { // `foo:bar/baz@1.0` @@ -632,7 +644,10 @@ struct UseName<'a> { } impl<'a> Use<'a> { - fn parse(tokens: &mut Tokenizer<'a>, attributes: Vec>) -> Result { + fn parse( + tokens: &mut Tokenizer<'a>, + attributes: Vec>, + ) -> Result { tokens.expect(Token::Use)?; let from = UsePath::parse(tokens)?; tokens.expect(Token::Period)?; @@ -674,7 +689,10 @@ struct IncludeName<'a> { } impl<'a> Include<'a> { - fn parse(tokens: &mut Tokenizer<'a>, attributes: Vec>) -> Result { + fn parse( + tokens: &mut Tokenizer<'a>, + attributes: Vec>, + ) -> Result { tokens.expect(Token::Include)?; let from = UsePath::parse(tokens)?; @@ -801,7 +819,7 @@ impl<'a> ResourceFunc<'a> { docs: Docs<'a>, attributes: Vec>, tokens: &mut Tokenizer<'a>, - ) -> Result { + ) -> Result { match tokens.clone().next()? { Some((span, Token::Constructor)) => { tokens.expect(Token::Constructor)?; @@ -965,8 +983,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>) -> Result, ParseErrors> { + fn parse_params<'a>( + tokens: &mut Tokenizer<'a>, + left_paren: bool, + ) -> Result, ParseErrors> { if left_paren { tokens.expect(Token::LeftParen)?; }; @@ -1001,7 +1022,7 @@ impl<'a> InterfaceItem<'a> { tokens: &mut Tokenizer<'a>, docs: Docs<'a>, attributes: Vec>, - ) -> Result> { + ) -> Result, ParseErrors> { match tokens.clone().next()? { Some((_span, Token::Type)) => { TypeDef::parse(tokens, docs, attributes).map(InterfaceItem::TypeDef) @@ -1035,7 +1056,7 @@ impl<'a> TypeDef<'a> { tokens: &mut Tokenizer<'a>, docs: Docs<'a>, attributes: Vec>, - ) -> Result { + ) -> Result { tokens.expect(Token::Type)?; let name = parse_id(tokens)?; tokens.expect(Token::Equals)?; @@ -1053,7 +1074,7 @@ impl<'a> TypeDef<'a> { tokens: &mut Tokenizer<'a>, docs: Docs<'a>, attributes: Vec>, - ) -> Result { + ) -> Result { tokens.expect(Token::Flags)?; let name = parse_id(tokens)?; let ty = Type::Flags(Flags { @@ -1080,7 +1101,7 @@ impl<'a> TypeDef<'a> { tokens: &mut Tokenizer<'a>, docs: Docs<'a>, attributes: Vec>, - ) -> Result { + ) -> Result { tokens.expect(Token::Resource)?; let name = parse_id(tokens)?; let mut funcs = Vec::new(); @@ -1109,7 +1130,7 @@ impl<'a> TypeDef<'a> { tokens: &mut Tokenizer<'a>, docs: Docs<'a>, attributes: Vec>, - ) -> Result { + ) -> Result { tokens.expect(Token::Record)?; let name = parse_id(tokens)?; let ty = Type::Record(Record { @@ -1138,7 +1159,7 @@ impl<'a> TypeDef<'a> { tokens: &mut Tokenizer<'a>, docs: Docs<'a>, attributes: Vec>, - ) -> Result { + ) -> Result { tokens.expect(Token::Variant)?; let name = parse_id(tokens)?; let ty = Type::Variant(Variant { @@ -1172,7 +1193,7 @@ impl<'a> TypeDef<'a> { tokens: &mut Tokenizer<'a>, docs: Docs<'a>, attributes: Vec>, - ) -> Result { + ) -> Result { tokens.expect(Token::Enum)?; let name = parse_id(tokens)?; let ty = Type::Enum(Enum { @@ -1201,7 +1222,7 @@ impl<'a> NamedFunc<'a> { tokens: &mut Tokenizer<'a>, docs: Docs<'a>, attributes: Vec>, - ) -> Result { + ) -> Result { let name = parse_id(tokens)?; tokens.expect(Token::Colon)?; let func = Func::parse(tokens)?; @@ -1215,7 +1236,7 @@ impl<'a> NamedFunc<'a> { } } -fn parse_id<'a>(tokens: &mut Tokenizer<'a>) -> Result> { +fn parse_id<'a>(tokens: &mut Tokenizer<'a>) -> Result, ParseErrors> { match tokens.next()? { Some((span, Token::Id)) => Ok(Id { name: tokens.parse_id(span)?, @@ -1225,11 +1246,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<'_>) -> Result, ParseErrors> { if tokens.eat(Token::At)? { parse_version(tokens).map(Some) } else { @@ -1237,7 +1258,7 @@ fn parse_opt_version(tokens: &mut Tokenizer<'_>) -> Result) -> Result<(Span, Version)> { +fn parse_version(tokens: &mut Tokenizer<'_>) -> Result<(Span, Version), ParseErrors> { let start = tokens.expect(Token::Integer)?.start(); tokens.expect(Token::Period)?; tokens.expect(Token::Integer)?; @@ -1247,7 +1268,12 @@ 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| { + ParseErrors::from(ParseErrorKind::Syntax { + span, + message: e.to_string(), + }) + })?; return Ok((span, version)); // According to `semver.org` this is what we're parsing: @@ -1303,7 +1329,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 +1357,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 +1386,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>) -> Result { match tokens.next()? { Some((span, Token::U8)) => Ok(Type::U8(span)), Some((span, Token::U16)) => Ok(Type::U16(span)), @@ -1392,7 +1422,12 @@ 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| { + ParseErrors::from(ParseErrorKind::Syntax { + span, + message: format!("invalid list size: {e}"), + }) + })?; Some(size) } else { return Err(err_expected(tokens, "fixed-length", number).into()); @@ -1560,8 +1595,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>) -> Result, +) -> Result, ParseErrors> { tokens.expect(start)?; parse_list_trailer(tokens, end, parse) } @@ -1569,8 +1604,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>) -> Result, +) -> Result, ParseErrors> { let mut items = Vec::new(); loop { // get docs before we skip them to try to eat the end token @@ -1598,13 +1633,16 @@ fn err_expected( tokens: &Tokenizer<'_>, expected: &'static str, found: Option<(Span, Token)>, -) -> Error { +) -> ParseErrors { match found { - Some((span, token)) => Error::new( + Some((span, token)) => ParseErrors::from(ParseErrorKind::Syntax { span, - format!("expected {}, found {}", expected, token.describe()), - ), - None => Error::new(tokens.eof_span(), format!("expected {expected}, found eof")), + message: format!("expected {}, found {}", expected, token.describe()), + }), + None => ParseErrors::from(ParseErrorKind::Syntax { + span: tokens.eof_span(), + message: format!("expected {expected}, found eof"), + }), } } @@ -1615,7 +1653,7 @@ enum Attribute<'a> { } impl<'a> Attribute<'a> { - fn parse_list(tokens: &mut Tokenizer<'a>) -> Result>> { + fn parse_list(tokens: &mut Tokenizer<'a>) -> Result>, ParseErrors> { let mut ret = Vec::new(); while tokens.eat(Token::At)? { let id = parse_id(tokens)?; @@ -1654,7 +1692,10 @@ impl<'a> Attribute<'a> { } } other => { - bail!(Error::new(id.span, format!("unknown attribute `{other}`"),)) + return Err(ParseErrors::from(ParseErrorKind::Syntax { + span: id.span, + message: format!("unknown attribute `{other}`"), + })); } }; ret.push(attr); @@ -1671,13 +1712,13 @@ impl<'a> Attribute<'a> { } } -fn eat_id(tokens: &mut Tokenizer<'_>, expected: &str) -> Result { +fn eat_id(tokens: &mut Tokenizer<'_>, expected: &str) -> Result { let id = parse_id(tokens)?; if id.name != expected { - bail!(Error::new( - id.span, - format!("expected `{expected}`, found `{}`", id.name), - )); + return Err(ParseErrors::from(ParseErrorKind::Syntax { + span: id.span, + message: format!("expected `{expected}`, found `{}`", id.name), + })); } Ok(id.span) } @@ -1699,6 +1740,16 @@ struct Source { contents: String, } +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SpanLocation { + /// File to which this span belongs + pub file: String, + /// UTF-8 byte offet within the file (start) + pub start: usize, + /// UTF-8 byte offet within the file (end) + pub end: usize, +} + impl SourceMap { /// Creates a new empty source map. pub fn new() -> SourceMap { @@ -1708,7 +1759,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,94 +1819,55 @@ impl SourceMap { /// Parses the files added to this source map into a /// [`UnresolvedPackageGroup`]. - pub fn parse(self) -> Result { + pub fn parse(self) -> Result { 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()?) - })?; + + // With nested packages handled push this file into the resolver. + resolver.push(file)?; + } + Ok(UnresolvedPackageGroup { - main, + main: resolver.resolve()?, nested, source_map: self, }) } - pub(crate) fn rewrite_error(&self, f: F) -> Result - where - F: FnOnce() -> 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(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) - } - - pub(crate) fn highlight_span(&self, span: Span, err: impl fmt::Display) -> Option { + pub fn highlight_span(&self, span: Span, err: impl fmt::Display) -> Option { if !span.is_known() { return None; } @@ -1915,6 +1927,20 @@ impl SourceMap { ) } + pub fn get_location(&self, span: Span) -> Option { + if !span.is_known() { + return None; + } + let start = span.start(); + let end = span.end(); + let src = self.source_for_offset(start); + Some(SpanLocation { + file: src.path.clone(), + start: src.to_relative_offset(start), + end: src.to_relative_offset(end), + }) + } + fn source_for_offset(&self, start: u32) -> &Source { let i = match self.sources.binary_search_by_key(&start, |src| src.offset) { Ok(i) => i, @@ -1960,11 +1986,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..da670b0d9e --- /dev/null +++ b/crates/wit-parser/src/ast/error.rs @@ -0,0 +1,123 @@ +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use core::fmt; + +use crate::{ + SourceMap, Span, + ast::{lex, toposort}, +}; + +#[derive(Debug)] +pub struct ParseErrors(Box); + +#[non_exhaustive] +#[derive(Debug)] +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. Arises from within-package toposort. + ItemNotFound { + span: Span, + name: String, + kind: String, + hint: Option, + }, + /// A type/interface/world depends on itself. Arises from within-package + /// toposort. + 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") + } + } + } +} + +impl ParseErrors { + pub fn kind(&self) -> &ParseErrorKind { + &self.0 + } + + 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 ParseErrors { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Display::fmt(self.kind(), f) + } +} + +impl core::error::Error for ParseErrors {} + +impl From for ParseErrors { + fn from(kind: ParseErrorKind) -> Self { + ParseErrors(Box::new(kind)) + } +} + +impl From for ParseErrors { + fn from(e: lex::Error) -> Self { + ParseErrorKind::Lex(e).into() + } +} + +impl From for ParseErrors { + fn from(e: toposort::Error) -> Self { + let kind = match e { + toposort::Error::NonexistentDep { + span, + name, + kind, + hint, + } => ParseErrorKind::ItemNotFound { + span, + name, + kind, + hint, + }, + toposort::Error::Cycle { span, name, kind } => { + ParseErrorKind::TypeCycle { span, name, kind } + } + }; + kind.into() + } +} diff --git a/crates/wit-parser/src/ast/resolve.rs b/crates/wit-parser/src/ast/resolve.rs index e77ac0f260..a1b72b1a38 100644 --- a/crates/wit-parser/src/ast/resolve.rs +++ b/crates/wit-parser/src/ast/resolve.rs @@ -1,11 +1,13 @@ use super::{ParamList, WorldOrInterface}; +use crate::alloc::borrow::ToOwned; +use crate::ast::error::{ParseErrorKind, ParseErrors}; 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; +use core::result::Result; #[derive(Default)] pub struct Resolver<'a> { @@ -105,7 +107,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>) -> Result<(), ParseErrors> { // 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 +115,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( - cur.span, - format!( + return Err(ParseErrors::from(ParseErrorKind::Syntax { + span: cur.span, + message: format!( "package identifier `{cur_name}` does not match \ previous package name of `{prev}`" ), - )) + })); } } self.package_name = Some((cur_name, cur.span)); @@ -128,10 +130,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( - cur.docs.span, - "found doc comments on multiple 'package' items" - )) + return Err(ParseErrors::from(ParseErrorKind::Syntax { + span: cur.docs.span, + message: "found doc comments on multiple 'package' items".to_owned(), + })); } self.package_docs = docs; } @@ -145,22 +147,26 @@ impl<'a> Resolver<'a> { ast::AstItem::Package(pkg) => pkg.package_id.as_ref().unwrap().span, _ => continue, }; - bail!(Error::new( - span, - "nested packages must be placed at the top-level" - )) + return Err(ParseErrors::from(ParseErrorKind::Syntax { + span: span, + message: "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) -> Result { // 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(ParseErrors::from(ParseErrorKind::Syntax { + span: Span::default(), + message: "no `package` header was found in any WIT file for this package" + .to_owned(), + })); } }; @@ -336,7 +342,7 @@ impl<'a> Resolver<'a> { fn populate_ast_items( &mut self, decl_lists: &[ast::DeclList<'a>], - ) -> Result<(Vec, Vec)> { + ) -> Result<(Vec, Vec), ParseErrors> { let mut package_items = IndexMap::default(); // Validate that all worlds and interfaces have unique names within this @@ -350,10 +356,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( - i.name.span, - format!("duplicate item named `{}`", i.name.name), - )) + return Err(ParseErrors::from(ParseErrorKind::Syntax { + span: i.name.span, + message: format!("duplicate item named `{}`", i.name.name), + })); } let prev = decl_list_ns.insert(i.name.name, ()); assert!(prev.is_none()); @@ -364,10 +370,10 @@ impl<'a> Resolver<'a> { } ast::AstItem::World(w) => { if package_items.insert(w.name.name, w.name.span).is_some() { - bail!(Error::new( - w.name.span, - format!("duplicate item named `{}`", w.name.name), - )) + return Err(ParseErrors::from(ParseErrorKind::Syntax { + span: w.name.span, + message: format!("duplicate item named `{}`", w.name.name), + })); } let prev = decl_list_ns.insert(w.name.name, ()); assert!(prev.is_none()); @@ -415,10 +421,10 @@ impl<'a> Resolver<'a> { ast::AstItem::Package(_) => unreachable!(), }; if decl_list_ns.insert(name.name, (name.span, src)).is_some() { - bail!(Error::new( - name.span, - format!("duplicate name `{}` in this file", name.name), - )); + return Err(ParseErrors::from(ParseErrorKind::Syntax { + span: name.span, + message: format!("duplicate name `{}` in this file", name.name), + })); } } @@ -446,13 +452,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(ParseErrors::from(ParseErrorKind::ItemNotFound { + span: used_name.span, + name: used_name.name.to_string(), + kind: "interface or world".to_string(), + hint: None, + })); } }, } @@ -494,21 +499,20 @@ impl<'a> Resolver<'a> { let (name, ast_item) = match item { ast::AstItem::Use(u) => { if !u.attributes.is_empty() { - bail!(Error::new( - u.span, - format!("attributes not allowed on top-level use"), - )) + return Err(ParseErrors::from(ParseErrorKind::Syntax { + span: u.span, + message: 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 - ), - ) + ParseErrors::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 +553,10 @@ 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>], + ) -> Result<(), ParseErrors> { 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 +600,11 @@ 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>, + ) -> Result { let docs = self.docs(&world.docs); self.worlds[world_id].docs = docs; let stability = self.stability(&world.attributes)?; @@ -627,10 +638,12 @@ impl<'a> Resolver<'a> { WorldItem::Type { id, span: *span }, ); if prev.is_some() { - bail!(Error::new( - *span, - format!("import `{name}` conflicts with prior import of same name"), - )) + return Err(ParseErrors::from(ParseErrorKind::Syntax { + span: *span, + message: format!( + "import `{name}` conflicts with prior import of same name" + ), + })); } } TypeOrItem::Item(_) => unreachable!(), @@ -704,10 +717,10 @@ impl<'a> Resolver<'a> { }; if let WorldItem::Interface { id, .. } = world_item { if !interfaces.insert(id) { - bail!(Error::new( - kind.span(), - format!("interface cannot be {desc}ed more than once"), - )) + return Err(ParseErrors::from(ParseErrorKind::Syntax { + span: kind.span(), + message: format!("interface cannot be {desc}ed more than once"), + })); } } let dst = if desc == "import" { @@ -726,10 +739,10 @@ impl<'a> Resolver<'a> { WorldKey::Name(name) => name, WorldKey::Interface(..) => unreachable!(), }; - bail!(Error::new( - kind.span(), - format!("{desc} `{name}` conflicts with prior {prev} of same name",), - )) + return Err(ParseErrors::from(ParseErrorKind::Syntax { + span: kind.span(), + message: format!("{desc} `{name}` conflicts with prior {prev} of same name",), + })); } } self.type_lookup.clear(); @@ -742,7 +755,7 @@ impl<'a> Resolver<'a> { docs: &ast::Docs<'a>, attrs: &[ast::Attribute<'a>], kind: &ast::ExternKind<'a>, - ) -> Result { + ) -> Result { match kind { ast::ExternKind::Interface(name, items) => { let prev = mem::take(&mut self.type_lookup); @@ -790,7 +803,7 @@ impl<'a> Resolver<'a> { fields: &[ast::InterfaceItem<'a>], docs: &ast::Docs<'a>, attrs: &[ast::Attribute<'a>], - ) -> Result<()> { + ) -> Result<(), ParseErrors> { let docs = self.docs(docs); self.interfaces[interface_id].docs = docs; let stability = self.stability(attrs)?; @@ -866,7 +879,7 @@ impl<'a> Resolver<'a> { &mut self, owner: TypeOwner, fields: impl Iterator> + Clone, - ) -> Result<()> + ) -> Result<(), ParseErrors> where 'a: 'b, { @@ -893,10 +906,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( - t.name.span, - format!("name `{}` is defined more than once", t.name.name), - )) + return Err(ParseErrors::from(ParseErrorKind::Syntax { + span: t.name.span, + message: format!("name `{}` is defined more than once", t.name.name), + })); } let mut deps = Vec::new(); collect_deps(&t.ty, &mut deps); @@ -911,7 +924,9 @@ impl<'a> Resolver<'a> { } } } - let order = toposort("type", &type_deps).map_err(attach_old_float_type_context)?; + let order = toposort("type", &type_deps) + .map_err(attach_old_float_type_context) + .map_err(ParseErrors::from)?; for ty in order { let def = match type_defs.swap_remove(&ty).unwrap() { Some(def) => def, @@ -932,28 +947,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: ast::toposort::Error) -> ast::toposort::Error { + if let ast::toposort::Error::NonexistentDep { name, hint, .. } = &mut err { + 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>) -> Result<(), ParseErrors> { 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 +975,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( - name.name.span, - format!("cannot import {s} `{}`", name.name.name), - )) + return Err(ParseErrors::from(ParseErrorKind::Syntax { + span: name.name.span, + message: format!("cannot import {s} `{}`", name.name.name), + })); + } + None => { + return Err(ParseErrors::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 +1005,11 @@ 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>, + ) -> Result<(), ParseErrors> { 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 +1033,7 @@ impl<'a> Resolver<'a> { &mut self, func: &ast::ResourceFunc<'_>, resource: &ast::Id<'_>, - ) -> Result { + ) -> Result { let resource_id = match self.type_lookup.get(resource.name) { Some((TypeOrItem::Type(id), _)) => *id, _ => panic!("type lookup for resource failed"), @@ -1062,7 +1082,7 @@ impl<'a> Resolver<'a> { name_span: Span, func: &ast::Func, kind: FunctionKind, - ) -> Result { + ) -> Result { let docs = self.docs(docs); let stability = self.stability(attrs)?; let params = self.resolve_params(&func.params, &kind, func.span)?; @@ -1078,7 +1098,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>, + ) -> Result<(AstItem, String, Span), ParseErrors> { match path { ast::UsePath::Id(id) => { let item = self.ast_items[self.cur_ast_index] @@ -1087,10 +1110,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(ParseErrors::from(ParseErrorKind::ItemNotFound { + span: id.span, + name: id.name.to_string(), + kind: "interface or world".to_owned(), + hint: None, + })); } } } @@ -1107,37 +1132,46 @@ impl<'a> Resolver<'a> { item: &AstItem, name: &str, span: Span, - ) -> Result { + ) -> Result { match item { AstItem::Interface(id) => Ok(*id), AstItem::World(_) => { - bail!(Error::new( + return Err(ParseErrors::from(ParseErrorKind::Syntax { span, - format!("name `{name}` is defined as a world, not an interface"), - )) + message: 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, + ) -> Result { match item { AstItem::World(id) => Ok(*id), AstItem::Interface(_) => { - bail!(Error::new( + return Err(ParseErrors::from(ParseErrorKind::Syntax { span, - format!("name `{name}` is defined as an interface, not a world"), - )) + message: 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, + ) -> Result<(), ParseErrors> { let prev = self.type_lookup.insert(name.name, (item, name.span)); if prev.is_some() { - bail!(Error::new( - name.span, - format!("name `{}` is defined more than once", name.name), - )) + return Err(ParseErrors::from(ParseErrorKind::Syntax { + span: name.span, + message: format!("name `{}` is defined more than once", name.name), + })); } else { Ok(()) } @@ -1147,7 +1181,7 @@ impl<'a> Resolver<'a> { &mut self, ty: &ast::Type<'_>, stability: &Stability, - ) -> Result { + ) -> Result { Ok(match ty { ast::Type::Bool(_) => TypeDefKind::Type(Type::Bool), ast::Type::U8(_) => TypeDefKind::Type(Type::U8), @@ -1188,10 +1222,10 @@ 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(ParseErrors::from(ParseErrorKind::Syntax { + span: map.span, + message: "invalid map key type: map keys must be bool, u8, u16, u32, u64, s8, s16, s32, s64, char, or string".to_owned(), + })); } } @@ -1216,16 +1250,19 @@ impl<'a> Resolver<'a> { match func { ast::ResourceFunc::Method(f) | ast::ResourceFunc::Static(f) => { if !names.insert(&f.name.name) { - bail!(Error::new( - f.name.span, - format!("duplicate function name `{}`", f.name.name), - )) + return Err(ParseErrors::from(ParseErrorKind::Syntax { + span: f.name.span, + message: 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(ParseErrors::from(ParseErrorKind::Syntax { + span: f.name.span, + message: "duplicate constructors".to_owned(), + })); } } } @@ -1245,7 +1282,7 @@ impl<'a> Resolver<'a> { span: field.name.span, }) }) - .collect::>>()?; + .collect::, ParseErrors>>()?; TypeDefKind::Record(Record { fields }) } ast::Type::Flags(flags) => { @@ -1265,12 +1302,15 @@ impl<'a> Resolver<'a> { .types .iter() .map(|ty| self.resolve_type(ty, stability)) - .collect::>>()?; + .collect::, ParseErrors>>()?; TypeDefKind::Tuple(Tuple { types }) } ast::Type::Variant(variant) => { if variant.cases.is_empty() { - bail!(Error::new(variant.span, "empty variant")) + return Err(ParseErrors::from(ParseErrorKind::Syntax { + span: variant.span, + message: "empty variant".to_owned(), + })); } let cases = variant .cases @@ -1283,12 +1323,15 @@ impl<'a> Resolver<'a> { span: case.name.span, }) }) - .collect::>>()?; + .collect::, ParseErrors>>()?; TypeDefKind::Variant(Variant { cases }) } ast::Type::Enum(e) => { if e.cases.is_empty() { - bail!(Error::new(e.span, "empty enum")) + return Err(ParseErrors::from(ParseErrorKind::Syntax { + span: e.span, + message: "empty enum".to_owned(), + })); } let cases = e .cases @@ -1300,7 +1343,7 @@ impl<'a> Resolver<'a> { span: case.name.span, }) }) - .collect::>>()?; + .collect::, ParseErrors>>()?; TypeDefKind::Enum(Enum { cases }) } ast::Type::Option(ty) => TypeDefKind::Option(self.resolve_type(&ty.ty, stability)?), @@ -1317,21 +1360,27 @@ impl<'a> Resolver<'a> { }) } - fn resolve_type_name(&mut self, name: &ast::Id<'_>) -> Result { + fn resolve_type_name(&mut self, name: &ast::Id<'_>) -> Result { 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(ParseErrors::from(ParseErrorKind::Syntax { + span: name.span, + message: format!("cannot use {s} `{name}` as a type", name = name.name), + })); + } + None => { + return Err(ParseErrors::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<'_>) -> Result { let id = self.resolve_type_name(name)?; let mut cur = id; loop { @@ -1342,10 +1391,15 @@ 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(ParseErrors::from(ParseErrorKind::Syntax { + span: name.span, + message: format!( + "type `{}` used in a handle must be a resource", + name.name + ), + })); + } } } } @@ -1419,7 +1473,11 @@ 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, + ) -> Result { // 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 +1501,7 @@ impl<'a> Resolver<'a> { &mut self, ty: Option<&super::Type<'_>>, stability: &Stability, - ) -> Result> { + ) -> Result, ParseErrors> { match ty { Some(ty) => Ok(Some(self.resolve_type(ty, stability)?)), None => Ok(None), @@ -1549,7 +1607,7 @@ impl<'a> Resolver<'a> { Docs { contents } } - fn stability(&mut self, attrs: &[ast::Attribute<'_>]) -> Result { + fn stability(&mut self, attrs: &[ast::Attribute<'_>]) -> Result { match attrs { [] => Ok(Stability::Unknown), @@ -1593,16 +1651,16 @@ impl<'a> Resolver<'a> { deprecated: Some(version.clone()), }), [ast::Attribute::Deprecated { span, .. }] => { - bail!(Error::new( - *span, - "must pair @deprecated with either @since or @unstable", - )) + return Err(ParseErrors::from(ParseErrorKind::Syntax { + span: *span, + message: "must pair @deprecated with either @since or @unstable".to_owned(), + })); } [_, b, ..] => { - bail!(Error::new( - b.span(), - "unsupported combination of attributes", - )) + return Err(ParseErrors::from(ParseErrorKind::Syntax { + span: b.span(), + message: "unsupported combination of attributes".to_owned(), + })); } } } @@ -1612,7 +1670,7 @@ impl<'a> Resolver<'a> { params: &ParamList<'_>, kind: &FunctionKind, span: Span, - ) -> Result> { + ) -> Result, ParseErrors> { let mut ret = Vec::new(); match *kind { // These kinds of methods don't have any adjustments to the @@ -1645,10 +1703,10 @@ impl<'a> Resolver<'a> { } for (name, ty) in params { if ret.iter().any(|p| p.name == name.name) { - bail!(Error::new( - name.span, - format!("param `{}` is defined more than once", name.name), - )) + return Err(ParseErrors::from(ParseErrorKind::Syntax { + span: name.span, + message: format!("param `{}` is defined more than once", name.name), + })); } ret.push(Param { name: name.name.to_string(), @@ -1664,7 +1722,7 @@ impl<'a> Resolver<'a> { result: &Option>, kind: &FunctionKind, _span: Span, - ) -> Result> { + ) -> Result, ParseErrors> { match *kind { // These kinds of methods don't have any adjustments to the return // values, so plumb them through as-is. @@ -1696,7 +1754,7 @@ impl<'a> Resolver<'a> { &mut self, resource_id: TypeId, result_ast: &ast::Type<'_>, - ) -> Result { + ) -> Result { let result = self.resolve_type(result_ast, &Stability::Unknown)?; let ok_type = match result { Type::Id(id) => match &self.types[id].kind { @@ -1706,10 +1764,11 @@ impl<'a> Resolver<'a> { _ => None, }; let Some(ok_type) = ok_type else { - bail!(Error::new( - result_ast.span(), - "if a constructor return type is declared it must be a `result`", - )); + return Err(ParseErrors::from(ParseErrorKind::Syntax { + span: result_ast.span(), + message: "if a constructor return type is declared it must be a `result`" + .to_owned(), + })); }; match ok_type { Some(Type::Id(ok_id)) if resource_id == ok_id => Ok(result), @@ -1720,10 +1779,10 @@ impl<'a> Resolver<'a> { } else { result_ast.span() }; - bail!(Error::new( - ok_span, - "the `ok` type must be the resource being constructed", - )); + return Err(ParseErrors::from(ParseErrorKind::Syntax { + span: ok_span, + message: "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..5dd36fb4a7 100644 --- a/crates/wit-parser/src/ast/toposort.rs +++ b/crates/wit-parser/src/ast/toposort.rs @@ -1,13 +1,12 @@ use crate::IndexMap; use crate::ast::{Id, Span}; use alloc::collections::BinaryHeap; -use alloc::format; use alloc::string::{String, ToString}; use alloc::vec; use alloc::vec::Vec; -use anyhow::Result; use core::fmt; use core::mem; +use core::result::Result; #[derive(Default, Clone)] struct State { @@ -59,7 +58,7 @@ pub fn toposort<'a>( span: edge.span, name: edge.name.to_string(), kind: kind.to_string(), - highlighted: None, + hint: None, })?; states[j].reverse_deps.push(i); } @@ -120,7 +119,6 @@ pub fn toposort<'a>( span: dep.span, name: dep.name.to_string(), kind: kind.to_string(), - highlighted: None, }); } } @@ -128,56 +126,42 @@ pub fn toposort<'a>( unreachable!() } -#[derive(Debug)] +#[derive(Clone, Debug)] pub enum Error { NonexistentDep { span: Span, name: String, kind: String, - highlighted: Option, + /// Optional hint to display after the main error message, e.g. to + /// suggest a renamed type. + hint: Option, }, Cycle { span: Span, name: String, kind: String, - highlighted: Option, }, } impl Error { - pub(crate) fn highlighted(&self) -> Option<&str> { + pub fn span(&self) -> Span { match self { - Error::NonexistentDep { highlighted, .. } | Error::Cycle { highlighted, .. } => { - highlighted.as_deref() - } - } - } - - /// 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::NonexistentDep { + kind, name, hint, .. + } => { + write!(f, "{kind} `{name}` does not exist")?; + if let Some(hint) = hint { + write!(f, "\n{hint}")?; + } + Ok(()) } Error::Cycle { kind, name, .. } => { write!(f, "{kind} `{name}` depends on itself") diff --git a/crates/wit-parser/src/decoding.rs b/crates/wit-parser/src/decoding.rs index 88253a3b6e..8d8e234da5 100644 --- a/crates/wit-parser/src/decoding.rs +++ b/crates/wit-parser/src/decoding.rs @@ -2,7 +2,7 @@ use crate::*; use alloc::string::{String, ToString}; use alloc::vec; use alloc::vec::Vec; -use anyhow::{Context, anyhow, bail}; +use anyhow::{Context, Result, anyhow, bail}; use core::mem; use std::io::Read; use wasmparser::Chunk; diff --git a/crates/wit-parser/src/lib.rs b/crates/wit-parser/src/lib.rs index 742d75159d..7f3e2b4310 100644 --- a/crates/wit-parser/src/lib.rs +++ b/crates/wit-parser/src/lib.rs @@ -10,8 +10,7 @@ use alloc::format; use alloc::string::{String, ToString}; use alloc::vec::Vec; #[cfg(feature = "std")] -use anyhow::Context; -use anyhow::{Result, bail}; +use anyhow::Context as _; use id_arena::{Arena, Id}; use semver::Version; @@ -33,6 +32,7 @@ pub(crate) use hashbrown::{HashMap, HashSet}; use alloc::borrow::Cow; use core::fmt; use core::hash::{Hash, Hasher}; +use core::result::Result; #[cfg(feature = "std")] use std::path::Path; @@ -46,8 +46,9 @@ pub use metadata::PackageMetadata; pub mod abi; mod ast; pub use ast::SourceMap; +pub use ast::error::{ParseErrorKind, ParseErrors}; pub use ast::lex::Span; -pub use ast::{ParsedUsePath, parse_use_path}; +pub use ast::{ParsedUsePath, SpanLocation, parse_use_path}; mod sizealign; pub use sizealign::*; mod resolve; @@ -63,7 +64,7 @@ mod serde_; use serde_::*; /// Checks if the given string is a legal identifier in wit. -pub fn validate_id(s: &str) -> Result<()> { +pub fn validate_id(s: &str) -> anyhow::Result<()> { ast::validate_id(0, s)?; Ok(()) } @@ -293,91 +294,6 @@ impl fmt::Display for PackageName { } } -#[derive(Debug)] -struct Error { - span: Span, - msg: String, - highlighted: Option, -} - -impl Error { - fn new(span: Span, msg: impl Into) -> Error { - Error { - span, - msg: msg.into(), - highlighted: None, - } - } - - /// Highlights this error using the given source map, if the span is known. - fn highlight(&mut self, source_map: &ast::SourceMap) { - if self.highlighted.is_none() { - self.highlighted = source_map.highlight_span(self.span, &self.msg); - } - } -} - -impl fmt::Display for Error { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - self.highlighted.as_ref().unwrap_or(&self.msg).fmt(f) - } -} - -impl core::error::Error for Error {} - -#[derive(Debug)] -struct PackageNotFoundError { - span: Span, - requested: PackageName, - known: Vec, - highlighted: Option, -} - -impl PackageNotFoundError { - pub fn new(span: Span, requested: PackageName, known: Vec) -> Self { - Self { - span, - requested, - known, - highlighted: None, - } - } - - /// Highlights this error using the given source map, if the span is known. - fn highlight(&mut self, source_map: &ast::SourceMap) { - if self.highlighted.is_none() { - self.highlighted = source_map.highlight_span(self.span, &format!("{self}")); - } - } -} - -impl fmt::Display for PackageNotFoundError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - if let Some(highlighted) = &self.highlighted { - return highlighted.fmt(f); - } - if self.known.is_empty() { - write!( - f, - "package '{}' not found. no known packages.", - self.requested - )?; - } else { - write!( - f, - "package '{}' not found. known packages:\n", - self.requested - )?; - for known in self.known.iter() { - write!(f, " {known}\n")?; - } - } - Ok(()) - } -} - -impl core::error::Error for PackageNotFoundError {} - impl UnresolvedPackageGroup { /// Parses the given string as a wit document. /// @@ -385,12 +301,18 @@ impl UnresolvedPackageGroup { /// are considered to be the contents of `path`. This function does not read /// the filesystem. #[cfg(feature = "std")] - pub fn parse(path: impl AsRef, contents: &str) -> Result { + pub fn parse(path: impl AsRef, contents: &str) -> anyhow::Result { let path = path .as_ref() .to_str() .ok_or_else(|| anyhow::anyhow!("path is not valid utf-8: {:?}", path.as_ref()))?; - Self::parse_str(path, contents) + let mut map = ast::SourceMap::default(); + map.push_str(path, contents); + // TODO: avoid clone by changing `SourceMap::parse` to return the map + // back on error, e.g. `Err((SourceMap, ParseErrors))`. + let map_for_err = map.clone(); + map.parse() + .map_err(|e| anyhow::anyhow!("{}", e.highlight(&map_for_err))) } /// Parses the given string as a wit document. @@ -398,7 +320,7 @@ impl UnresolvedPackageGroup { /// 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 { + pub fn parse_str(path: &str, contents: &str) -> Result { let mut map = SourceMap::default(); map.push_str(path, contents); map.parse() @@ -410,7 +332,7 @@ impl UnresolvedPackageGroup { /// 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 { + pub fn parse_path(path: impl AsRef) -> anyhow::Result { let path = path.as_ref(); if path.is_dir() { UnresolvedPackageGroup::parse_dir(path) @@ -424,7 +346,7 @@ impl UnresolvedPackageGroup { /// 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 { + pub fn parse_file(path: impl AsRef) -> anyhow::Result { let path = path.as_ref(); let contents = std::fs::read_to_string(path) .with_context(|| format!("failed to read file {path:?}"))?; @@ -438,7 +360,7 @@ impl UnresolvedPackageGroup { /// grouping. This is useful when a WIT package is split across multiple /// files. #[cfg(feature = "std")] - pub fn parse_dir(path: impl AsRef) -> Result { + pub fn parse_dir(path: impl AsRef) -> anyhow::Result { let path = path.as_ref(); let mut map = SourceMap::default(); let cx = || format!("failed to read directory {path:?}"); @@ -463,7 +385,11 @@ impl UnresolvedPackageGroup { } map.push_file(&path)?; } + // TODO: avoid clone by changing `SourceMap::parse` to return the map + // back on error, e.g. `Err((SourceMap, ParseErrors))`. + let map_for_err = map.clone(); map.parse() + .map_err(|e| anyhow::anyhow!("{}", e.highlight(&map_for_err))) } } @@ -1195,12 +1121,12 @@ pub enum Mangling { impl core::str::FromStr for Mangling { type Err = anyhow::Error; - fn from_str(s: &str) -> Result { + fn from_str(s: &str) -> anyhow::Result { match s { "legacy" => Ok(Mangling::Legacy), "standard32" => Ok(Mangling::Standard32), _ => { - bail!( + anyhow::bail!( "unknown name mangling `{s}`, \ supported values are `legacy` or `standard32`" ) diff --git a/crates/wit-parser/src/resolve/error.rs b/crates/wit-parser/src/resolve/error.rs new file mode 100644 index 0000000000..d012004a3c --- /dev/null +++ b/crates/wit-parser/src/resolve/error.rs @@ -0,0 +1,115 @@ +use alloc::boxed::Box; +use alloc::format; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::fmt; + +use crate::{PackageName, SourceMap, Span}; + +#[derive(Clone, Debug)] +pub struct ResolveErrors(Box); + +impl ResolveErrors { + pub fn kind(&self) -> &ResolveErrorKind { + &self.0 + } + + pub fn highlight(&self, source_map: &SourceMap) -> String { + let e = self.kind(); + let msg = e.to_string(); + match e { + ResolveErrorKind::DuplicatePackage { name, span1, span2 } => { + let loc1 = source_map.render_location(*span1); + let loc2 = source_map.render_location(*span2); + format!( + "package `{name}` is defined in two different locations:\n * {loc1}\n * {loc2}" + ) + } + _ => source_map.highlight_span(e.span(), &msg).unwrap_or(msg), + } + } +} + +impl fmt::Display for ResolveErrors { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Display::fmt(self.kind(), f) + } +} + +impl core::error::Error for ResolveErrors {} + +impl From for ResolveErrors { + fn from(kind: ResolveErrorKind) -> Self { + ResolveErrors(Box::new(kind)) + } +} + +#[non_exhaustive] +#[derive(Clone, Debug)] +pub enum ResolveErrorKind { + PackageNotFound { + span: Span, + requested: PackageName, + known: Vec, + }, + InvalidTransitiveDependency { + span: Span, + name: String, + }, + DuplicatePackage { + name: PackageName, + span1: Span, + span2: Span, + }, + PackageCycle { + package: PackageName, + span: Span, + }, + Semantic { + span: Span, + message: String, + }, +} + +impl ResolveErrorKind { + pub fn span(&self) -> Span { + match self { + ResolveErrorKind::PackageNotFound { span, .. } + | ResolveErrorKind::InvalidTransitiveDependency { span, .. } + | ResolveErrorKind::PackageCycle { span, .. } + | ResolveErrorKind::Semantic { span, .. } => *span, + ResolveErrorKind::DuplicatePackage { span1, .. } => *span1, + } + } +} + +impl fmt::Display for ResolveErrorKind { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + ResolveErrorKind::PackageNotFound { + requested, known, .. + } => { + if known.is_empty() { + write!(f, "package '{requested}' not found") + } else { + write!(f, "package '{requested}' not found. known packages:")?; + for k in known { + write!(f, "\n {k}")?; + } + Ok(()) + } + } + ResolveErrorKind::InvalidTransitiveDependency { name, .. } => write!( + f, + "interface `{name}` transitively depends on an interface in incompatible ways", + ), + ResolveErrorKind::DuplicatePackage { name, .. } => { + write!(f, "package `{name}` is defined in two different locations",) + } + ResolveErrorKind::PackageCycle { package, .. } => { + write!(f, "package `{package}` creates a dependency cycle") + } + ResolveErrorKind::Semantic { message, .. } => message.fmt(f), + } + } +} diff --git a/crates/wit-parser/src/resolve/fs.rs b/crates/wit-parser/src/resolve/fs.rs index 39ff86721c..a979156ed0 100644 --- a/crates/wit-parser/src/resolve/fs.rs +++ b/crates/wit-parser/src/resolve/fs.rs @@ -131,7 +131,9 @@ impl Resolve { .parse_deps_dir(&deps) .with_context(|| format!("failed to parse dependency directory: {}", deps.display()))?; - let (pkg_id, inner) = self.sort_unresolved_packages(top_pkg, deps)?; + let sort_result = self.sort_unresolved_packages(top_pkg, deps); + let (pkg_id, inner) = + sort_result.map_err(|e| anyhow::anyhow!("{}", e.highlight(&self.source_map)))?; Ok((pkg_id, PackageSourceMap::from_inner(inner))) } diff --git a/crates/wit-parser/src/resolve/mod.rs b/crates/wit-parser/src/resolve/mod.rs index f7d7b5ac92..a08ce9f251 100644 --- a/crates/wit-parser/src/resolve/mod.rs +++ b/crates/wit-parser/src/resolve/mod.rs @@ -4,11 +4,12 @@ use alloc::string::{String, ToString}; use alloc::vec::Vec; use alloc::{format, vec}; use core::cmp::Ordering; -use core::fmt; use core::mem; +use core::result::Result; +use crate::resolve::error::{ResolveErrorKind, ResolveErrors}; use crate::*; -use anyhow::{Context, Result, anyhow, bail}; +use anyhow::{Context, anyhow, bail}; #[cfg(not(feature = "std"))] use hashbrown::hash_map::Entry; use id_arena::{Arena, Id}; @@ -23,15 +24,16 @@ use crate::ast::{ParsedUsePath, parse_use_path}; #[cfg(feature = "serde")] use crate::serde_::{serialize_arena, serialize_id_map}; use crate::{ - AstItem, Docs, Error, Function, FunctionKind, Handle, IncludeName, Interface, InterfaceId, - LiftLowerAbi, ManglingAndAbi, PackageName, PackageNotFoundError, SourceMap, Stability, Type, - TypeDef, TypeDefKind, TypeId, TypeIdVisitor, TypeOwner, UnresolvedPackage, - UnresolvedPackageGroup, World, WorldId, WorldItem, WorldKey, + AstItem, Docs, Function, FunctionKind, Handle, IncludeName, Interface, InterfaceId, + LiftLowerAbi, ManglingAndAbi, PackageName, SourceMap, Stability, Type, TypeDef, TypeDefKind, + TypeId, TypeIdVisitor, TypeOwner, UnresolvedPackage, UnresolvedPackageGroup, World, WorldId, + WorldItem, WorldKey, }; pub use clone::CloneMaps; mod clone; +pub mod error; #[cfg(feature = "std")] mod fs; @@ -195,33 +197,38 @@ fn visit<'a>( pkg_details_map: &'a BTreeMap, order: &mut IndexSet, visiting: &mut HashSet<&'a PackageName>, - source_maps: &[SourceMap], -) -> Result<()> { + source_map_offsets: &[u32], +) -> Result<(), ResolveErrors> { if order.contains(&pkg.name) { return Ok(()); } - match pkg_details_map.get(&pkg.name) { - Some(pkg_details) => { - let (_, source_maps_index) = pkg_details; - source_maps[*source_maps_index].rewrite_error(|| { - for (i, (dep, _)) in pkg.foreign_deps.iter().enumerate() { - let span = pkg.foreign_dep_spans[i]; - if !visiting.insert(dep) { - bail!(Error::new(span, "package depends on itself")); - } - if let Some(dep) = pkg_details_map.get(dep) { - let (dep_pkg, _) = dep; - visit(dep_pkg, pkg_details_map, order, visiting, source_maps)?; - } - assert!(visiting.remove(dep)); - } - assert!(order.insert(pkg.name.clone())); - Ok(()) - }) + let (_, sm_idx) = pkg_details_map + .get(&pkg.name) + .expect("No pkg_details found for package when doing topological sort"); + let offset = source_map_offsets[*sm_idx]; + for (i, (dep, _)) in pkg.foreign_deps.iter().enumerate() { + let mut span = pkg.foreign_dep_spans[i]; + span.adjust(offset); + if !visiting.insert(dep) { + return Err(ResolveErrors::from(ResolveErrorKind::PackageCycle { + package: dep.clone(), + span, + })); + } + if let Some((dep_pkg, _)) = pkg_details_map.get(dep) { + visit( + dep_pkg, + pkg_details_map, + order, + visiting, + source_map_offsets, + )?; } - None => panic!("No pkg_details found for package when doing topological sort"), + assert!(visiting.remove(dep)); } + assert!(order.insert(pkg.name.clone())); + Ok(()) } impl Resolve { @@ -230,35 +237,18 @@ impl Resolve { Resolve::default() } - /// Parse WIT packages from the input `path`. - /// - /// The input `path` can be one of: - /// - /// * A directory containing a WIT package with an optional `deps` directory - /// for any dependent WIT packages it references. - /// * A single standalone WIT file. - /// * A wasm-encoded WIT package as a single file in the wasm binary format. - /// * A wasm-encoded WIT package as a single file in the wasm text format. - /// - /// In all of these cases packages are allowed to depend on previously - /// inserted packages into this `Resolve`. Resolution for packages is based - /// on the name of each package and reference. - /// - /// This method returns a `PackageId` and additionally a `PackageSourceMap`. - /// The `PackageId` represent the main package that was parsed. For example if a single WIT - /// file was specified this will be the main package found in the file. For a directory this - /// will be all the main package in the directory itself. The `PackageId` value is useful - /// to pass to [`Resolve::select_world`] to take a user-specified world in a - /// conventional fashion and select which to use for bindings generation. + /// Merge `main` and `deps` into this [`Resolve`], topologically sorting + /// them internally. Returns the [`PackageId`] of `main` and a + /// [`PackageSources`] covering all groups. fn sort_unresolved_packages( &mut self, main: UnresolvedPackageGroup, deps: Vec, - ) -> Result<(PackageId, PackageSources)> { - let mut pkg_details_map = BTreeMap::new(); - let mut source_maps = Vec::new(); + ) -> Result<(PackageId, PackageSources), ResolveErrors> { + let mut source_maps: Vec = Vec::new(); + let mut all_packages: Vec<(UnresolvedPackage, usize)> = Vec::new(); - let mut insert = |group: UnresolvedPackageGroup| { + let mut collect = |group: UnresolvedPackageGroup| { let UnresolvedPackageGroup { main, nested, @@ -266,31 +256,45 @@ impl Resolve { } = group; let i = source_maps.len(); source_maps.push(source_map); - for pkg in nested.into_iter().chain([main]) { - let name = pkg.name.clone(); - let my_span = pkg.package_name_span; - let (prev_pkg, prev_i) = match pkg_details_map.insert(name.clone(), (pkg, i)) { - Some(pair) => pair, - None => continue, - }; - let loc1 = source_maps[i].render_location(my_span); - let loc2 = source_maps[prev_i].render_location(prev_pkg.package_name_span); - bail!( - "\ -package {name} is defined in two different locations:\n\ - * {loc1}\n\ - * {loc2}\n\ - " - ) + all_packages.push((pkg, i)); } - Ok(()) }; let main_name = main.main.name.clone(); - insert(main)?; + collect(main); for dep in deps { - insert(dep)?; + collect(dep); + } + + // Merge all source maps into resolve.source_map upfront so that every + // span produced during toposort and duplicate detection is valid in + // resolve.source_map and can be located by rewrite_error below. + // Each group has exactly one source map, so a Vec of offsets suffices. + let source_map_offsets: Vec = source_maps + .iter() + .map(|sm| self.push_source_map(sm.clone())) + .collect(); + + let mut pkg_details_map: BTreeMap = + BTreeMap::new(); + for (pkg, sm_idx) in all_packages { + let name = pkg.name.clone(); + let my_span = pkg.package_name_span; + let offset = source_map_offsets[sm_idx]; + if let Some((prev_pkg, prev_idx)) = pkg_details_map.insert(name.clone(), (pkg, sm_idx)) + { + let prev_offset = source_map_offsets[prev_idx]; + let mut span1 = my_span; + span1.adjust(offset); + let mut span2 = prev_pkg.package_name_span; + span2.adjust(prev_offset); + return Err(ResolveErrors::from(ResolveErrorKind::DuplicatePackage { + name, + span1, + span2, + })); + } } // Perform a simple topological sort which will bail out on cycles @@ -299,39 +303,29 @@ package {name} is defined in two different locations:\n\ let mut order = IndexSet::default(); { let mut visiting = HashSet::new(); - for pkg_details in pkg_details_map.values() { - let (pkg, _) = pkg_details; + for (pkg, _) in pkg_details_map.values() { visit( pkg, &pkg_details_map, &mut order, &mut visiting, - &source_maps, + &source_map_offsets, )?; } } - // Ensure that the final output is topologically sorted. Track which source maps - // have been appended and their byte offsets to avoid duplicating them. let mut package_id_to_source_map_idx = BTreeMap::new(); let mut main_pkg_id = None; - let mut source_map_offsets: HashMap = HashMap::new(); for name in order { - let (pkg, source_map_index) = pkg_details_map.remove(&name).unwrap(); - let source_map = &source_maps[source_map_index]; + let (pkg, sm_idx) = pkg_details_map.remove(&name).unwrap(); + let span_offset = source_map_offsets[sm_idx]; let is_main = pkg.name == main_name; - - // Get or compute the span offset for this source map - let span_offset = *source_map_offsets - .entry(source_map_index) - .or_insert_with(|| self.push_source_map(source_map.clone())); - let id = self.push(pkg, span_offset)?; if is_main { assert!(main_pkg_id.is_none()); main_pkg_id = Some(id); } - package_id_to_source_map_idx.insert(id, source_map_index); + package_id_to_source_map_idx.insert(id, sm_idx); } Ok(( @@ -368,14 +362,14 @@ package {name} is defined in two different locations:\n\ &mut self, mut unresolved: UnresolvedPackage, span_offset: u32, - ) -> Result { + ) -> Result { unresolved.adjust_spans(span_offset); let ret = Remap::default().append(self, unresolved); if ret.is_ok() { #[cfg(debug_assertions)] self.assert_valid(); } - self.source_map.rewrite_error(|| ret) + ret } /// Appends new [`UnresolvedPackageGroup`] to this [`Resolve`], creating a @@ -385,9 +379,48 @@ package {name} is defined in two different locations:\n\ /// will be returned here, if successful a package identifier is returned /// which corresponds to the package that was just inserted. /// - /// The returned [`PackageId`]s are listed in topologically sorted order. - pub fn push_group(&mut self, unresolved_group: UnresolvedPackageGroup) -> Result { - let (pkg_id, _) = self.sort_unresolved_packages(unresolved_group, Vec::new())?; + /// If the package has dependencies that have not yet been pushed into this + /// [`Resolve`], use [`Resolve::push_groups`] instead to pass them all at + /// once and have dependency ordering and cycle detection handled internally. + /// Appends new [`UnresolvedPackageGroup`] to this [`Resolve`], creating a + /// fully resolved package with no dangling references. + /// + /// Any dependency resolution error or otherwise world-elaboration error + /// will be returned here, if successful a package identifier is returned + /// which corresponds to the package that was just inserted. + /// + /// If the package has dependencies that have not yet been pushed into this + /// [`Resolve`], use [`Resolve::push_groups`] instead to pass them all at + /// once and have dependency ordering and cycle detection handled internally. + pub fn push_group( + &mut self, + unresolved_group: UnresolvedPackageGroup, + ) -> anyhow::Result { + self.push_groups(unresolved_group, Vec::new()) + .map_err(|e| anyhow::anyhow!("{}", e.highlight(&self.source_map))) + } + + /// Appends a main [`UnresolvedPackageGroup`] and its dependencies to this + /// [`Resolve`] in a single call, returning a structured [`ResolveErrors`] on + /// failure. + /// + /// This is the preferred alternative to calling [`Resolve::push_group`] + /// repeatedly when you have a package and its local dependencies available + /// as in-memory [`UnresolvedPackageGroup`]s (e.g. from [`SourceMap::parse`] + /// or [`UnresolvedPackageGroup::parse_str`]). Wit-parser sorts them into + /// the correct topological order internally and detects dependency cycles. + /// + /// On error, spans in the returned [`ResolveErrors`] are absolute within + /// `self.source_map` and can be resolved with + /// [`SourceMap::get_location`]. + /// + /// The returned [`PackageId`] corresponds to `main`. + pub fn push_groups( + &mut self, + main: UnresolvedPackageGroup, + deps: Vec, + ) -> Result { + let (pkg_id, _) = self.sort_unresolved_packages(main, deps)?; Ok(pkg_id) } @@ -397,7 +430,7 @@ package {name} is defined in two different locations:\n\ /// 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 { + pub fn push_source(&mut self, path: &str, contents: &str) -> anyhow::Result { self.push_group(UnresolvedPackageGroup::parse_str(path, contents)?) } @@ -464,7 +497,7 @@ package {name} is defined in two different locations:\n\ /// URLs present. If found then it's assumed that both `Resolve` instances /// were originally created from the same contents and are two views /// of the same package. - pub fn merge(&mut self, resolve: Resolve) -> Result { + pub fn merge(&mut self, resolve: Resolve) -> anyhow::Result { log::trace!( "merging {} packages into {} packages", resolve.packages.len(), @@ -519,7 +552,7 @@ package {name} is defined in two different locations:\n\ for (id, mut ty) in types { let new_id = match type_map.get(&id).copied() { Some(id) => { - update_stability(&ty.stability, &mut self.types[id].stability)?; + update_stability(&ty.stability, &mut self.types[id].stability, ty.span)?; id } None => { @@ -538,7 +571,11 @@ package {name} is defined in two different locations:\n\ for (id, mut iface) in interfaces { let new_id = match interface_map.get(&id).copied() { Some(id) => { - update_stability(&iface.stability, &mut self.interfaces[id].stability)?; + update_stability( + &iface.stability, + &mut self.interfaces[id].stability, + iface.span, + )?; id } None => { @@ -557,7 +594,11 @@ package {name} is defined in two different locations:\n\ for (id, mut world) in worlds { let new_id = match world_map.get(&id).copied() { Some(world_id) => { - update_stability(&world.stability, &mut self.worlds[world_id].stability)?; + update_stability( + &world.stability, + &mut self.worlds[world_id].stability, + world.span, + )?; for from_import in world.imports.iter() { Resolve::update_world_imports_stability( from_import, @@ -577,24 +618,25 @@ package {name} is defined in two different locations:\n\ None => { log::debug!("moving world {}", world.name); moved_worlds.push(id); - let mut update = |map: &mut IndexMap| -> Result<_> { - for (mut name, mut item) in mem::take(map) { - remap.update_world_key(&mut name, Default::default())?; - match &mut item { - WorldItem::Function(f) => { - remap.update_function(self, f, Default::default())? - } - WorldItem::Interface { id, .. } => { - *id = remap.map_interface(*id, Default::default())? - } - WorldItem::Type { id, .. } => { - *id = remap.map_type(*id, Default::default())? + let mut update = + |map: &mut IndexMap| -> anyhow::Result<_> { + for (mut name, mut item) in mem::take(map) { + remap.update_world_key(&mut name, Default::default())?; + match &mut item { + WorldItem::Function(f) => { + remap.update_function(self, f, Default::default())? + } + WorldItem::Interface { id, .. } => { + *id = remap.map_interface(*id, Default::default())? + } + WorldItem::Type { id, .. } => { + *id = remap.map_type(*id, Default::default())? + } } + map.insert(name, item); } - map.insert(name, item); - } - Ok(()) - }; + Ok(()) + }; update(&mut world.imports)?; update(&mut world.exports)?; world.adjust_spans(span_offset); @@ -685,7 +727,7 @@ package {name} is defined in two different locations:\n\ from_item: (&WorldKey, &WorldItem), into_items: &mut IndexMap, interface_map: &HashMap, Id>, - ) -> Result<()> { + ) -> anyhow::Result<()> { match from_item.0 { WorldKey::Name(_) => { // No stability info to update here, only updating import/include stability @@ -699,7 +741,7 @@ package {name} is defined in two different locations:\n\ WorldItem::Interface { id: aid, stability: astability, - .. + span: aspan, }, WorldItem::Interface { id: bid, @@ -709,7 +751,7 @@ package {name} is defined in two different locations:\n\ ) => { let aid = interface_map.get(aid).copied().unwrap_or(*aid); assert_eq!(aid, *bid); - update_stability(astability, bstability)?; + update_stability(astability, bstability, *aspan)?; Ok(()) } _ => unreachable!(), @@ -742,7 +784,7 @@ package {name} is defined in two different locations:\n\ from: WorldId, into: WorldId, clone_maps: &mut CloneMaps, - ) -> Result<()> { + ) -> anyhow::Result<()> { let mut new_imports = Vec::new(); let mut new_exports = Vec::new(); @@ -859,7 +901,7 @@ package {name} is defined in two different locations:\n\ Ok(()) } - fn merge_world_item(&self, from: &WorldItem, into: &WorldItem) -> Result<()> { + fn merge_world_item(&self, from: &WorldItem, into: &WorldItem) -> anyhow::Result<()> { let mut map = MergeMap::new(self, self); match (from, into) { (WorldItem::Interface { id: from, .. }, WorldItem::Interface { id: into, .. }) => { @@ -924,7 +966,7 @@ package {name} is defined in two different locations:\n\ name: &WorldKey, item: &WorldItem, must_be_imported: &HashMap, - ) -> Result<()> { + ) -> anyhow::Result<()> { assert!(!into.exports.contains_key(name)); let name = self.name_world_key(name); @@ -956,7 +998,7 @@ package {name} is defined in two different locations:\n\ Ok(()) } - fn ensure_not_exported(&self, world: &World, id: InterfaceId) -> Result<()> { + fn ensure_not_exported(&self, world: &World, id: InterfaceId) -> anyhow::Result<()> { let key = WorldKey::Interface(id); let name = self.name_world_key(&key); if world.exports.contains_key(&key) { @@ -1050,7 +1092,11 @@ package {name} is defined in two different locations:\n\ /// bindings in a context that is importing the original world. This /// is intended to be used as part of language tooling when depending on /// other components. - pub fn importize(&mut self, world_id: WorldId, out_world_name: Option) -> Result<()> { + pub fn importize( + &mut self, + world_id: WorldId, + out_world_name: Option, + ) -> anyhow::Result<()> { // Rename the world to avoid having it get confused with the original // name of the world. Add `-importized` to it for now. Precisely how // this new world is created may want to be updated over time if this @@ -1091,7 +1137,8 @@ package {name} is defined in two different locations:\n\ // Fill out any missing transitive interface imports by elaborating this // world which does that for us. - self.elaborate_world(world_id)?; + let world_span = self.worlds[world_id].span; + self.elaborate_world(world_id, world_span)?; #[cfg(debug_assertions)] self.assert_valid(); @@ -1252,7 +1299,7 @@ package {name} is defined in two different locations:\n\ &self, main_packages: &[PackageId], world: Option<&str>, - ) -> Result { + ) -> anyhow::Result { // Determine if `world` is a kebab-name or an ID. let world_path = match world { Some(world) => Some( @@ -1806,8 +1853,7 @@ package {name} is defined in two different locations:\n\ stability: &Stability, pkg_id: &PackageId, span: Span, - ) -> Result { - let err = |msg: String| -> anyhow::Error { Error::new(span, msg).into() }; + ) -> Result { Ok(match stability { Stability::Unknown => true, // NOTE: deprecations are intentionally omitted -- an existing @@ -1827,22 +1873,28 @@ package {name} is defined in two different locations:\n\ // Use of feature gating with version specifiers inside a // package that is not versioned is not allowed let package_version = p.name.version.as_ref().ok_or_else(|| { - err(format!( - "package [{}] contains a feature gate with a version \ + ResolveErrors::from(ResolveErrorKind::Semantic { + span: span, + message: format!( + "package [{}] contains a feature gate with a version \ specifier, so it must have a version", - p.name - )) + p.name + ), + }) })?; // If the version on the feature gate is: // - released, then we can include it // - unreleased, then we must check the feature (if present) if since > package_version { - return Err(err(format!( - "feature gate cannot reference unreleased version \ + return Err(ResolveErrors::from(ResolveErrorKind::Semantic { + span, + message: format!( + "feature gate cannot reference unreleased version \ {since} of package [{}] (current version {package_version})", - p.name - ))); + p.name + ), + })); } true @@ -1853,19 +1905,6 @@ package {name} is defined in two different locations:\n\ }) } - /// Convenience wrapper around `include_stability` specialized for types - /// with a more targeted error message. - fn include_type(&self, ty: &TypeDef, pkgid: PackageId, span: Span) -> Result { - self.include_stability(&ty.stability, &pkgid, span) - .with_context(|| { - format!( - "failed to process feature gate for type [{}] in package [{}]", - ty.name.as_ref().map(String::as_str).unwrap_or(""), - self.packages[pkgid].name, - ) - }) - } - /// Performs the "elaboration process" necessary for the `world_id` /// specified to ensure that all of its transitive imports are listed. /// @@ -1877,7 +1916,7 @@ package {name} is defined in two different locations:\n\ /// noted on `elaborate_world_exports`. /// /// The world is mutated in-place in this `Resolve`. - fn elaborate_world(&mut self, world_id: WorldId) -> Result<()> { + fn elaborate_world(&mut self, world_id: WorldId, span: Span) -> Result<(), ResolveErrors> { // First process all imports. This is easier than exports since the only // requirement here is that all interfaces need to be added with a // topological order between them. @@ -1982,7 +2021,7 @@ package {name} is defined in two different locations:\n\ } } - self.elaborate_world_exports(&export_interfaces, &mut new_imports, &mut new_exports)?; + self.elaborate_world_exports(&export_interfaces, &mut new_imports, &mut new_exports, span)?; // In addition to sorting at the start of elaboration also sort here at // the end of elaboration to handle types being interspersed with @@ -2075,7 +2114,8 @@ package {name} is defined in two different locations:\n\ export_interfaces: &IndexMap, imports: &mut IndexMap, exports: &mut IndexMap, - ) -> Result<()> { + span: Span, + ) -> Result<(), ResolveErrors> { let mut required_imports = HashSet::new(); for (id, (key, stability)) in export_interfaces.iter() { let name = self.name_world_key(&key); @@ -2091,26 +2131,26 @@ package {name} is defined in two different locations:\n\ stability, ); if !ok { - bail!( - // FIXME: this is not a great error message and basically no - // one will know what to do when it gets printed. Improving - // this error message, however, is a chunk of work that may - // not be best spent doing this at this time, so I'm writing - // this comment instead. - // - // More-or-less what should happen here is that a "path" - // from this interface to the conflicting interface should - // be printed. It should be explained why an import is being - // injected, why that's conflicting with an export, and - // ideally with a suggestion of "add this interface to the - // export list to fix this error". - // - // That's a lot of info that's not easy to get at without - // more refactoring, so it's left to a future date in the - // hopes that most folks won't actually run into this for - // the time being. - InvalidTransitiveDependency(name), - ); + // FIXME: this is not a great error message and basically no + // one will know what to do when it gets printed. Improving + // this error message, however, is a chunk of work that may + // not be best spent doing this at this time, so I'm writing + // this comment instead. + // + // More-or-less what should happen here is that a "path" + // from this interface to the conflicting interface should + // be printed. It should be explained why an import is being + // injected, why that's conflicting with an export, and + // ideally with a suggestion of "add this interface to the + // export list to fix this error". + // + // That's a lot of info that's not easy to get at without + // more refactoring, so it's left to a future date in the + // hopes that most folks won't actually run into this for + // the time being. + return Err(ResolveErrors::from( + ResolveErrorKind::InvalidTransitiveDependency { name, span }, + )); } } return Ok(()); @@ -2185,7 +2225,7 @@ package {name} is defined in two different locations:\n\ /// and 0.2.1 then the result afterwards will be that it imports /// 0.2.1. If, however, 0.3.0 where imported then the final result would /// import both 0.2.0 and 0.3.0. - pub fn merge_world_imports_based_on_semver(&mut self, world_id: WorldId) -> Result<()> { + pub fn merge_world_imports_based_on_semver(&mut self, world_id: WorldId) -> anyhow::Result<()> { let world = &self.worlds[world_id]; // The first pass here is to build a map of "semver tracks" where they @@ -2311,13 +2351,8 @@ package {name} is defined in two different locations:\n\ // modified directly. let ids = self.worlds.iter().map(|(id, _)| id).collect::>(); for world_id in ids { - self.elaborate_world(world_id).with_context(|| { - let name = &self.worlds[world_id].name; - format!( - "failed to elaborate world `{name}` after deduplicating imports \ - based on semver" - ) - })?; + let world_span = self.worlds[world_id].span; + self.elaborate_world(world_id, world_span)?; } #[cfg(debug_assertions)] @@ -2993,7 +3028,12 @@ pub struct Remap { type_has_borrow: Vec>, } -fn apply_map(map: &[Option>], id: Id, desc: &str, span: Span) -> Result> { +fn apply_map( + map: &[Option>], + id: Id, + desc: &str, + span: Span, +) -> Result, ResolveErrors> { match map.get(id.index()) { Some(Some(id)) => Ok(*id), Some(None) => { @@ -3001,7 +3041,10 @@ fn apply_map(map: &[Option>], id: Id, desc: &str, span: Span) -> Res "found a reference to a {desc} which is excluded \ due to its feature not being activated" ); - Err(Error::new(span, msg).into()) + Err(ResolveErrors::from(ResolveErrorKind::Semantic { + span, + message: msg, + })) } None => panic!("request to remap a {desc} that has not yet been registered"), } @@ -3022,38 +3065,57 @@ fn rename(original_name: &str, include_name: &IncludeName) -> Option { } impl Remap { - pub fn map_type(&self, id: TypeId, span: Span) -> Result { + pub fn map_type(&self, id: TypeId, span: Span) -> Result { apply_map(&self.types, id, "type", span) } - pub fn map_interface(&self, id: InterfaceId, span: Span) -> Result { + pub fn map_interface(&self, id: InterfaceId, span: Span) -> Result { apply_map(&self.interfaces, id, "interface", span) } - pub fn map_world(&self, id: WorldId, span: Span) -> Result { + pub fn map_world(&self, id: WorldId, span: Span) -> Result { apply_map(&self.worlds, id, "world", span) } + pub fn map_world_for_type(&self, id: WorldId, span: Span) -> Result { + self.map_world(id, span).map_err(|e| { + ResolveErrors::from(ResolveErrorKind::Semantic { + span, + message: format!("{e}; this type is not gated by a feature but its world is"), + }) + }) + } + + pub fn map_interface_for_type( + &self, + id: InterfaceId, + span: Span, + ) -> Result { + self.map_interface(id, span).map_err(|e| { + ResolveErrors::from(ResolveErrorKind::Semantic { + span, + message: format!("{e}; this type is not gated by a feature but its interface is"), + }) + }) + } + fn append( &mut self, resolve: &mut Resolve, unresolved: UnresolvedPackage, - ) -> Result { + ) -> Result { let pkgid = resolve.packages.alloc(Package { name: unresolved.name.clone(), docs: unresolved.docs.clone(), interfaces: Default::default(), worlds: Default::default(), }); - let prev = resolve.package_names.insert(unresolved.name.clone(), pkgid); - if let Some(prev) = prev { - resolve.package_names.insert(unresolved.name.clone(), prev); - bail!( - "attempting to re-add package `{}` when it's already present in this `Resolve`", - unresolved.name, - ); - } - + assert!( + !resolve.package_names.contains_key(&unresolved.name), + "attempting to re-add package `{}` when it's already present in this `Resolve`", + unresolved.name, + ); + resolve.package_names.insert(unresolved.name.clone(), pkgid); self.process_foreign_deps(resolve, pkgid, &unresolved)?; let foreign_types = self.types.len(); @@ -3067,7 +3129,7 @@ impl Remap { // yet. for (id, mut ty) in unresolved.types.into_iter().skip(foreign_types) { let span = ty.span; - if !resolve.include_type(&ty, pkgid, span)? { + if !resolve.include_stability(&ty.stability, &pkgid, span)? { self.types.push(None); continue; } @@ -3101,20 +3163,7 @@ impl Remap { // referenced along the way. for (id, mut iface) in unresolved.interfaces.into_iter().skip(foreign_interfaces) { let span = iface.span; - if !resolve - .include_stability(&iface.stability, &pkgid, span) - .with_context(|| { - format!( - "failed to process feature gate for interface [{}] in package [{}]", - iface - .name - .as_ref() - .map(String::as_str) - .unwrap_or(""), - resolve.packages[pkgid].name, - ) - })? - { + if !resolve.include_stability(&iface.stability, &pkgid, span)? { self.interfaces.push(None); continue; } @@ -3136,10 +3185,7 @@ impl Remap { let span = resolve.types[id].span; match &mut resolve.types[id].owner { TypeOwner::Interface(iface_id) => { - *iface_id = self.map_interface(*iface_id, span) - .with_context(|| { - "this type is not gated by a feature but its interface is gated by a feature" - })?; + *iface_id = self.map_interface_for_type(*iface_id, span)?; } TypeOwner::World(_) | TypeOwner::None => {} } @@ -3154,15 +3200,7 @@ impl Remap { // here. for (id, mut world) in unresolved.worlds.into_iter().skip(foreign_worlds) { let world_span = world.span; - if !resolve - .include_stability(&world.stability, &pkgid, world_span) - .with_context(|| { - format!( - "failed to process feature gate for world [{}] in package [{}]", - world.name, resolve.packages[pkgid].name, - ) - })? - { + if !resolve.include_stability(&world.stability, &pkgid, world_span)? { self.worlds.push(None); continue; } @@ -3182,10 +3220,7 @@ impl Remap { let span = resolve.types[id].span; match &mut resolve.types[id].owner { TypeOwner::World(world_id) => { - *world_id = self.map_world(*world_id, span) - .with_context(|| { - "this type is not gated by a feature but its interface is gated by a feature" - })?; + *world_id = self.map_world_for_type(*world_id, span)?; } TypeOwner::Interface(_) | TypeOwner::None => {} } @@ -3214,15 +3249,7 @@ impl Remap { self.process_world_includes(id, resolve, &pkgid)?; let world_span = resolve.worlds[id].span; - resolve.elaborate_world(id).with_context(|| { - Error::new( - world_span, - format!( - "failed to elaborate world imports/exports of `{}`", - resolve.worlds[id].name - ), - ) - })?; + resolve.elaborate_world(id, world_span)?; } // Fixup "parent" ids now that everything has been identified @@ -3258,7 +3285,7 @@ impl Remap { resolve: &mut Resolve, pkgid: PackageId, unresolved: &UnresolvedPackage, - ) -> Result<()> { + ) -> Result<(), ResolveErrors> { // Invert the `foreign_deps` map to be keyed by world id to get // used in the loops below. let mut world_to_package = HashMap::new(); @@ -3310,10 +3337,12 @@ impl Remap { match resolve.types[id].kind { TypeDefKind::Type(Type::Id(i)) => id = i, TypeDefKind::Resource => break, - _ => bail!(Error::new( - *span, - format!("type used in a handle must be a resource"), - )), + _ => { + return Err(ResolveErrors::from(ResolveErrorKind::Semantic { + span: *span, + message: format!("type used in a handle must be a resource"), + })); + } } } } @@ -3330,7 +3359,7 @@ impl Remap { interface_to_package: &HashMap)>, resolve: &mut Resolve, parent_pkg_id: &PackageId, - ) -> Result<(), anyhow::Error> { + ) -> Result<(), ResolveErrors> { for (unresolved_iface_id, unresolved_iface) in unresolved.interfaces.iter() { let (pkg_name, interface, span, stabilities) = match interface_to_package.get(&unresolved_iface_id) { @@ -3346,11 +3375,11 @@ impl Remap { .get(pkg_name) .copied() .ok_or_else(|| { - PackageNotFoundError::new( + ResolveErrors::from(ResolveErrorKind::PackageNotFound { span, - pkg_name.clone(), - resolve.package_names.keys().cloned().collect(), - ) + requested: pkg_name.clone(), + known: resolve.package_names.keys().cloned().collect(), + }) })?; // Functions can't be imported so this should be empty. @@ -3372,11 +3401,12 @@ impl Remap { continue; } - let iface_id = pkg - .interfaces - .get(interface) - .copied() - .ok_or_else(|| Error::new(iface_span, "interface not found in package"))?; + let iface_id = pkg.interfaces.get(interface).copied().ok_or_else(|| { + ResolveErrors::from(ResolveErrorKind::Semantic { + span: iface_span, + message: "interface not found in package".to_owned(), + }) + })?; assert_eq!(self.interfaces.len(), unresolved_iface_id.index()); self.interfaces.push(Some(iface_id)); } @@ -3395,7 +3425,7 @@ impl Remap { world_to_package: &HashMap)>, resolve: &mut Resolve, parent_pkg_id: &PackageId, - ) -> Result<(), anyhow::Error> { + ) -> Result<(), ResolveErrors> { for (unresolved_world_id, unresolved_world) in unresolved.worlds.iter() { let (pkg_name, world, span, stabilities) = match world_to_package.get(&unresolved_world_id) { @@ -3409,7 +3439,13 @@ impl Remap { .package_names .get(pkg_name) .copied() - .ok_or_else(|| Error::new(span, "package not found"))?; + .ok_or_else(|| { + ResolveErrors::from(ResolveErrorKind::PackageNotFound { + span, + requested: pkg_name.clone(), + known: resolve.package_names.keys().cloned().collect(), + }) + })?; let pkg = &resolve.packages[pkgid]; let world_span = unresolved_world.span; @@ -3426,11 +3462,12 @@ impl Remap { continue; } - let world_id = pkg - .worlds - .get(world) - .copied() - .ok_or_else(|| Error::new(world_span, "world not found in package"))?; + let world_id = pkg.worlds.get(world).copied().ok_or_else(|| { + ResolveErrors::from(ResolveErrorKind::Semantic { + span: world_span, + message: "world not found in package".to_owned(), + }) + })?; assert_eq!(self.worlds.len(), unresolved_world_id.index()); self.worlds.push(Some(world_id)); } @@ -3448,7 +3485,7 @@ impl Remap { unresolved: &UnresolvedPackage, pkgid: PackageId, resolve: &mut Resolve, - ) -> Result<(), anyhow::Error> { + ) -> Result<(), ResolveErrors> { for (unresolved_type_id, unresolved_ty) in unresolved.types.iter() { // All "Unknown" types should appear first so once we're no longer // in unknown territory it's package-defined types so break out of @@ -3459,7 +3496,7 @@ impl Remap { } let span = unresolved_ty.span; - if !resolve.include_type(unresolved_ty, pkgid, span)? { + if !resolve.include_stability(&unresolved_ty.stability, &pkgid, span)? { self.types.push(None); continue; } @@ -3475,7 +3512,10 @@ impl Remap { .types .get(name) .ok_or_else(|| { - Error::new(span, format!("type `{name}` not defined in interface")) + ResolveErrors::from(ResolveErrorKind::Semantic { + span: span, + message: format!("type `{name}` not defined in interface"), + }) })?; assert_eq!(self.types.len(), unresolved_type_id.index()); self.types.push(Some(type_id)); @@ -3493,7 +3533,7 @@ impl Remap { resolve: &mut Resolve, ty: &mut TypeDef, span: Span, - ) -> Result<()> { + ) -> Result<(), ResolveErrors> { // NB: note that `ty.owner` is not updated here since interfaces // haven't been mapped yet and that's done in a separate step. use crate::TypeDefKind::*; @@ -3506,8 +3546,7 @@ impl Remap { Resource => {} Record(r) => { for field in r.fields.iter_mut() { - self.update_ty(resolve, &mut field.ty, span) - .with_context(|| format!("failed to update field `{}`", field.name))?; + self.update_ty(resolve, &mut field.ty, span)? } } Tuple(t) => { @@ -3556,7 +3595,12 @@ impl Remap { Ok(()) } - fn update_ty(&mut self, resolve: &mut Resolve, ty: &mut Type, span: Span) -> Result<()> { + fn update_ty( + &mut self, + resolve: &mut Resolve, + ty: &mut Type, + span: Span, + ) -> Result<(), ResolveErrors> { let id = match ty { Type::Id(id) => id, _ => return Ok(()), @@ -3591,12 +3635,16 @@ impl Remap { Ok(()) } - fn update_type_id(&self, id: &mut TypeId, span: Span) -> Result<()> { + fn update_type_id(&self, id: &mut TypeId, span: Span) -> Result<(), ResolveErrors> { *id = self.map_type(*id, span)?; Ok(()) } - fn update_interface(&mut self, resolve: &mut Resolve, iface: &mut Interface) -> Result<()> { + fn update_interface( + &mut self, + resolve: &mut Resolve, + iface: &mut Interface, + ) -> Result<(), ResolveErrors> { iface.types.retain(|_, ty| self.types[ty.index()].is_some()); let iface_pkg_id = iface.package.as_ref().unwrap_or_else(|| { panic!( @@ -3614,21 +3662,12 @@ impl Remap { for (_name, ty) in iface.types.iter_mut() { self.update_type_id(ty, iface.span)?; } - for (func_name, func) in iface.functions.iter_mut() { + for (_, func) in iface.functions.iter_mut() { let span = func.span; - if !resolve - .include_stability(&func.stability, iface_pkg_id, span) - .with_context(|| { - format!( - "failed to process feature gate for function [{func_name}] in package [{}]", - resolve.packages[*iface_pkg_id].name, - ) - })? - { + if !resolve.include_stability(&func.stability, iface_pkg_id, span)? { continue; } - self.update_function(resolve, func, span) - .with_context(|| format!("failed to update function `{}`", func.name))?; + self.update_function(resolve, func, span)? } // Filter out all of the existing functions in interface which fail the @@ -3647,7 +3686,7 @@ impl Remap { resolve: &mut Resolve, func: &mut Function, span: Span, - ) -> Result<()> { + ) -> Result<(), ResolveErrors> { if let Some(id) = func.kind.resource_mut() { self.update_type_id(id, span)?; } @@ -3660,13 +3699,13 @@ impl Remap { if let Some(ty) = &func.result { if self.type_has_borrow(resolve, ty) { - bail!(Error::new( + return Err(ResolveErrors::from(ResolveErrorKind::Semantic { span, - format!( + message: format!( "function returns a type which contains \ a `borrow` which is not supported" - ) - )) + ), + })); } } @@ -3678,7 +3717,7 @@ impl Remap { world: &mut World, resolve: &mut Resolve, pkg_id: &PackageId, - ) -> Result<()> { + ) -> Result<(), ResolveErrors> { // Rewrite imports/exports with their updated versions. Note that this // may involve updating the key of the imports/exports maps so this // starts by emptying them out and then everything is re-inserted. @@ -3694,10 +3733,7 @@ impl Remap { *id = self.map_type(*id, span)?; } let stability = item.stability(resolve); - if !resolve - .include_stability(stability, pkg_id, span) - .with_context(|| format!("failed to process world item in `{}`", world.name))? - { + if !resolve.include_stability(stability, pkg_id, span)? { continue; } self.update_world_key(&mut name, span)?; @@ -3730,22 +3766,13 @@ impl Remap { id: WorldId, resolve: &mut Resolve, pkg_id: &PackageId, - ) -> Result<()> { + ) -> Result<(), ResolveErrors> { let world = &mut resolve.worlds[id]; // Resolve all `include` statements of the world which will add more // entries to the imports/exports list for this world. let includes = mem::take(&mut world.includes); for include in includes { - if !resolve - .include_stability(&include.stability, pkg_id, include.span) - .with_context(|| { - format!( - "failed to process feature gate for included world [{}] in package [{}]", - resolve.worlds[include.id].name.as_str(), - resolve.packages[*pkg_id].name - ) - })? - { + if !resolve.include_stability(&include.stability, pkg_id, include.span)? { continue; } self.resolve_include( @@ -3767,47 +3794,55 @@ impl Remap { /// Validates that a world's imports and exports don't have case-insensitive /// duplicate names. Per the WIT specification, kebab-case identifiers are /// case-insensitive within the same scope. - fn validate_world_case_insensitive_names(resolve: &Resolve, world_id: WorldId) -> Result<()> { + fn validate_world_case_insensitive_names( + resolve: &Resolve, + world_id: WorldId, + ) -> Result<(), ResolveErrors> { let world = &resolve.worlds[world_id]; // Helper closure to check for case-insensitive duplicates in a map - let validate_names = |items: &IndexMap, - item_type: &str| - -> Result<()> { - let mut seen_lowercase: HashMap = HashMap::new(); - - for key in items.keys() { - // Only WorldKey::Name variants can have case-insensitive conflicts - if let WorldKey::Name(name) = key { - let lowercase_name = name.to_lowercase(); - - if let Some(existing_name) = seen_lowercase.get(&lowercase_name) { - // Only error on case-insensitive duplicates (e.g., "foo" vs "FOO"). - // Exact duplicates would have been caught earlier. - if existing_name != name { - bail!( - "{item_type} `{name}` conflicts with {item_type} `{existing_name}` \ - (kebab-case identifiers are case-insensitive)" - ); + let validate_names = + |items: &IndexMap, item_type: &str| -> Result<(), ResolveErrors> { + let mut seen_lowercase: HashMap = HashMap::new(); + + for key in items.keys() { + // Only WorldKey::Name variants can have case-insensitive conflicts + if let WorldKey::Name(name) = key { + let lowercase_name = name.to_lowercase(); + + if let Some(existing_name) = seen_lowercase.get(&lowercase_name) { + // Only error on case-insensitive duplicates (e.g., "foo" vs "FOO"). + // Exact duplicates would have been caught earlier. + if existing_name != name { + // TODO: `WorldKey::Name` does not carry a `Span`, so we + // cannot point at the conflicting item. Add a span to + // `WorldKey::Name` to improve this error. + return Err(ResolveErrors::from(ResolveErrorKind::Semantic { + span: Span::default(), + message: format!( + "{item_type} `{name}` in world `{}` conflicts with \ + {item_type} `{existing_name}` \ + (kebab-case identifiers are case-insensitive)", + world.name, + ), + })); + } } - } - seen_lowercase.insert(lowercase_name, name.clone()); + seen_lowercase.insert(lowercase_name, name.clone()); + } } - } - Ok(()) - }; + Ok(()) + }; - validate_names(&world.imports, "import") - .with_context(|| format!("failed to validate imports in world `{}`", world.name))?; - validate_names(&world.exports, "export") - .with_context(|| format!("failed to validate exports in world `{}`", world.name))?; + validate_names(&world.imports, "import")?; + validate_names(&world.exports, "export")?; Ok(()) } - fn update_world_key(&self, key: &mut WorldKey, span: Span) -> Result<()> { + fn update_world_key(&self, key: &mut WorldKey, span: Span) -> Result<(), ResolveErrors> { match key { WorldKey::Name(_) => {} WorldKey::Interface(id) => { @@ -3825,7 +3860,7 @@ impl Remap { span: Span, pkg_id: &PackageId, resolve: &mut Resolve, - ) -> Result<()> { + ) -> Result<(), ResolveErrors> { let world = &resolve.worlds[id]; let include_world_id = self.map_world(include_world_id_orig, span)?; let include_world = resolve.worlds[include_world_id].clone(); @@ -3840,13 +3875,13 @@ impl Remap { self.remove_matching_name(export, &mut names_); } if !names_.is_empty() { - bail!(Error::new( + return Err(ResolveErrors::from(ResolveErrorKind::Semantic { span, - format!( + message: format!( "no import or export kebab-name `{}`. Note that an ID does not support renaming", names_[0].name ), - )); + })); } let mut maps = Default::default(); @@ -3899,7 +3934,7 @@ impl Remap { span: Span, item_type: &str, is_external_include: bool, - ) -> Result<()> { + ) -> Result<(), ResolveErrors> { match item.0 { WorldKey::Name(n) => { let n = names @@ -3923,10 +3958,12 @@ impl Remap { let prev = get_items(cloner.resolve).insert(key, new_item); if prev.is_some() { - bail!(Error::new( + return Err(ResolveErrors::from(ResolveErrorKind::Semantic { span, - format!("{item_type} of `{n}` shadows previously {item_type}ed items"), - )) + message: format!( + "{item_type} of `{n}` shadows previously {item_type}ed items" + ), + })); } } key @ WorldKey::Interface(_) => { @@ -3938,7 +3975,7 @@ impl Remap { WorldItem::Interface { id: aid, stability: astability, - .. + span: aspan, }, WorldItem::Interface { id: bid, @@ -3947,7 +3984,12 @@ impl Remap { }, ) => { assert_eq!(*aid, *bid); - merge_include_stability(astability, bstability, is_external_include)?; + merge_include_stability( + astability, + bstability, + is_external_include, + *aspan, + )?; } (WorldItem::Interface { .. }, _) => unreachable!(), (WorldItem::Function(_), _) => unreachable!(), @@ -4070,7 +4112,7 @@ impl<'a> MergeMap<'a> { } } - fn build(&mut self) -> Result<()> { + fn build(&mut self) -> anyhow::Result<()> { for from_id in self.from.topological_packages() { let from = &self.from.packages[from_id]; let into_id = match self.into.package_names.get(&from.name) { @@ -4093,7 +4135,7 @@ impl<'a> MergeMap<'a> { Ok(()) } - fn build_package(&mut self, from_id: PackageId, into_id: PackageId) -> Result<()> { + fn build_package(&mut self, from_id: PackageId, into_id: PackageId) -> anyhow::Result<()> { let prev = self.package_map.insert(from_id, into_id); assert!(prev.is_none()); @@ -4138,7 +4180,11 @@ impl<'a> MergeMap<'a> { Ok(()) } - fn build_interface(&mut self, from_id: InterfaceId, into_id: InterfaceId) -> Result<()> { + fn build_interface( + &mut self, + from_id: InterfaceId, + into_id: InterfaceId, + ) -> anyhow::Result<()> { let prev = self.interface_map.insert(from_id, into_id); assert!(prev.is_none()); @@ -4182,7 +4228,7 @@ impl<'a> MergeMap<'a> { Ok(()) } - fn build_type_id(&mut self, from_id: TypeId, into_id: TypeId) -> Result<()> { + fn build_type_id(&mut self, from_id: TypeId, into_id: TypeId) -> anyhow::Result<()> { // FIXME: ideally the types should be "structurally // equal" but that's not trivial to do in the face of // resources. @@ -4191,7 +4237,7 @@ impl<'a> MergeMap<'a> { Ok(()) } - fn build_type(&mut self, from_ty: &Type, into_ty: &Type) -> Result<()> { + fn build_type(&mut self, from_ty: &Type, into_ty: &Type) -> anyhow::Result<()> { match (from_ty, into_ty) { (Type::Id(from), Type::Id(into)) => { self.build_type_id(*from, *into)?; @@ -4202,7 +4248,7 @@ impl<'a> MergeMap<'a> { Ok(()) } - fn build_function(&mut self, from_func: &Function, into_func: &Function) -> Result<()> { + fn build_function(&mut self, from_func: &Function, into_func: &Function) -> anyhow::Result<()> { if from_func.name != into_func.name { bail!( "different function names `{}` and `{}`", @@ -4264,7 +4310,7 @@ impl<'a> MergeMap<'a> { Ok(()) } - fn build_world(&mut self, from_id: WorldId, into_id: WorldId) -> Result<()> { + fn build_world(&mut self, from_id: WorldId, into_id: WorldId) -> anyhow::Result<()> { let prev = self.world_map.insert(from_id, into_id); assert!(prev.is_none()); @@ -4323,7 +4369,7 @@ impl<'a> MergeMap<'a> { } } - fn match_world_item(&mut self, from: &WorldItem, into: &WorldItem) -> Result<()> { + fn match_world_item(&mut self, from: &WorldItem, into: &WorldItem) -> anyhow::Result<()> { match (from, into) { (WorldItem::Interface { id: from, .. }, WorldItem::Interface { id: into, .. }) => { match ( @@ -4373,7 +4419,11 @@ impl<'a> MergeMap<'a> { /// This is done to keep up-to-date stability information if possible. /// Components for example don't carry stability information but WIT does so /// this tries to move from "unknown" to stable/unstable if possible. -fn update_stability(from: &Stability, into: &mut Stability) -> Result<()> { +fn update_stability( + from: &Stability, + into: &mut Stability, + span: Span, +) -> Result<(), ResolveErrors> { // If `from` is unknown or the two stability annotations are equal then // there's nothing to do here. if from == into || from.is_unknown() { @@ -4388,56 +4438,33 @@ fn update_stability(from: &Stability, into: &mut Stability) -> Result<()> { // Failing all that this means that the two attributes are different so // generate an error. - bail!("mismatch in stability from '{:?}' to '{:?}'", from, into) + Err(ResolveErrors::from(ResolveErrorKind::Semantic { + span, + message: format!("mismatch in stability from '{from:?}' to '{into:?}'"), + })) } fn merge_include_stability( from: &Stability, into: &mut Stability, is_external_include: bool, -) -> Result<()> { + span: Span, +) -> Result<(), ResolveErrors> { if is_external_include && from.is_stable() { log::trace!("dropped stability from external package"); *into = Stability::Unknown; return Ok(()); } - return update_stability(from, into); -} - -/// An error that can be returned during "world elaboration" during various -/// [`Resolve`] operations. -/// -/// Methods on [`Resolve`] which mutate its internals, such as -/// [`Resolve::push_dir`] or [`Resolve::importize`] can fail if `world` imports -/// in WIT packages are invalid. This error indicates one of these situations -/// where an invalid dependency graph between imports and exports are detected. -/// -/// Note that at this time this error is subtle and not easy to understand, and -/// work needs to be done to explain this better and additionally provide a -/// better error message. For now though this type enables callers to test for -/// the exact kind of error emitted. -#[derive(Debug, Clone)] -pub struct InvalidTransitiveDependency(String); - -impl fmt::Display for InvalidTransitiveDependency { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!( - f, - "interface `{}` transitively depends on an interface in \ - incompatible ways", - self.0 - ) - } + update_stability(from, into, span) } -impl core::error::Error for InvalidTransitiveDependency {} - #[cfg(test)] mod tests { use crate::alloc::format; use crate::alloc::string::ToString; - use crate::{Resolve, WorldItem, WorldKey}; + use crate::alloc::vec; + use crate::{Resolve, UnresolvedPackageGroup, WorldItem, WorldKey}; use anyhow::Result; #[test] @@ -5497,6 +5524,48 @@ interface iface { Ok(()) } + #[test] + fn push_groups_resolves_dep_before_main() -> Result<()> { + // push_groups must topologically sort main + deps internally and succeed + // even when the dep is listed after main in the caller's mental model. + let dep = UnresolvedPackageGroup::parse_str( + "file:///dep.wit", + "package foo:dep;\ninterface i { type t = u32; }", + )?; + let main = UnresolvedPackageGroup::parse_str( + "file:///main.wit", + "package foo:main;\ninterface j { use foo:dep/i.{t}; type u = t; }", + )?; + let mut resolve = Resolve::default(); + resolve.push_groups(main, vec![dep])?; + assert_eq!(resolve.packages.len(), 2); + Ok(()) + } + + #[test] + fn push_groups_cycle_error_contains_location() { + // A cross-group cycle must produce an error message with a file URI and + // line/col. This validates that source maps are merged into resolve.source_map + // *before* toposort runs, so the span in the cycle error is resolvable. + let a = UnresolvedPackageGroup::parse_str( + "file:///a.wit", + "package foo:a;\ninterface i { use foo:b/j.{}; }", + ) + .unwrap(); + let b = UnresolvedPackageGroup::parse_str( + "file:///b.wit", + "package foo:b;\ninterface j { use foo:a/i.{}; }", + ) + .unwrap(); + let mut resolve = Resolve::default(); + let err = resolve.push_groups(a, vec![b]).unwrap_err(); + let msg = err.highlight(&resolve.source_map); + assert!( + msg.contains("file:///"), + "cycle error should contain a file URI, got: {msg}" + ); + } + #[test] fn param_spans_preserved_through_merge() -> Result<()> { let mut resolve1 = Resolve::default(); 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-gate3.wit.result b/crates/wit-parser/tests/ui/parse-fail/bad-gate3.wit.result index 181a55f67e..6838ae3369 100644 --- a/crates/wit-parser/tests/ui/parse-fail/bad-gate3.wit.result +++ b/crates/wit-parser/tests/ui/parse-fail/bad-gate3.wit.result @@ -1,4 +1,4 @@ -this type is not gated by a feature but its interface is gated by a feature: found a reference to a interface which is excluded due to its feature not being activated +found a reference to a interface which is excluded due to its feature not being activated; this type is not gated by a feature but its interface is --> tests/ui/parse-fail/bad-gate3.wit:5:8 | 5 | type a = u32; diff --git a/crates/wit-parser/tests/ui/parse-fail/bad-gate4.wit.result b/crates/wit-parser/tests/ui/parse-fail/bad-gate4.wit.result index 956ba063aa..3558d373be 100644 --- a/crates/wit-parser/tests/ui/parse-fail/bad-gate4.wit.result +++ b/crates/wit-parser/tests/ui/parse-fail/bad-gate4.wit.result @@ -1,4 +1,4 @@ -failed to update function `[constructor]a`: found a reference to a type which is excluded due to its feature not being activated +found a reference to a type which is excluded due to its feature not being activated --> tests/ui/parse-fail/bad-gate4.wit:6:5 | 6 | constructor(); diff --git a/crates/wit-parser/tests/ui/parse-fail/bad-gate5.wit.result b/crates/wit-parser/tests/ui/parse-fail/bad-gate5.wit.result index 6c36fb3f80..ad28d61c66 100644 --- a/crates/wit-parser/tests/ui/parse-fail/bad-gate5.wit.result +++ b/crates/wit-parser/tests/ui/parse-fail/bad-gate5.wit.result @@ -1,4 +1,4 @@ -failed to update function `[static]a.x`: found a reference to a type which is excluded due to its feature not being activated +found a reference to a type which is excluded due to its feature not being activated --> tests/ui/parse-fail/bad-gate5.wit:9:5 | 9 | x: static func(); 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 d4c634eaf4..ccbe1bb3d2 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,4 +1,4 @@ -interface or world `non-existance` not found in package +interface or world `non-existance` does not exist --> tests/ui/parse-fail/bad-include1.wit:4:11 | 4 | include non-existance; 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/bad-pkg6.wit.result b/crates/wit-parser/tests/ui/parse-fail/bad-pkg6.wit.result index 0adea11b98..96d0344722 100644 --- a/crates/wit-parser/tests/ui/parse-fail/bad-pkg6.wit.result +++ b/crates/wit-parser/tests/ui/parse-fail/bad-pkg6.wit.result @@ -1,7 +1,6 @@ failed to resolve directory while parsing WIT for path [tests/ui/parse-fail/bad-pkg6]: package 'foo:bar' not found. known packages: foo:baz foo:foo - --> tests/ui/parse-fail/bad-pkg6/root.wit:3:7 | 3 | use foo:bar/baz.{}; diff --git a/crates/wit-parser/tests/ui/parse-fail/case-insensitive-duplicates.wit.result b/crates/wit-parser/tests/ui/parse-fail/case-insensitive-duplicates.wit.result index d46da42b70..e48535d03f 100644 --- a/crates/wit-parser/tests/ui/parse-fail/case-insensitive-duplicates.wit.result +++ b/crates/wit-parser/tests/ui/parse-fail/case-insensitive-duplicates.wit.result @@ -1 +1 @@ -failed to validate exports in world `example`: export `GET-USER` conflicts with export `get-user` (kebab-case identifiers are case-insensitive) \ No newline at end of file +export `GET-USER` in world `example` conflicts with export `get-user` (kebab-case identifiers are case-insensitive) \ No newline at end of file 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/import-and-export1.wit.result b/crates/wit-parser/tests/ui/parse-fail/import-and-export1.wit.result index 2642cf4c47..bfbc7a17dc 100644 --- a/crates/wit-parser/tests/ui/parse-fail/import-and-export1.wit.result +++ b/crates/wit-parser/tests/ui/parse-fail/import-and-export1.wit.result @@ -1,5 +1,5 @@ -failed to elaborate world imports/exports of `test` +interface `foo:foo/i3` transitively depends on an interface in incompatible ways --> tests/ui/parse-fail/import-and-export1.wit:12:7 | 12 | world test { - | ^---: interface `foo:foo/i3` transitively depends on an interface in incompatible ways \ No newline at end of file + | ^--- \ No newline at end of file diff --git a/crates/wit-parser/tests/ui/parse-fail/import-and-export2.wit.result b/crates/wit-parser/tests/ui/parse-fail/import-and-export2.wit.result index 76406d791a..19f11b9db9 100644 --- a/crates/wit-parser/tests/ui/parse-fail/import-and-export2.wit.result +++ b/crates/wit-parser/tests/ui/parse-fail/import-and-export2.wit.result @@ -1,5 +1,5 @@ -failed to elaborate world imports/exports of `baz` +interface `anon` transitively depends on an interface in incompatible ways --> tests/ui/parse-fail/import-and-export2.wit:11:7 | 11 | world baz { - | ^--: interface `anon` transitively depends on an interface in incompatible ways \ No newline at end of file + | ^-- \ No newline at end of file diff --git a/crates/wit-parser/tests/ui/parse-fail/import-and-export3.wit.result b/crates/wit-parser/tests/ui/parse-fail/import-and-export3.wit.result index 857a927999..89a8ecdd70 100644 --- a/crates/wit-parser/tests/ui/parse-fail/import-and-export3.wit.result +++ b/crates/wit-parser/tests/ui/parse-fail/import-and-export3.wit.result @@ -1,5 +1,5 @@ -failed to elaborate world imports/exports of `test` +interface `foo:foo/i3` transitively depends on an interface in incompatible ways --> tests/ui/parse-fail/import-and-export3.wit:33:7 | 33 | world test { - | ^---: interface `foo:foo/i3` transitively depends on an interface in incompatible ways \ No newline at end of file + | ^--- \ No newline at end of file diff --git a/crates/wit-parser/tests/ui/parse-fail/import-and-export4.wit.result b/crates/wit-parser/tests/ui/parse-fail/import-and-export4.wit.result index 9028ce7324..a7ab331087 100644 --- a/crates/wit-parser/tests/ui/parse-fail/import-and-export4.wit.result +++ b/crates/wit-parser/tests/ui/parse-fail/import-and-export4.wit.result @@ -1,5 +1,5 @@ -failed to elaborate world imports/exports of `test` +interface `foo:foo/i3` transitively depends on an interface in incompatible ways --> tests/ui/parse-fail/import-and-export4.wit:40:7 | 40 | world test { - | ^---: interface `foo:foo/i3` transitively depends on an interface in incompatible ways \ No newline at end of file + | ^--- \ No newline at end of file diff --git a/crates/wit-parser/tests/ui/parse-fail/import-and-export5.wit.result b/crates/wit-parser/tests/ui/parse-fail/import-and-export5.wit.result index 4bb5face1c..460634730e 100644 --- a/crates/wit-parser/tests/ui/parse-fail/import-and-export5.wit.result +++ b/crates/wit-parser/tests/ui/parse-fail/import-and-export5.wit.result @@ -1,5 +1,5 @@ -failed to elaborate world imports/exports of `w` +interface `anon` transitively depends on an interface in incompatible ways --> tests/ui/parse-fail/import-and-export5.wit:12:7 | 12 | world w { - | ^: interface `anon` transitively depends on an interface in incompatible ways \ No newline at end of file + | ^ \ No newline at end of file diff --git a/crates/wit-parser/tests/ui/parse-fail/multi-package-deps-share-nest.wit.result b/crates/wit-parser/tests/ui/parse-fail/multi-package-deps-share-nest.wit.result index 053a98b163..8c31ec8689 100644 --- a/crates/wit-parser/tests/ui/parse-fail/multi-package-deps-share-nest.wit.result +++ b/crates/wit-parser/tests/ui/parse-fail/multi-package-deps-share-nest.wit.result @@ -1,3 +1,3 @@ -failed to resolve directory while parsing WIT for path [tests/ui/parse-fail/multi-package-deps-share-nest]: package foo:shared is defined in two different locations: -* tests/ui/parse-fail/multi-package-deps-share-nest/deps/dep2/types.wit:3:9 -* tests/ui/parse-fail/multi-package-deps-share-nest/deps/dep1/types.wit:3:9 \ No newline at end of file +failed to resolve directory while parsing WIT for path [tests/ui/parse-fail/multi-package-deps-share-nest]: package `foo:shared` is defined in two different locations: + * tests/ui/parse-fail/multi-package-deps-share-nest/deps/dep2/types.wit:3:9 + * tests/ui/parse-fail/multi-package-deps-share-nest/deps/dep1/types.wit:3:9 \ No newline at end of file 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/multiple-package-inline-cycle.wit.result b/crates/wit-parser/tests/ui/parse-fail/multiple-package-inline-cycle.wit.result index 420ca84d72..ebbbaeac33 100644 --- a/crates/wit-parser/tests/ui/parse-fail/multiple-package-inline-cycle.wit.result +++ b/crates/wit-parser/tests/ui/parse-fail/multiple-package-inline-cycle.wit.result @@ -1,4 +1,4 @@ -package depends on itself +package `foo:qux` creates a dependency cycle --> tests/ui/parse-fail/multiple-package-inline-cycle.wit:4:9 | 4 | use foo:qux/i.{}; diff --git a/crates/wit-parser/tests/ui/parse-fail/nested-packages-colliding-names.wit.result b/crates/wit-parser/tests/ui/parse-fail/nested-packages-colliding-names.wit.result index 1376351db3..156887fc0a 100644 --- a/crates/wit-parser/tests/ui/parse-fail/nested-packages-colliding-names.wit.result +++ b/crates/wit-parser/tests/ui/parse-fail/nested-packages-colliding-names.wit.result @@ -1,3 +1,3 @@ -package foo:name is defined in two different locations: -* tests/ui/parse-fail/nested-packages-colliding-names.wit:5:9 -* tests/ui/parse-fail/nested-packages-colliding-names.wit:3:9 \ No newline at end of file +package `foo:name` is defined in two different locations: + * tests/ui/parse-fail/nested-packages-colliding-names.wit:5:9 + * tests/ui/parse-fail/nested-packages-colliding-names.wit:3:9 \ No newline at end of file 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/pkg-cycle.wit.result b/crates/wit-parser/tests/ui/parse-fail/pkg-cycle.wit.result index 250e158141..233e0cc79e 100644 --- a/crates/wit-parser/tests/ui/parse-fail/pkg-cycle.wit.result +++ b/crates/wit-parser/tests/ui/parse-fail/pkg-cycle.wit.result @@ -1,4 +1,4 @@ -failed to resolve directory while parsing WIT for path [tests/ui/parse-fail/pkg-cycle]: package depends on itself +failed to resolve directory while parsing WIT for path [tests/ui/parse-fail/pkg-cycle]: package `foo:a1` creates a dependency cycle --> tests/ui/parse-fail/pkg-cycle/deps/a1/root.wit:3:7 | 3 | use foo:a1/foo.{}; diff --git a/crates/wit-parser/tests/ui/parse-fail/pkg-cycle2.wit.result b/crates/wit-parser/tests/ui/parse-fail/pkg-cycle2.wit.result index ec10e18c27..b890772931 100644 --- a/crates/wit-parser/tests/ui/parse-fail/pkg-cycle2.wit.result +++ b/crates/wit-parser/tests/ui/parse-fail/pkg-cycle2.wit.result @@ -1,4 +1,4 @@ -failed to resolve directory while parsing WIT for path [tests/ui/parse-fail/pkg-cycle2]: package depends on itself +failed to resolve directory while parsing WIT for path [tests/ui/parse-fail/pkg-cycle2]: package `foo:a2` creates a dependency cycle --> tests/ui/parse-fail/pkg-cycle2/deps/a1/root.wit:3:7 | 3 | use foo:a2/foo.{}; diff --git a/crates/wit-parser/tests/ui/parse-fail/return-borrow1.wit.result b/crates/wit-parser/tests/ui/parse-fail/return-borrow1.wit.result index a4ddb59f1a..aa7dd50790 100644 --- a/crates/wit-parser/tests/ui/parse-fail/return-borrow1.wit.result +++ b/crates/wit-parser/tests/ui/parse-fail/return-borrow1.wit.result @@ -1,4 +1,4 @@ -failed to update function `x`: function returns a type which contains a `borrow` which is not supported +function returns a type which contains a `borrow` which is not supported --> tests/ui/parse-fail/return-borrow1.wit:6:3 | 6 | x: func() -> borrow; diff --git a/crates/wit-parser/tests/ui/parse-fail/return-borrow2.wit.result b/crates/wit-parser/tests/ui/parse-fail/return-borrow2.wit.result index 01c7f6dad1..d29f0ee7aa 100644 --- a/crates/wit-parser/tests/ui/parse-fail/return-borrow2.wit.result +++ b/crates/wit-parser/tests/ui/parse-fail/return-borrow2.wit.result @@ -1,4 +1,4 @@ -failed to update function `[method]y.x`: function returns a type which contains a `borrow` which is not supported +function returns a type which contains a `borrow` which is not supported --> tests/ui/parse-fail/return-borrow2.wit:5:5 | 5 | x: func() -> borrow; diff --git a/crates/wit-parser/tests/ui/parse-fail/return-borrow6.wit.result b/crates/wit-parser/tests/ui/parse-fail/return-borrow6.wit.result index e1264b574d..4c0f86ab16 100644 --- a/crates/wit-parser/tests/ui/parse-fail/return-borrow6.wit.result +++ b/crates/wit-parser/tests/ui/parse-fail/return-borrow6.wit.result @@ -1,4 +1,4 @@ -failed to update function `x`: function returns a type which contains a `borrow` which is not supported +function returns a type which contains a `borrow` which is not supported --> tests/ui/parse-fail/return-borrow6.wit:6:3 | 6 | x: func() -> tuple>; diff --git a/crates/wit-parser/tests/ui/parse-fail/return-borrow7.wit.result b/crates/wit-parser/tests/ui/parse-fail/return-borrow7.wit.result index f2175ae6d6..5d8532f944 100644 --- a/crates/wit-parser/tests/ui/parse-fail/return-borrow7.wit.result +++ b/crates/wit-parser/tests/ui/parse-fail/return-borrow7.wit.result @@ -1,4 +1,4 @@ -failed to update function `x`: function returns a type which contains a `borrow` which is not supported +function returns a type which contains a `borrow` which is not supported --> tests/ui/parse-fail/return-borrow7.wit:10:3 | 10 | x: func() -> y2; diff --git a/crates/wit-parser/tests/ui/parse-fail/return-borrow8.wit.result b/crates/wit-parser/tests/ui/parse-fail/return-borrow8.wit.result index 3ace7b8be7..386c05e7d2 100644 --- a/crates/wit-parser/tests/ui/parse-fail/return-borrow8.wit.result +++ b/crates/wit-parser/tests/ui/parse-fail/return-borrow8.wit.result @@ -1,4 +1,4 @@ -failed to resolve directory while parsing WIT for path [tests/ui/parse-fail/return-borrow8]: failed to update function `x`: function returns a type which contains a `borrow` which is not supported +failed to resolve directory while parsing WIT for path [tests/ui/parse-fail/return-borrow8]: function returns a type which contains a `borrow` which is not supported --> tests/ui/parse-fail/return-borrow8/foo.wit:6:3 | 6 | x: func() -> r; diff --git a/crates/wit-parser/tests/ui/parse-fail/unresolved-interface4.wit.result b/crates/wit-parser/tests/ui/parse-fail/unresolved-interface4.wit.result index 2c9268f995..ca541065c7 100644 --- a/crates/wit-parser/tests/ui/parse-fail/unresolved-interface4.wit.result +++ b/crates/wit-parser/tests/ui/parse-fail/unresolved-interface4.wit.result @@ -1,6 +1,5 @@ package 'some:dependency' not found. known packages: foo:foo - --> tests/ui/parse-fail/unresolved-interface4.wit:6:10 | 6 | import some:dependency/iface; 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); diff --git a/crates/wit-smith/src/lib.rs b/crates/wit-smith/src/lib.rs index ebc0e09fa2..c147ce38a6 100644 --- a/crates/wit-smith/src/lib.rs +++ b/crates/wit-smith/src/lib.rs @@ -6,7 +6,10 @@ //! type structures. use arbitrary::{Result, Unstructured}; -use wit_parser::{InvalidTransitiveDependency, Resolve}; +use wit_parser::{ + Resolve, + error::{ResolveErrorKind, ResolveErrors}, +}; mod config; pub use self::config::Config; @@ -27,7 +30,11 @@ pub fn smith(config: &Config, u: &mut Unstructured<'_>) -> Result> { let id = match resolve.push_group(group) { Ok(id) => id, Err(e) => { - if e.is::() { + if matches!( + e.downcast_ref::(), + Some(e) if matches!(e.kind(), + ResolveErrorKind::InvalidTransitiveDependency { .. }) + ) { return Err(arbitrary::Error::IncorrectFormat); } let err = e.to_string(); diff --git a/tests/cli/since-on-future-package.wit.stderr b/tests/cli/since-on-future-package.wit.stderr index c575764151..4994ed6115 100644 --- a/tests/cli/since-on-future-package.wit.stderr +++ b/tests/cli/since-on-future-package.wit.stderr @@ -1,8 +1,5 @@ -error: failed to process feature gate for function [b] in package [test:invalid@0.1.0] - -Caused by: - 0: feature gate cannot reference unreleased version 0.1.1 of package [test:invalid@0.1.0] (current version 0.1.0) - --> tests/cli/since-on-future-package.wit:9:3 - | - 9 | b: func(s: string) -> string; - | ^ +error: feature gate cannot reference unreleased version 0.1.1 of package [test:invalid@0.1.0] (current version 0.1.0) + --> tests/cli/since-on-future-package.wit:9:3 + | + 9 | b: func(s: string) -> string; + | ^