RFC 013: Error Code Specification
Abstract
This RFC proposes a specification for classifying error codes in the YaoXiang compiler. It uses a single-level numbering system similar to Rust, supports multiple languages through JSON resource files, and provides error explanations through the yaoxiang explain command.
Motivation
Why Do We Need Standardized Error Codes?
- User experience: Users can quickly determine the type and severity of an error from its error code
- Documentation organization: Grouping by category makes error reference documentation easier to write and maintain
- Tool integration: IDEs/LSPs can provide quick-fix suggestions and documentation links based on error codes
- Internationalization support: Separating error messages from codes makes translation into multiple languages easier
Design Goals
- Concise: A single level of numbering means users do not need to memorize complex classification rules
- Friendly: Rust-like error message formatting with help text and examples
- Extensible: Resource files drive the implementation, making it easy to add new errors and languages
- Tool-friendly: The explain command and JSON output support IDE/LSP integration
Proposal
Core Design: Single-Level Numbering System
Four-digit numeric identifiers are used, grouped by compilation phase:
Exxxx
││││
│││└── 序号 (000-999)
││└─── 编译阶段 (0-9)
└───── 固定前缀 'E'Phase Division
| Phase | Range | Description |
|---|---|---|
| 0 | E0xxx | Lexical and syntactic analysis |
| 1 | E1xxx | Type checking |
| 2 | E2xxx | Semantic analysis |
| 3 | E3xxx | Code generation |
| 4 | E4xxx | Generics and traits |
| 5 | E5xxx | Modules and imports |
| 6 | E6xxx | Runtime errors |
| 7 | E7xxx | I/O and system errors |
| 8 | E8xxx | Internal compiler errors |
| 9 | E9xxx | Reserved/experimental |
Error Category Enum
/// Error category
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ErrorCategory {
Lexer, // E0xxx: Lexical and syntactic analysis
Parser, // E0xxx: Parser errors
TypeCheck, // E1xxx: Type checking
Semantic, // E2xxx: Semantic analysis
Generic, // E4xxx: Generics and traits
Module, // E5xxx: Modules and imports
Runtime, // E6xxx: Runtime errors
Io, // E7xxx: I/O and system errors
Internal, // E8xxx: Internal compiler errors
}Error Code Definitions and the Generic Builder
Core principle: Error code definitions are separated from display text.
ErrorCodeDefinition: Error code metadata (code, category, template), excluding display textlocales/*.json: Display text in each language (title, message, help; error codes are nested objects)DiagnosticBuilder: A generic builder that replaces the trait-per-error design
Error Code Definitions
// diagnostic/codes/mod.rs
use crate::util::span::Span;
use crate::util::diagnostic::{Diagnostic, Severity};
/// Error code definition (metadata only; display text is in the i18n file)
#[derive(Debug, Clone, Copy)]
pub struct ErrorCodeDefinition {
pub code: &'static str,
pub category: ErrorCategory,
pub message_template: &'static str, // Message template; supports {param} placeholders
}
/// Generic diagnostic builder
pub struct DiagnosticBuilder {
code: &'static str,
message_template: &'static str,
params: Vec<(&'static str, String)>,
span: Option<Span>,
}
impl DiagnosticBuilder {
pub fn new(code: &'static str, template: &'static str) -> Self {
Self {
code,
message_template: template,
params: Vec::new(),
span: None,
}
}
/// Add a template parameter
pub fn param(mut self, key: &'static str, value: impl Into<String>) -> Self {
self.params.push((key, value.into()));
self
}
/// Set the location
pub fn at(mut self, span: Span) -> Self {
self.span = Some(span);
self
}
/// Build a Diagnostic (template rendering is completed at compile time)
pub fn build(&self, i18n: &I18nRegistry) -> Diagnostic {
// Check that every {key} in the template has a corresponding parameter
self.validate_params();
let message = i18n.render(self.message_template, &self.params);
let help = self.help(i18n);
Diagnostic {
severity: Severity::Error,
code: self.code.to_string(),
message,
help,
span: self.span,
related: Vec::new(),
}
}
}Shortcut Method for Each Error Code
// diagnostic/codes/e1xxx.rs
impl ErrorCodeDefinition {
/// E1001 Unknown variable
pub fn unknown_variable(name: &str) -> DiagnosticBuilder {
let def = Self::find("E1001").unwrap();
DiagnosticBuilder::new(def.code, def.message_template)
.param("name", name)
}
/// E1002 Type mismatch
pub fn type_mismatch(expected: &str, found: &str) -> DiagnosticBuilder {
let def = Self::find("E1002").unwrap();
DiagnosticBuilder::new(def.code, def.message_template)
.param("expected", expected)
.param("found", found)
}
}Usage Example
// checking/mod.rs
use crate::util::diagnostic::codes::{ErrorCodeDefinition, E1001};
// Simplified approach
return Err(E1001::unknown_variable(&var_name)
.at(span)
.build(&i18n_registry));
// Manual approach
return Err(ErrorCodeDefinition::find("E1001")
.builder()
.param("name", var_name)
.at(span)
.build(&i18n_registry));Error Code Definition Example
// diagnostic/codes/e1xxx.rs
pub static E1XXX: &[ErrorCodeDefinition] = &[
ErrorCodeDefinition {
code: "E1001",
category: ErrorCategory::TypeCheck,
message_template: "Unknown variable: '{name}'",
},
ErrorCodeDefinition {
code: "E1002",
category: ErrorCategory::TypeCheck,
message_template: "Expected type '{expected}', found type '{found}'",
},
// ... Other error codes
];Design Advantages
| Feature | Description |
|---|---|
| Single Builder | One DiagnosticBuilder works with all error codes |
| Type safety | Shortcut methods ensure parameter correctness |
| Self-documenting | E1001::unknown_variable(name) is immediately clear |
| Template separation | Message templates are separated from code, easing i18n |
| Zero runtime overhead | Compile-time rendering; AOT binaries perform no table lookups |
Error Macro Simplification
error! Macro (Automatic Context Injection)
/// Macro that automatically obtains the span and i18n configuration at compile time
macro_rules! error {
($code:ident, $($key:ident = $value:expr),* $(,)?) => {
$code()
$(.$key($value))*
.at(crate::util::span::Span::current())
.build(crate::util::diagnostic::I18nRegistry::current())
};
}
/// Usage: only pass parameters; the span and i18n are injected automatically
return Err(error!(E1001, name = var_name));
return Err(error!(E1002, expected = "bool", found = cond_ty));Using the Builder Manually
// When manual control is needed
E1001::unknown_variable(&var_name)
.at(my_span) // Custom span
.build(&custom_i18n) // Custom i18nDetailed Design
Error Code List
E0xxx: Lexical and Syntactic Analysis
| Code | Description |
|---|---|
| E0001 | Invalid character |
| E0002 | Invalid numeric literal |
| E0003 | Unterminated string |
| E0004 | Invalid character literal |
| E0010 | Expected token |
| E0011 | Unexpected token |
| E0012 | Invalid syntax |
| E0013 | Mismatched parentheses |
| E0014 | Missing semicolon |
| E0016 | Expected expression |
| E0018 | Keyword used as a name |
| E0019 | Expression nesting is too deep |
E1xxx: Type Checking
| Code | Description |
|---|---|
| E1001 | Unknown variable |
| E1002 | Type mismatch |
| E1003 | Unknown type |
| E1010 | Argument count mismatch |
| E1011 | Implementation parameter annotations do not match the declaration |
| E1012 | Return type mismatch |
| E1013 | Function not found |
| E1014 | Unknown named parameter |
| E1015 | Duplicate argument specification |
| E1020 | Unable to infer type |
| E1021 | Type inference conflict |
| E1030 | Incomplete pattern |
| E1031 | Unreachable pattern |
| E1032 | Duplicate pattern binding |
| E1033 | Inconsistent or-pattern bindings |
| E1034 | Struct pattern is missing fields |
| E1040 | Unsupported operation |
| E1041 | Index out of bounds |
| E1042 | Field not found |
| E1043 | Module member not found |
| E1050 | Boolean operand required |
| E1051 | Logical NOT requires a boolean operand |
| E1052 | Invalid dereference |
| E1053 | Field access on a non-struct |
| E1054 | Conditional type mismatch |
| E1055 | Constraint in a non-generic context |
| E1060 | Type argument count mismatch |
| E1061 | Unable to instantiate generic |
| E1062 | const generic constraint failed |
| E1064 | Invalid binding position index |
| E1065 | Call on a non-function value |
| E1071 | Type definitions are only allowed at module scope |
| E1081 | ? is only allowed in functions returning a propagatable type |
| E1082 | ? can only be used with types implementing Try |
| E1083 | ? error type mismatch |
| E1090 | ✨ Unspeakable ✨ |
| E1091 | Invalid generic meta type |
| E1092 | Illegal shape of refinement type arguments |
| E1093 | Refinement argument count mismatch |
| E1094 | Unused compile-time value parameter |
| E1095 | Unknown interface |
| E1096 | Interface argument count mismatch |
| E1097 | Interface member name conflict |
| E1098 | Interface method not implemented |
| E1099 | Interface method signature mismatch |
| E1100 | Duplicate implementation of an interface method |
| E1101 | Type does not implement the interface |
| E1102 | Loop control statement outside a loop |
| E1103 | Square brackets cannot be used in type position |
| E1104 | Interface implementation is not in the type's defining module |
| E1105 | Variant constructor cannot be accessed as a field |
| E1106 | Constraint method dispatch failed |
| E1107 | Ambiguous method overload |
| E1108 | Empty block where a container is expected |
| E1109 | return outside a function |
| E1110 | Method binding lacks a signature annotation |
| E1111 | Duplicate or invalidly ordered argument use |
| E1112 | Implementation parameter count exceeds the declaration |
| E1113 | Compile-time value parameter lacks compile-time evidence |
| E1114 | witness field cannot be read as a value |
| E1115 | witness-bearing record is immutable |
| E1116 | A bare name conflicts with exports from multiple standard library units |
RFC-011b association (note dated 2026-09-22): RFC-011b: Operator Overloading Implementation will affect three points in this section—① the wording of
E1081/E1082will remove "Result" (?will instead be determined through theTryinterface, no longer bound to a concrete type name), and will be synchronized with phase 2 according to this document's "three-way consistency" process (codes/*.rs ↔ locales ↔ code tables); ② the rejection diagnostic for an unsatisfiedEqualprecondition (linear token) will reuse theE1101(type does not implement the interface) family; ③ after phase 1 is wired up,Struct == Structwill change from theE6007runtime error to a compile-time determination, reducing the trigger surface ofE6007. The registered wording in the table will remain unchanged until the implementation lands.
E2xxx: Semantic Analysis
| Code | Description |
|---|---|
| E2001 | Scope error |
| E2002 | Duplicate definition |
| E2003 | Ownership error |
| E2010 | Immutable assignment |
| E2011 | Use of uninitialized variable |
| E2012 | Mutability conflict |
| E2013 | Variable shadowing |
| E2014 | Use of moved value |
| E2016 | Immutable assignment |
| E2018 | Mutable/immutable borrow conflict |
| E2019 | Double free |
| E2020 | Use after free |
| E2027 | unsafe dereference |
| E2029 | Reference cycle within spawn |
| E2030 | Refinement constraint violation |
| E2031 | Refinement constraint cannot be proven |
| E2090 | Invalid signature |
| E2091 | Unknown type in signature |
| E2092 | Signature missing an arrow |
| E2093 | Duplicate parameter name |
| E2094 | Generic parameter shadowing |
| E2095 | Parameter name shadows a generic |
| E2096 | Signature contains a bare container type |
Reserved code notes (inventory dated 2026-09-14, release scope for #251): E2019 (double free), E2020 (use after free), E2027 (unsafe dereference), and E2029 (ref cycle within spawn) have completed registration and are anchored by unit tests, but there is not yet a reachable yx source surface (explicit drop statements, Ptr dereference grammar, or a spawn ref-cycle construction path). The claim that their semantics are completely correct does not cover these four codes; until the implementations are completed, they should be treated as "reserved".
E3xxx: Code Generation
| Code | Description |
|---|---|
| E3004 | Unsupported iterator |
| E3005 | IR generation error |
| E3006 | Unresolved variable |
| E3007 | Top-level binding initialization must be a constant |
| E3008 | Unsupported match pattern |
| E3014 | Register overflow |
| E3017 | Invalid operand (code generation) |
| E3018 | Monomorphization instantiation failed |
| E3019 | Top-level binding cyclic dependency |
| E3020 | Missing program entry point |
| E3021 | Entry point is not a function |
| E3022 | Entry point main signature mismatch |
| E3023 | Executable statements are not allowed at the top level |
| E3024 | Project configuration is unreadable |
E4xxx: Generics and Traits
| Code | Description |
|---|---|
| E4001 | Generic constraint violation |
| E4002 | Trait not found |
| E4003 | Missing trait implementation |
| E4004 | Conflicting trait implementations |
| E4005 | Associated type not found |
| E4010 | Constant division by zero |
| E4011 | Constant overflow |
| E4012 | Constant recursion is too deep |
| E4014 | Constant evaluation failed |
| E4018 | Refinement predicate violation |
| E4019 | Type equality does not hold |
| E4020 | Proof function required |
| E4021 | Loop termination cannot be automatically proven |
| E4022 | Measure does not hold |
| E4023 | Cannot prove within the kernel |
E4006/E8004 currently have no emission points (reserved codes): Sized constraints and optimization error paths await implementation; wire them to their actual trigger surfaces during implementation.
E4023: Generic “Unable to Prove”
Status: registered (2026-11-13). This section records the code semantics and division of responsibility; the code is emitted along the generic
Unprovenpath, and all four mechanical registration surfaces were submitted together.
- Code:
E4023 - Category (face):
Generic(E4xxx, generics and proof surface), in the same family asE4021andE4022. - Semantics: A generic “unable to prove.” It is emitted when no proof can be constructed within resource limits; it is not tied to a specific proposition shape.
- Template:
Unable to prove: {proposition} ({reason}) - Parameters:
proposition(renderable text for the unsolved proposition),reason(capability boundary / exhausted budget / contains unbound symbol names). - Location: Non-exempt—the emission site provides the source location. If a decision point genuinely has no location, use the default location and explain the reason in an implementation comment.
- Division of responsibility with E2031:
E2031is dedicated to refinement constraints, is emitted by the refinement channel with a real location, and includes the assigned name, variable, and constraint in its wording.E4023is the generic fallback, coversUnprovenat equality checking and other obligation points, and carries the proposition and reason. The two codes must not substitute for one another: a missing proof for a refinement constraint still reports E2031, while an inability to decide equality or another obligation reports E4023. - Boundary with existing codes:
E4019(type equality does not hold) corresponds toDisproved;E4023corresponds toUnproven.E4014(constant evaluation failed) corresponds to a deterministic failure in closed-term evaluation and is not used for "unproven within resource limits". - Mechanical registration surfaces (completed): the
define_codes!entry insrc/util/diagnostic/codes/e4xxx.rs→ templates and parameters in the six language files underlocales/→ the E4xxx code table in this document (regenerated by the error code documentation generator) → the generated page underdocs/src/reference/error-code/. All four were submitted together.
E5xxx: Modules and Imports
| Code | Description |
|---|---|
| E5001 | Module not found |
| E5002 | Import error |
| E5003 | Export not found |
| E5004 | Circular dependency |
| E5005 | Invalid module path |
| E5006 | Duplicate import |
| E5007 | Module export |
| E5008 | Import name conflict |
E6xxx: Runtime Errors
| Code | Description |
|---|---|
| E6001 | Division by zero error |
| E6003 | Array index out of bounds |
| E6004 | Stack overflow |
| E6005 | Assertion failed |
| E6006 | Function not found (runtime) |
| E6007 | Runtime error |
| E6008 | Key does not exist |
| E6009 | Invalid Range step |
| E6010 | Integer parsing failed |
| E6011 | Floating-point parsing failed |
| E6012 | Invalid code point |
| E6013 | JSON parsing failed |
E6xxx code-space semantics: This family covers only trigger surfaces that genuinely exist at runtime—YaoXiang has value semantics, so there are no null pointers, heap allocation failures, or type conversion concepts, and runtime overflow paths are not detected. E6002 is unused; E6003 is Runtime index out of bounds; E6005 is Assertion failed (the real path of std.assert); E6006 is Function not found; E6007 is the generic Runtime error (the unified landing point for unmapped variants of ExecutorError).
E7xxx: I/O and System Errors
| Code | Description |
|---|---|
| E7001 | File not found |
| E7002 | Permission denied |
| E7003 | I/O error |
| E7004 | Network error |
E8xxx: Internal Compiler Errors
| Code | Description |
|---|---|
| E8001 | Internal compiler error |
| E8002 | Unexpected panic |
| E8003 | Compiler phase error |
W1xxx: Warning Codes
| Code | Description |
|---|---|
| W1001 | Unused private function |
| W1002 | Unused private type |
| W1003 | Unused import |
| W1004 | Unused private variable |
| W1005 | Unused private method |
| W1006 | Local module shadows a dependency package |
| W1007 | Module import cycle |
| W1063 | const generic constraint cannot be evaluated |
| W1080 | Compile-time proof downgrade |
| W1081 | Termination obligation not decided |
| W1082 | Ownership analysis downgrade |
| W1090 | Obligation produced but has no consumer |
W code-space rules: W codes are isomorphic to E codes and are grouped by phase (W + the phase's thousand segment); W1xxx = warnings in the type-checking phase.
Dead code semantics (RFC-029f role semantics + RFC-029g): W1001/W1002/W1004/W1005 report top-level bindings and type definitions that are never referenced—a binding is reported if it is never referenced during file-local reachability analysis rooted at
main; methods (W1005) are matched by their short call-site name. The sole exemption is the package-internal reference pool (RFC-029f: a name referenced by any file in the project is considered live—cross-file consumers are not visible in this file, so this policy errs on the side of under-reporting).Implementation correction (2026-10-08, RFC-029g): The original text of this section stated, “
pubdefinitions are public interfaces and are never reported (#321 decision B).” Thepubkeyword has been removed, and modifiers no longer grant any exemption; the previous role-based exemption policy (Bin may be reported immediately / Internal tightened in phase two / Lib absolutely exempt) has converged on the single condition of whether a package-internal reference pool is provided. For behavior changes, see 029g.Unused imports (W1003): Detected by use elaboration in typecheck (pass2 registers imported local names; a hit in expression resolution or a type-annotation position counts as use), covering both whole-module imports (
use std.io→ module alias) and named imports (use std.io.{print}).Emission channel: The builder defaults W-prefixed diagnostics to
Severity::Warning(an explicit specification takes precedence), and their collection and presentation follow the same path as errors (rendered with thewarning[W####]prefix), but they do not block compilation or affect a successful exit code.yaoxiang check --deny-warningsescalates warnings to failures (exits with a non-zero code when warnings exist), for use in CI strict mode. Per-code suppression (such as allow attributes) is a future extension.Decoupling code families from emission levels (W1090 promoted to E, user decision dated 2026-10-13): A code number's prefix determines only its numbering family, not its emission severity—severity is determined by the explicit
severityat the diagnostic construction point (theEprefix defaults to Error, theWprefix defaults to Warning, and an explicit specification takes precedence). Accordingly,W1090(obligation produced but has no consumer) retains its W-family code number (no new E code is introduced: two codes for the same fact are parallel representations), but its emission severity is error: when triggered, it counts towarderror_count, is rendered aserror[W1090], and changes the exit code (the terminal state of obligation settlement; a semantic correction classified as a D-class breaking change and faithfully recorded in the 01-architecture § Obligation Ledger). Healthy programs emit nothing (no report is made when every obligation has a delivery marker), so this promotion affects the build result only when a phase contract defect actually occurs.
Message Quality Specification
This section was introduced by the single-track messaging and quality revision (2026-09-03). It is enforced in CI by
scripts/audit_diagnostics.py.
- Single-track messaging: All user-visible diagnostic messages must be rendered through the authoritative registry's shortcut methods and locale templates; the code passes only structured parameters. It is forbidden to bypass the registry and directly construct native values such as
Diagnostic::error(...), because that path bypasses code validation and i18n. - Code validity: Unregistered codes and pseudo-codes (such as
E_INTERNAL) are forbidden; a code literal at a use site must already be defined in the registry. All internal errors must use E8001 (internal_error). - Type display: Type Display must distinguish instantiated and uninstantiated forms (
Expected 'Container', found 'Container'cannot distinguish bare names). - Isolation of solver internal state: Solver intermediate state TypeVar (Display form
t<N>) must not appear in user-visible messages. Test anchor:test_type_error_message_no_solver_typevar_leak. - E8xxx boundary: E8xxx is only for internal compiler consistency problems (ICEs). User-fixable errors must not use E8001 as a fallback; ICE messages must include minimal reproduction guidance.
Runtime Error Values and Code Integration
This section was introduced by the revision that added codes to runtime Error values (2026-09-03). The E6xxx/E7xxx semantic space carries two channels simultaneously; the code space is shared, while the presentation channels differ.
Two Channels
| Channel | Carrier | Presentation |
|---|---|---|
| Compiler/CLI diagnostic channel | Hard host-layer errors such as ExecutorError | stderr error[E####]: (E6003/E6005/E6007 wired) |
| In-program error value channel | Error, the Err carrier in the std library Result(T, Error) | A language value, consumed by the program through match/comparison |
Error Structure (since v0.8, breaking change)
Error { code: String, message: String }codereuses the E6xxx/E7xxx numbering from this specification, in string form (such as"E6008").- Stable contract: The semantics of allocated codes do not change across versions; a deleted code is not reused for the same semantics (the E6002 precedent).
- Consumption surface: Within a program,
e.code == "E6xxx"comparison is the only programmable determination contract;yaoxiang explain E6xxxdocumentation is connected to it; the toolchain (LSP / DAP, see RFC-034) uses the code as its exceptionId. - Accessors:
std.result.code(e)/std.result.message(e). - User-defined errors: The E in
Result(T, E)is a generic parameter; rigorous modeling should use a user-defined type. The stdErroris only a convenient fallback carrier, and its code system does not constrain the user's E type.
Code Allocation Rules
- Runtime error value codes and compiler diagnostic codes share the E6xxx/E7xxx space. New codes are allocated according to actual trigger surfaces, without reserving codes for hypothetical scenarios.
- Register before use: A new code must enter the authoritative registry and pass three-way consistency validation (codes/*.rs ↔ locales ↔ the code tables in this document) before it can be emitted. The registration source for runtime error value codes is the
RUNTIME_ERROR_CODEStable insrc/std/result.rs, which is subject to the samebuild.rsbuild-time gate andtools/code-tablesvalidation as diagnostic codes. - E7xxx is reserved for std.io / std.net error values (currently unused; enabled when io/net become Result-based).
- Emission points: Each std module constructs an Error value through
error_new(code, message); on the consuming side,std.result.unwrap_errretrieves the Err carrier, andstd.result.code/messagereads its fields.
Evolution Path (Line C, Not Implemented)
After pattern-match exhaustiveness (RFC-010b) is implemented, Error can be upgraded to { kind: ErrorKind, message: String }, with code becoming a property derived from kind (the code registry is located at the variant definition). During the evolution period, the stable code contract in this section remains unchanged; this upgrade is an independent decision and does not constitute a commitment in this section.
Multilingual Resource Files
Resource File Format
// locales/en.json
{
"E1001": {
"title": "Unknown variable",
"message": "Referenced variable is not defined",
"template": "Unknown variable: '{name}'",
"help": "Check if the variable name is spelled correctly, or define it first",
"example": "x = 100;",
"error_output": "error[E1001]: Unknown variable: 'x'\n --> example.yx:1:1\n |\n 1 | print(x)\n | ^ unknown variable 'x'"
},
"E1002": {
"title": "Type mismatch",
"message": "Expected type does not match actual type",
"template": "Expected type '{expected}', found type '{found}'",
"help": "Use the correct type or add a type conversion",
"example": "x: Int = \"hello\";",
"error_output": "error[E1002]: Type mismatch\n --> example.yx:1:12\n |\n 1 | x: Int = \"hello\";\n | ^ expected 'Int', found 'String'"
}
}// locales/zh.json
{
"E1001": {
"title": "未知变量",
"message": "引用的变量未定义",
"template": "未知变量:'{name}'",
"help": "检查变量名是否拼写正确,或先定义它",
"example": "x = 100;",
"error_output": "error[E1001]: 未知变量:'x'\n --> example.yx:1:1\n |\n 1 | print(x)\n | ^ 未知变量 'x'"
},
"E1002": {
"title": "类型不匹配",
"message": "期望类型与实际类型不匹配",
"template": "期望类型 '{expected}',实际类型 '{found}'",
"help": "使用正确的类型或添加类型转换",
"example": "x: Int = \"hello\";",
"error_output": "error[E1002]: 类型不匹配\n --> example.yx:1:12\n |\n 1 | x: Int = \"hello\";\n | ^ 期望 'Int',找到 'String'"
}
}I18nRegistry Implementation
// locales/*.json (error code objects)
/// Registry of i18n display text (loaded from JSON at compile time, with zero runtime lookups)
pub struct I18nRegistry {
/// Title
titles: HashMap<&'static str, &'static str>,
/// Description
messages: HashMap<&'static str, &'static str>,
/// Help text
helps: HashMap<&'static str, &'static str>,
/// Example code
examples: HashMap<&'static str, &'static str>,
/// Example error output
error_outputs: HashMap<&'static str, &'static str>,
}
/// Information about a single error code
#[derive(Clone, Copy)]
pub struct ErrorInfo<'a> {
pub title: &'a str,
pub message: &'a str,
pub help: &'a str,
pub example: Option<&'a str>,
pub error_output: Option<&'a str>,
}
impl I18nRegistry {
/// Get the registry for a language code
pub fn new(lang: &str) -> Self {
match lang {
"zh" => Self::zh(),
_ => Self::en(),
}
}
/// Get error information
pub fn get_info(&self, code: &str) -> Option<ErrorInfo<'_>> {
Some(ErrorInfo {
title: self.titles.get(code)?,
message: self.messages.get(code)?,
help: self.helps.get(code)?,
example: self.examples.get(code).copied(),
error_output: self.error_outputs.get(code).copied(),
})
}
/// Render a template (completed at compile time, with zero runtime overhead)
pub fn render(&self, template: &'static str, params: &[(&str, String)]) -> String {
let mut result = String::with_capacity(template.len() + 64);
let mut chars = template.chars().peekable();
while let Some(c) = chars.next() {
if c == '{' {
let mut key = String::new();
while let Some(&c) = chars.peek() {
if c == '}' {
chars.next();
if let Some((_, value)) = params.iter().find(|(k, _)| k == &key) {
result.push_str(value);
} else {
result.push_str(&format!("{{{}}}", key));
}
break;
}
key.push(c);
chars.next();
}
} else {
result.push(c);
}
}
result
}
}Template Placeholders
Predefined Placeholders (Common)
| Placeholder | Purpose | Example |
|---|---|---|
{name} | Variable names, type names, trait names, and other identifiers | Unknown variable: '{name}' |
{expected} | Expected type | Expected type '{expected}' |
{found} | Actual/found type | , found type '{found}' |
{method} | Method name | Method {method} is not a function |
{trait} | Trait name | Cannot find trait: {trait} |
{path} | Module path | Invalid path: {path} |
{ty} | Type expression | Invalid type: {ty} |
{message} | Internal error message | Internal error: {message} |
Arbitrary Key Support
params supports any key and is not limited to the predefined ones. Callers can pass any key:
// Use an arbitrary key
E1001::unknown_variable(&var_name)
.param("location", "global scope")
.param("hint", "try declaring it first")
.at(span)
.build(&i18n);
// Template definition
"Unknown variable: '{name}' at {location}. {hint}"Note: Not every error code uses placeholders. Some error codes, such as E0001, use static messages and require no parameters.
Language Priority
1. yaoxiang.toml [language.default]
2. ~/.yaoxiang/yaoxiang.toml [language.default]
3. 默认值: enyaoxiang.toml Configuration
Project-Level Configuration
# yaoxiang.toml
[project]
name = "my-project"
version = "0.1.0"
[language]
# Error message language; options: en, zh, ja, ...
default = "zh"User-Level Configuration
# ~/.yaoxiang/yaoxiang.toml
[language]
default = "zh"Compile-Time Language Selection
1. 读取项目级 yaoxiang.toml 的 language.default
2. 若未配置,读取用户级 ~/.yaoxiang/yaoxiang.toml
3. 若都未配置,默认使用 "en"
4. 编译器根据选择的语言创建 I18nRegistry(一次)
5. 所有错误使用该 I18nRegistry 渲染消息Key to Zero-Lookup Overhead
Rendering occurs when the user's project is compiled, not at runtime.
┌─────────────────────────────────────────────────────────────────────────┐
│ 阶段 1: Rust 编译 YaoXiang 编译器 │
│ │
│ JSON 打包进编译器二进制 │
│ 目的:explain 指令能直接读取 i18n 数据 │
└─────────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────┐
│ 阶段 2: YaoXiang 编译用户项目(渲染发生在这里) │
│ │
│ error! 宏调用时: │
│ 1. 读取 yaoxiang.toml 获取语言偏好 │
│ 2. 从编译器二进制加载对应语言的 i18n JSON │
│ 3. 模板 + 参数 → render() → "Unknown variable: 'x'" │
│ 4. Diagnostic.message = 已渲染的字符串 │
│ │
│ AOT 二进制直接存储最终字符串,无模板,无查表 │
└─────────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────┐
│ 阶段 3: 用户程序运行时 │
│ │
│ println!("{}", diagnostic.message) │
│ // Output final string; no lookup │
└─────────────────────────────────────────────────────────────────────────┘| Component | Responsibility | Rendering time |
|---|---|---|
I18nRegistry | Provides templates and display text | When compiling the user project |
DiagnosticBuilder.render() | Template + parameters → final string | When compiling the user project |
Diagnostic.message | Rendered string | Stores the final result |
| AOT binary | Contains the final string | Used directly at runtime |
Error Message Format
Error messages use the following format:
error[E####]: <简短描述>
--> <文件>:<行>:<列>
<行> | <代码片段>
^^^<高亮>Complete Example
error[E1001]: Unknown variable: x
--> src/main.yx:5:12
5 | print(x)
^
help: Did you mean to define it?Severity Levels
Error severity is managed through the DiagnosticLevel enum, decoupled from error code numbering:
pub enum DiagnosticLevel {
Error, // Causes compilation to fail
Warning, // Does not affect compilation, but a fix is recommended
Note, // Additional information
Help, // Suggested fix
}| Level | Prefix | Description |
|---|---|---|
| Error | error[E####]: | Causes compilation to fail |
| Warning | warning[E####]: | Does not affect compilation |
| Note | note[E####]: | Additional information |
| Help | help[E####]: | Suggested fix |
yaoxiang explain Command
Command Syntax
yaoxiang explain <ERROR_CODE> [OPTIONS]Options
| Option | Description |
|---|---|
--lang <code> | Specify the language (en-US, zh-CN; default en-US) |
--json | JSON-formatted output (for IDE/LSP use) |
--json-pretty | Pretty-printed JSON output |
--examples | Show only example code |
--help | Show help information |
Usage Examples
# Default English
$ yaoxiang explain E1001
error[E1001]: Unknown variable: {name}
--> <file>:<line>:<col>
Help: Did you mean to define it?
Example:
let {name} = value;
# Chinese output
$ yaoxiang explain E1001 --lang zh
error[E1001]: 未知变量: {name}
--> <file>:<line>:<col>
帮助: 你是否想要定义它?
示例:
let {name} = value;
# JSON output (LSP integration)
$ yaoxiang explain E1001 --json
{
"code": "E1001",
"message": "Unknown variable: {name}",
"help": "Did you mean to define it?",
"examples": ["let {name} = value;"],
"language": "en-US"
}JSON Output Format
{
"code": "E1001",
"message": "Unknown variable: {name}",
"help": "Did you mean to define it?",
"examples": ["let {name} = value;"],
"language": "en-US"
}Backward Compatibility
Because this RFC designs the error code system from scratch, there are no backward compatibility issues.
Future migration strategy (for reference by later versions):
- Maintain a mapping from old error codes to new error codes
- Display both old and new codes during the migration period
- Provide a deprecation timeline
Implementation Strategy
Phase One: Error Code Infrastructure
- Create the
src/diagnostics/directory structure - Implement the
ErrorCodeenum - Implement
DiagnosticandDiagnosticLevel - Create the resource file directory and sample JSON
Phase Two: explain Command
- Implement the
yaoxiang explainCLI command - Support the
--langand--jsonoptions - Integrate resource file loading
- Implement parameter template rendering
Phase Three: Compile-Time Integration
- Update all error reporting sites to use the new system
- Implement message template parameter injection
- Add language priority logic
- Add unit test coverage
Phase Four: IDE/LSP Integration
- Integrate the LSP server with the explain JSON output
- Display error code links in the IDE
- Show error explanations on hover
- Provide quick-fix suggestions
Appendix
Complete Error Code Quick Reference
| Range | Category |
|---|---|
| E0xxx | Lexical and syntactic analysis |
| E1xxx | Type checking |
| E2xxx | Semantic analysis |
| E3xxx | Code generation |
| E4xxx | Generics and traits |
| E5xxx | Modules and imports |
| E6xxx | Runtime errors |
| E7xxx | I/O and system errors |
| E8xxx | Internal compiler errors |
| E9xxx | Reserved |
Supported Languages
| Code | Language | Status |
|---|---|---|
| en-US | English (US) | Default |
| zh-CN | Simplified Chinese | Planned |
Error Message Example Comparison
# English (en-US)
error[E1001]: Unknown variable: x
--> src/main.yx:5:12
5 | print(x)
^
help: Did you mean to define it?
# Chinese (zh-CN)
error[E1001]: 未知变量: x
--> src/main.yx:5:12
5 | print(x)
^
帮助: 你是否想要定义它?