use waddling_errors::prelude::*;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum Component {
Parser,
Semantic,
Codegen,
}
impl ComponentId for Component {
fn as_str(&self) -> &'static str {
match self {
Component::Parser => "PARSER",
Component::Semantic => "SEMANTIC",
Component::Codegen => "CODEGEN",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum Primary {
Syntax,
Type,
Logic,
}
impl PrimaryId for Primary {
fn as_str(&self) -> &'static str {
match self {
Primary::Syntax => "SYNTAX",
Primary::Type => "TYPE",
Primary::Logic => "LOGIC",
}
}
}
const ERR_PARSER_SYNTAX: Code<Component, Primary> =
Code::error(Component::Parser, Primary::Syntax, 3);
const ERR_SEMANTIC_TYPE: Code<Component, Primary> =
Code::error(Component::Semantic, Primary::Type, 3);
const WARN_CODEGEN_LOGIC: Code<Component, Primary> =
Code::warning(Component::Codegen, Primary::Logic, 3);
fn main() {
println!("🦆 Trait-Based Error Codes Example\n");
println!("====================================\n");
println!("Error codes:");
println!(" {}", ERR_PARSER_SYNTAX.code());
println!(" {}", ERR_SEMANTIC_TYPE.code());
println!(" {}", WARN_CODEGEN_LOGIC.code());
println!();
println!("Type-safe component access:");
println!(" Component: {:?}", ERR_PARSER_SYNTAX.component());
println!(" Primary: {:?}", ERR_PARSER_SYNTAX.primary());
println!(" Sequence: {}", ERR_PARSER_SYNTAX.sequence());
println!();
println!("Pattern matching on components:");
check_error(ERR_PARSER_SYNTAX);
check_error(ERR_SEMANTIC_TYPE);
check_error(WARN_CODEGEN_LOGIC);
println!();
println!("Using in Result types:");
match parse_something() {
Ok(val) => println!(" Success: {}", val),
Err(code) => println!(" Error: {}", code.code()),
}
println!();
println!("Severity checks:");
println!(
" Is ERR_PARSER_SYNTAX blocking? {}",
ERR_PARSER_SYNTAX.severity().is_blocking()
);
println!(
" Is WARN_CODEGEN_LOGIC blocking? {}",
WARN_CODEGEN_LOGIC.severity().is_blocking()
);
println!(" Priority: {}", ERR_PARSER_SYNTAX.severity().priority());
println!();
#[cfg(feature = "runtime-hash")]
{
println!("Hash feature (5-char base62):");
println!(
" {}: {}",
ERR_PARSER_SYNTAX.code(),
ERR_PARSER_SYNTAX.hash()
);
println!(
" {}: {}",
ERR_SEMANTIC_TYPE.code(),
ERR_SEMANTIC_TYPE.hash()
);
println!(
" {}: {}",
WARN_CODEGEN_LOGIC.code(),
WARN_CODEGEN_LOGIC.hash()
);
println!(" (Safe for all logging systems, 916M combinations)");
}
}
fn check_error(code: Code<Component, Primary>) {
match code.component() {
Component::Parser => println!(" Parser error detected!"),
Component::Semantic => println!(" Semantic error detected!"),
Component::Codegen => println!(" Codegen error detected!"),
}
}
fn parse_something() -> Result<String, Code<Component, Primary>> {
Err(ERR_PARSER_SYNTAX)
}