Skip to content

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? ​

  1. User experience: Users can quickly determine the type and severity of an error from its error code
  2. Documentation organization: Grouping by category makes error reference documentation easier to write and maintain
  3. Tool integration: IDEs/LSPs can provide quick-fix suggestions and documentation links based on error codes
  4. 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 ​

PhaseRangeDescription
0E0xxxLexical and syntactic analysis
1E1xxxType checking
2E2xxxSemantic analysis
3E3xxxCode generation
4E4xxxGenerics and traits
5E5xxxModules and imports
6E6xxxRuntime errors
7E7xxxI/O and system errors
8E8xxxInternal compiler errors
9E9xxxReserved/experimental

Error Category Enum ​

rust
/// 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 text
  • locales/*.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 ​

rust
// 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 ​

rust
// 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 ​

rust
// 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 ​

rust
// 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 ​

FeatureDescription
Single BuilderOne DiagnosticBuilder works with all error codes
Type safetyShortcut methods ensure parameter correctness
Self-documentingE1001::unknown_variable(name) is immediately clear
Template separationMessage templates are separated from code, easing i18n
Zero runtime overheadCompile-time rendering; AOT binaries perform no table lookups

Error Macro Simplification ​

error! Macro (Automatic Context Injection) ​

rust
/// 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 ​

rust
// When manual control is needed
E1001::unknown_variable(&var_name)
    .at(my_span)           // Custom span
    .build(&custom_i18n)   // Custom i18n

Detailed Design ​

Error Code List ​

E0xxx: Lexical and Syntactic Analysis ​

CodeDescription
E0001Invalid character
E0002Invalid numeric literal
E0003Unterminated string
E0004Invalid character literal
E0010Expected token
E0011Unexpected token
E0012Invalid syntax
E0013Mismatched parentheses
E0014Missing semicolon
E0016Expected expression
E0018Keyword used as a name
E0019Expression nesting is too deep

E1xxx: Type Checking ​

CodeDescription
E1001Unknown variable
E1002Type mismatch
E1003Unknown type
E1010Argument count mismatch
E1011Implementation parameter annotations do not match the declaration
E1012Return type mismatch
E1013Function not found
E1014Unknown named parameter
E1015Duplicate argument specification
E1020Unable to infer type
E1021Type inference conflict
E1030Incomplete pattern
E1031Unreachable pattern
E1032Duplicate pattern binding
E1033Inconsistent or-pattern bindings
E1034Struct pattern is missing fields
E1040Unsupported operation
E1041Index out of bounds
E1042Field not found
E1043Module member not found
E1050Boolean operand required
E1051Logical NOT requires a boolean operand
E1052Invalid dereference
E1053Field access on a non-struct
E1054Conditional type mismatch
E1055Constraint in a non-generic context
E1060Type argument count mismatch
E1061Unable to instantiate generic
E1062const generic constraint failed
E1064Invalid binding position index
E1065Call on a non-function value
E1071Type 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 ✨
E1091Invalid generic meta type
E1092Illegal shape of refinement type arguments
E1093Refinement argument count mismatch
E1094Unused compile-time value parameter
E1095Unknown interface
E1096Interface argument count mismatch
E1097Interface member name conflict
E1098Interface method not implemented
E1099Interface method signature mismatch
E1100Duplicate implementation of an interface method
E1101Type does not implement the interface
E1102Loop control statement outside a loop
E1103Square brackets cannot be used in type position
E1104Interface implementation is not in the type's defining module
E1105Variant constructor cannot be accessed as a field
E1106Constraint method dispatch failed
E1107Ambiguous method overload
E1108Empty block where a container is expected
E1109return outside a function
E1110Method binding lacks a signature annotation
E1111Duplicate or invalidly ordered argument use
E1112Implementation parameter count exceeds the declaration
E1113Compile-time value parameter lacks compile-time evidence
E1114witness field cannot be read as a value
E1115witness-bearing record is immutable
E1116A 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 / E1082 will remove "Result" (? will instead be determined through the Try interface, 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 unsatisfied Equal precondition (linear token) will reuse the E1101 (type does not implement the interface) family; ③ after phase 1 is wired up, Struct == Struct will change from the E6007 runtime error to a compile-time determination, reducing the trigger surface of E6007. The registered wording in the table will remain unchanged until the implementation lands.

E2xxx: Semantic Analysis ​

CodeDescription
E2001Scope error
E2002Duplicate definition
E2003Ownership error
E2010Immutable assignment
E2011Use of uninitialized variable
E2012Mutability conflict
E2013Variable shadowing
E2014Use of moved value
E2016Immutable assignment
E2018Mutable/immutable borrow conflict
E2019Double free
E2020Use after free
E2027unsafe dereference
E2029Reference cycle within spawn
E2030Refinement constraint violation
E2031Refinement constraint cannot be proven
E2090Invalid signature
E2091Unknown type in signature
E2092Signature missing an arrow
E2093Duplicate parameter name
E2094Generic parameter shadowing
E2095Parameter name shadows a generic
E2096Signature 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 ​

CodeDescription
E3004Unsupported iterator
E3005IR generation error
E3006Unresolved variable
E3007Top-level binding initialization must be a constant
E3008Unsupported match pattern
E3014Register overflow
E3017Invalid operand (code generation)
E3018Monomorphization instantiation failed
E3019Top-level binding cyclic dependency
E3020Missing program entry point
E3021Entry point is not a function
E3022Entry point main signature mismatch
E3023Executable statements are not allowed at the top level
E3024Project configuration is unreadable

E4xxx: Generics and Traits ​

CodeDescription
E4001Generic constraint violation
E4002Trait not found
E4003Missing trait implementation
E4004Conflicting trait implementations
E4005Associated type not found
E4010Constant division by zero
E4011Constant overflow
E4012Constant recursion is too deep
E4014Constant evaluation failed
E4018Refinement predicate violation
E4019Type equality does not hold
E4020Proof function required
E4021Loop termination cannot be automatically proven
E4022Measure does not hold
E4023Cannot 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 Unproven path, and all four mechanical registration surfaces were submitted together.

  • Code: E4023
  • Category (face): Generic (E4xxx, generics and proof surface), in the same family as E4021 and E4022.
  • 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: E2031 is 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. E4023 is the generic fallback, covers Unproven at 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 to Disproved; E4023 corresponds to Unproven. 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 in src/util/diagnostic/codes/e4xxx.rs → templates and parameters in the six language files under locales/ → the E4xxx code table in this document (regenerated by the error code documentation generator) → the generated page under docs/src/reference/error-code/. All four were submitted together.

E5xxx: Modules and Imports ​

CodeDescription
E5001Module not found
E5002Import error
E5003Export not found
E5004Circular dependency
E5005Invalid module path
E5006Duplicate import
E5007Module export
E5008Import name conflict

E6xxx: Runtime Errors ​

CodeDescription
E6001Division by zero error
E6003Array index out of bounds
E6004Stack overflow
E6005Assertion failed
E6006Function not found (runtime)
E6007Runtime error
E6008Key does not exist
E6009Invalid Range step
E6010Integer parsing failed
E6011Floating-point parsing failed
E6012Invalid code point
E6013JSON 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 ​

CodeDescription
E7001File not found
E7002Permission denied
E7003I/O error
E7004Network error

E8xxx: Internal Compiler Errors ​

CodeDescription
E8001Internal compiler error
E8002Unexpected panic
E8003Compiler phase error

W1xxx: Warning Codes ​

CodeDescription
W1001Unused private function
W1002Unused private type
W1003Unused import
W1004Unused private variable
W1005Unused private method
W1006Local module shadows a dependency package
W1007Module import cycle
W1063const generic constraint cannot be evaluated
W1080Compile-time proof downgrade
W1081Termination obligation not decided
W1082Ownership analysis downgrade
W1090Obligation 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, “pub definitions are public interfaces and are never reported (#321 decision B).” The pub keyword 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 the warning[W####] prefix), but they do not block compilation or affect a successful exit code. yaoxiang check --deny-warnings escalates 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 severity at the diagnostic construction point (the E prefix defaults to Error, the W prefix 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 toward error_count, is rendered as error[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.

  1. 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.
  2. 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).
  3. Type display: Type Display must distinguish instantiated and uninstantiated forms (Expected 'Container', found 'Container' cannot distinguish bare names).
  4. 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.
  5. 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 ​

ChannelCarrierPresentation
Compiler/CLI diagnostic channelHard host-layer errors such as ExecutorErrorstderr error[E####]: (E6003/E6005/E6007 wired)
In-program error value channelError, 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 }
  • code reuses 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 E6xxx documentation 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 std Error is only a convenient fallback carrier, and its code system does not constrain the user's E type.

Code Allocation Rules ​

  1. 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.
  2. 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_CODES table in src/std/result.rs, which is subject to the same build.rs build-time gate and tools/code-tables validation as diagnostic codes.
  3. E7xxx is reserved for std.io / std.net error values (currently unused; enabled when io/net become Result-based).
  4. Emission points: Each std module constructs an Error value through error_new(code, message); on the consuming side, std.result.unwrap_err retrieves the Err carrier, and std.result.code/message reads 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 ​

json
// 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'"
  }
}
json
// 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 ​

rust
// 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) ​
PlaceholderPurposeExample
{name}Variable names, type names, trait names, and other identifiersUnknown variable: '{name}'
{expected}Expected typeExpected type '{expected}'
{found}Actual/found type, found type '{found}'
{method}Method nameMethod {method} is not a function
{trait}Trait nameCannot find trait: {trait}
{path}Module pathInvalid path: {path}
{ty}Type expressionInvalid type: {ty}
{message}Internal error messageInternal error: {message}
Arbitrary Key Support ​

params supports any key and is not limited to the predefined ones. Callers can pass any key:

rust
// 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. 默认值: en

yaoxiang.toml Configuration ​

Project-Level Configuration ​

toml
# yaoxiang.toml
[project]
name = "my-project"
version = "0.1.0"

[language]
# Error message language; options: en, zh, ja, ...
default = "zh"

User-Level Configuration ​

toml
# ~/.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                                        │
└─────────────────────────────────────────────────────────────────────────┘
ComponentResponsibilityRendering time
I18nRegistryProvides templates and display textWhen compiling the user project
DiagnosticBuilder.render()Template + parameters → final stringWhen compiling the user project
Diagnostic.messageRendered stringStores the final result
AOT binaryContains the final stringUsed 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:

rust
pub enum DiagnosticLevel {
    Error,    // Causes compilation to fail
    Warning,  // Does not affect compilation, but a fix is recommended
    Note,     // Additional information
    Help,     // Suggested fix
}
LevelPrefixDescription
Errorerror[E####]:Causes compilation to fail
Warningwarning[E####]:Does not affect compilation
Notenote[E####]:Additional information
Helphelp[E####]:Suggested fix

yaoxiang explain Command ​

Command Syntax ​

bash
yaoxiang explain <ERROR_CODE> [OPTIONS]

Options ​

OptionDescription
--lang <code>Specify the language (en-US, zh-CN; default en-US)
--jsonJSON-formatted output (for IDE/LSP use)
--json-prettyPretty-printed JSON output
--examplesShow only example code
--helpShow help information

Usage Examples ​

bash
# 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 ​

json
{
  "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):

  1. Maintain a mapping from old error codes to new error codes
  2. Display both old and new codes during the migration period
  3. Provide a deprecation timeline

Implementation Strategy ​

Phase One: Error Code Infrastructure ​

  1. Create the src/diagnostics/ directory structure
  2. Implement the ErrorCode enum
  3. Implement Diagnostic and DiagnosticLevel
  4. Create the resource file directory and sample JSON

Phase Two: explain Command ​

  1. Implement the yaoxiang explain CLI command
  2. Support the --lang and --json options
  3. Integrate resource file loading
  4. Implement parameter template rendering

Phase Three: Compile-Time Integration ​

  1. Update all error reporting sites to use the new system
  2. Implement message template parameter injection
  3. Add language priority logic
  4. Add unit test coverage

Phase Four: IDE/LSP Integration ​

  1. Integrate the LSP server with the explain JSON output
  2. Display error code links in the IDE
  3. Show error explanations on hover
  4. Provide quick-fix suggestions

Appendix ​

Complete Error Code Quick Reference ​

RangeCategory
E0xxxLexical and syntactic analysis
E1xxxType checking
E2xxxSemantic analysis
E3xxxCode generation
E4xxxGenerics and traits
E5xxxModules and imports
E6xxxRuntime errors
E7xxxI/O and system errors
E8xxxInternal compiler errors
E9xxxReserved

Supported Languages ​

CodeLanguageStatus
en-USEnglish (US)Default
zh-CNSimplified ChinesePlanned

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)
          ^
          帮助: 你是否想要定义它?

References ​