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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 30 additions & 9 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ itertools = "0.13.0"
arbitrary = { version = "1", optional = true, features = ["derive"] }
clap = "4.5.37"
chumsky = "0.11.2"
thiserror = "2.0.18"

[target.wasm32-unknown-unknown.dependencies]
getrandom = { version = "0.2", features = ["js"] }
Expand Down
113 changes: 111 additions & 2 deletions src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use simplicity::jet::Elements;

use crate::debug::{CallTracker, DebugSymbols, TrackedCallName};
use crate::driver::{FileScoped, SymbolTable, MAIN_MODULE, MAIN_STR};
use crate::error::{Error, RichError, Span, WithSpan};
use crate::error::{RichError, Span, WithSpan};
use crate::num::{NonZeroPow2Usize, Pow2Usize};
use crate::parse::MatchPattern;
use crate::pattern::Pattern;
Expand All @@ -22,6 +22,115 @@ use crate::value::{UIntValue, Value};
use crate::witness::{Parameters, WitnessTypes, WitnessValues};
use crate::{driver, impl_eq_hash, parse};

#[derive(Debug, thiserror::Error, Clone, Eq, PartialEq, Hash)]
pub enum Error {
#[error("Main function is required")]
MainRequired,

#[error("Function `{0}` was defined multiple times")]
FunctionRedefined(FunctionName),

#[error("Type alias `{0}` is not defined")]
UndefinedAlias(AliasName),

#[error("INTERNAL ERROR: {0}")]
Internal(String),

#[error("Item `{0}` is private")]
PrivateItem(String),

#[error("Type alias `{0}` was defined multiple times")]
RedefinedAlias(AliasName),

#[error("Expected expression of type `{0}`, found type `{1}`")]
ExpressionTypeMismatch(ResolvedType, ResolvedType),

#[error("Witness expressions are not allowed outside the `main` function")]
WitnessOutsideMain,

#[error("Witness `{0}` has been used before somewhere in the program")]
WitnessReused(WitnessName),

#[error("Function `{0}` was called but not defined")]
FunctionUndefined(FunctionName),

#[error("Failed to compile to Simplicity: {0}")]
CannotCompile(String),
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In 39ff893:

This is used in only one place - to indicate that the use keyword is not yet supported. We should have a dedicated error variant for this.


#[error("Main function takes no input parameters")]
MainNoInputs,

#[error("Main function produces no output")]
MainNoOutput,

#[error("The 'main' function must be defined in the entry point file")]
MainOutOfEntryFile,

#[error("Expected expression of type `{0}`; found something else")]
ExpressionUnexpectedType(ResolvedType),

#[error("Variable `{0}` is used twice in the pattern")]
VariableReuseInPattern(Identifier),

#[error("Variable `{0}` is not defined")]
UndefinedVariable(Identifier),

#[error("Value is out of bounds for type `{0}`")]
IntegerOutOfBounds(UIntType),

#[error("Cannot parse: {0}")]
IntParseError(String),

#[error("Expected a valid bit string length (1, 2, 4, 8, 16, 32, 64, 128, 256), found {0}")]
BitStringPow2(usize),

#[error("{0}")]
Generic(String),
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In 39ff893:

What is this for? It is unused in this commit. Can it hold a Box<dyn std::error::Error> rather than a string?


#[error("Expected {0} arguments, found {1} arguments")]
InvalidNumberOfArguments(usize, usize),

#[error("Cannot cast values of type `{0}` as values of type `{1}`")]
InvalidCast(ResolvedType, ResolvedType),

#[error("Jet `{0}` does not exist")]
JetDoesNotExist(crate::str::JetName),

#[error("Expected a signature like `fn {0}(element: E, accumulator: A) -> A` for a fold")]
FunctionNotFoldable(FunctionName),

#[error("Module `{0}` is defined twice")]
ModuleRedefined(ModuleName),

#[error("Witness `{0}` has already been assigned a value")]
WitnessReassigned(WitnessName),

#[error("Expected a signature like `fn {0}(accumulator: A, context: C, counter u{{1,2,4,8,16}}) -> Either<B, A>` for a for-while loop")]
FunctionNotLoopable(FunctionName),

#[error("Witness `{0}` was declared with type `{1}` but its assigned value is of type `{2}`")]
WitnessTypeMismatch(WitnessName, ResolvedType, ResolvedType),

#[error("Parameter `{0}` is missing an argument")]
ArgumentMissing(WitnessName),

#[error(
"Parameter `{0}` was declared with type `{1}` but its assigned argument is of type `{2}`"
)]
ArgumentTypeMismatch(WitnessName, ResolvedType, ResolvedType),
}

impl From<crate::num::ParseIntError> for Error {
fn from(error: crate::num::ParseIntError) -> Self {
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In 39ff893:

My same complaint about the From impls in the last commit apply here.

Self::IntParseError(error.to_string())
}
}
impl From<std::num::ParseIntError> for Error {
fn from(error: std::num::ParseIntError) -> Self {
Self::IntParseError(error.to_string())
}
}

/// A program consists of the main function.
///
/// Other items such as custom functions or type aliases
Expand Down Expand Up @@ -896,7 +1005,7 @@ impl AbstractSyntaxTree for Item {
Function::analyze(function, ty, scope).map(Self::Function)
}
parse::Item::Use(use_decl) => Err(RichError::new(
Error::CannotCompile("The `use` keyword is not supported yet.".to_string()),
Error::CannotCompile("The `use` keyword is not supported yet.".to_string()).into(),
*use_decl.span(),
)),
parse::Item::Module => Ok(Self::Module),
Expand Down
8 changes: 8 additions & 0 deletions src/compile/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
#[derive(Debug, thiserror::Error, Clone, Eq, PartialEq, Hash)]
pub enum Error {
#[error("Variable `{0}` is not defined")]
UndefinedVariable(crate::str::Identifier),

#[error("Simplicity compiler error: {0}")]
TypeError(String),
}
5 changes: 4 additions & 1 deletion src/compile/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
//! Compile the parsed ast into a simplicity program

mod builtins;
mod error;

pub use error::Error;

use std::sync::Arc;

Expand All @@ -16,7 +19,7 @@ use crate::ast::{
SingleExpressionInner, Statement,
};
use crate::debug::CallTracker;
use crate::error::{Error, RichError, Span, WithSpan};
use crate::error::{RichError, Span, WithSpan};
use crate::named::{self, CoreExt, PairBuilder};
use crate::num::{NonZeroPow2Usize, Pow2Usize};
use crate::pattern::{BasePattern, Pattern};
Expand Down
45 changes: 45 additions & 0 deletions src/driver/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
use crate::str::{AliasName, FunctionName};

#[derive(Debug, thiserror::Error, Clone, Eq, PartialEq, Hash)]
pub enum Error {
#[error("Item `{0}` could not be found")]
UnresolvedItem(String),

#[error("Item `{0}` is private")]
PrivateItem(String),

#[error("The alias `{0}` was defined multiple times")]
DuplicateAlias(String),

#[error("Item `{0}` was defined multiple times")]
RedefinedItem(String),

#[error("Main function cannot be public")]
MainCannotBePublic,

#[error("Function `{0}` was defined multiple times")]
FunctionRedefined(FunctionName),

#[error("Unknown module or library '{0}'")]
UnknownLibrary(String),

#[error("Main function cannot be alias")]
MainCannotBeAlias,

#[error("Type alias `{0}` was defined multiple times")]
RedefinedAlias(AliasName),

#[error("Local file `{0}` not found")]
FileNotFound(String),

#[error(
"File `{0}` is part of the local project and must be imported using the `crate::` prefix"
)]
LocalFileImportedAsExternal(String),

#[error("File `{1}` not found in external library `{0}`")]
ExternalFileNotFound(String, String),

#[error("INTERNAL ERROR: {0}")]
Internal(String),
}
13 changes: 9 additions & 4 deletions src/driver/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,21 +27,23 @@
//! resolves and parses these external files relative to the entry point during
//! the dependency graph construction.

mod error;
mod linearization;
pub(crate) mod resolve_order;

use std::collections::{HashMap, HashSet, VecDeque};
use std::path::PathBuf;
use std::sync::Arc;

use chumsky::container::Container;

use crate::error::{Error, ErrorCollector, RichError, Span};
use crate::error::{ErrorCollector, RichError, Span};
use crate::parse::{self, ParseFromStrWithErrors};
use crate::resolution::{CanonPath, DependencyMap, SourceFile};

pub use crate::driver::resolve_order::{FileScoped, Program, SymbolTable};

pub use crate::driver::error::Error;

/// The reserved identifier for the program's entry point.
pub(crate) const MAIN_STR: &str = "main";

Expand Down Expand Up @@ -257,8 +259,11 @@ impl DependencyGraph {
handler: &mut ErrorCollector,
) -> Option<Module> {
let Ok(content) = std::fs::read_to_string(path.as_path()) else {
let err = RichError::new(Error::FileNotFound(PathBuf::from(path.as_path())), span)
.with_source(importer_source.clone());
let err = RichError::new(
Error::FileNotFound(path.as_path().to_string_lossy().to_string()).into(),
span,
)
.with_source(importer_source.clone());

handler.push(err);
return None;
Expand Down
Loading
Loading