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 @@ -43,6 +43,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
125 changes: 120 additions & 5 deletions src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,134 @@ use simplicity::jet::{Elements, Jet};

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::jet::JetHL;
use crate::num::{NonZeroPow2Usize, Pow2Usize};
use crate::parse::MatchPattern;
use crate::pattern::Pattern;
use crate::str::{AliasName, FunctionName, Identifier, ModuleName, WitnessName};
use crate::str::{AliasName, FunctionName, Identifier, JetName, ModuleName, WitnessName};
use crate::types::{
AliasedType, ResolvedType, StructuralType, TypeConstructible, TypeDeconstructible, UIntType,
};
use crate::value::{UIntValue, Value};
use crate::witness::{Parameters, WitnessTypes};
use crate::{driver, impl_eq_hash, parse};

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

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

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

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

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

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

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

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

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

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

#[error("Failed to compile to Simplicity: {msg}")]
CannotCompile { msg: String },

#[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 `{ty}`; found something else")]
ExpressionUnexpectedType { ty: ResolvedType },

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

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

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

#[error("Expected {expected} arguments, found {found} arguments")]
InvalidNumberOfArguments { expected: usize, found: usize },

#[error("Cannot cast values of type `{source_type}` as values of type `{target_type}`")]
InvalidCast {
source_type: ResolvedType,
target_type: ResolvedType,
},

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

#[error("Expected a signature like `fn {name}(element: E, accumulator: A) -> A` for a fold")]
FunctionNotFoldable { name: 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 {name}(accumulator: A, context: C, counter u{{1,2,4,8,16}}) -> Either<B, A>` for a for-while loop")]
FunctionNotLoopable { name: FunctionName },

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

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

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

#[error("The `use` keyword is not supported yet")]
UseKeywordIsNotSupported,

#[error("Integer parsing error")]
ParseIntCrate(#[from] crate::num::ParseIntError),

#[error("Integer parsing error")]
ParseInt(#[from] std::num::ParseIntError),

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

/// A program consists of the main function.
///
/// Other items such as custom functions or type aliases
Expand Down Expand Up @@ -981,7 +1096,7 @@ impl AbstractSyntaxTree for Item {
Function::analyze(function, ty, scope).map(Self::Function)
}
parse::Item::Use(use_decl) => Err(RichError::new(
Error::UseKeywordIsNotSupported,
crate::error::Error::AnalyzingError(Error::UseKeywordIsNotSupported),
*use_decl.span(),
)),
parse::Item::Module => Ok(Self::Module),
Expand Down Expand Up @@ -1428,8 +1543,8 @@ impl AbstractSyntaxTree for Call {
CallName::TypeCast(source) => {
if StructuralType::from(&source) != StructuralType::from(ty) {
return Err(Error::InvalidCast {
source,
target: ty.clone(),
source_type: source,
target_type: ty.clone(),
})
.with_span(from);
}
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)]
pub enum Error {
#[error("Variable `{identifier}` is not defined")]
UndefinedVariable { identifier: crate::str::Identifier },

#[error("Simplicity type error")]
TypeError(#[from] simplicity::types::Error),
}
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 @@ -15,7 +18,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
65 changes: 65 additions & 0 deletions src/driver/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
use std::path::PathBuf;

use crate::str::{AliasName, FunctionName};

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

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

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

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

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

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

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

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

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

#[error("Local file `{}` not found", filename.display())]
FileNotFound { filename: PathBuf },

#[error(
"File `{}` is part of the local project and must be imported using the `crate::` prefix", path.to_string_lossy()

)]
LocalFileImportedAsExternal { path: PathBuf },

#[error("File `{}` not found in external library `{}`", lib, filename.display())]
ExternalFileNotFound { lib: String, filename: PathBuf },

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

#[error("Path not found: {}", path.display())]
DependencyPathNotFound { path: PathBuf },

#[error("Path must be a directory: {}", path.display())]
DependencyNotADirectory { path: PathBuf },

#[error("The '{keyword}' keyword is reserved and cannot be manually mapped. Use the builder's context definitions instead.")]
ReservedDependencyKeyword { keyword: String },

#[error("Duplicate dependency mapping: alias '{alias}' is defined multiple times for context '{context}'")]
DuplicateDependencyAlias { alias: String, context: String },

#[error(
"Invalid dependency alias '{alias}': must be a valid identifier and not a reserved keyword"
)]
InvalidDependencyIdentifier { alias: String },
}
8 changes: 6 additions & 2 deletions src/driver/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
//! 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;

Expand All @@ -36,13 +37,15 @@ 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::DependencyMap;
use crate::source::{CanonPath, CanonSourceFile};

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 @@ -209,7 +212,8 @@ impl DependencyGraph {
let err = RichError::new(
Error::FileNotFound {
filename: PathBuf::from(path.as_path()),
},
}
.into(),
span,
)
.with_source(importer_source.clone());
Expand Down
Loading
Loading