Skip to content

Rust API ​

The crate is named your_language. It exposes compilation, artifact loading, parsing, structured ASTs, diagnostics, and inspection of the YL frontend. All source offsets are UTF-8 byte offsets.

compile_language ​

rust
pub fn compile_language(
    entry_file: impl AsRef<std::path::Path>,
) -> CompileResult<CompiledLanguage>

Compiles a filesystem entry module and its dependency graph. Relative imports resolve from the importing module. The compiler loads embedded core/parser and std/parser modules as needed. Compile failures return Vec<Diagnostic> through CompileResult; non-fatal diagnostics are retained on the compiled language.

rust
fn example() -> your_language::diagnostic::CompileResult<()> {
    let language = your_language::compile_language("examples/03-mini-js/definition/minijs.yl")?;
    for diagnostic in language.diagnostics() {
        eprintln!("{}", diagnostic.message);
    }
    Ok(())
}

compile_sources ​

rust
pub fn compile_sources(
    entry: &str,
    sources: &std::collections::BTreeMap<String, String>,
) -> CompileResult<CompiledLanguage>

Compiles an in-memory module graph. Map keys are module IDs, and values are YL source. Relative imports resolve against the importing ID, normalizing . and ..; omitted extensions become .yl. Every non-embedded imported module must be provided in the map. The compiler follows the graph reachable from the supplied entry rather than treating unrelated map entries as language modules.

rust
fn example() -> your_language::diagnostic::CompileResult<()> {
    use std::collections::BTreeMap;
    use your_language::{compile_sources, parse};

    let sources = BTreeMap::from([
        (
            "names.yl".into(),
            "export node Name = value: /[A-Za-z]+/".into(),
        ),
        (
            "entry.yl".into(),
            r#"
        import { Name } from "./names"
        node Greeting = "hello:" name: Name
        entry Greeting
    "#
            .into(),
        ),
    ]);
    let language = compile_sources("entry.yl", &sources)?;
    let result = parse(&language, "hello:world");
    assert!(!result.has_errors());
    Ok(())
}

CompiledLanguage ​

CompiledLanguage is a checked, immutable executable language handle. Callers compile or load it rather than assembling one manually. The engine executes indexed parser, check, and query tables directly.

rust
impl CompiledLanguage {
    pub fn diagnostics(&self) -> &[Diagnostic];
    pub fn to_bytes(&self) -> CompileResult<Vec<u8>>;
    pub fn executable_image(&self) -> &your_language::image::LanguageImage;
}

diagnostics() returns non-fatal definition diagnostics. to_bytes() serializes the artifact deterministically. Definition warnings/help are not serialized; runtime constraint checks are. See artifacts.

load_compiled_language ​

rust
pub fn load_compiled_language(bytes: &[u8]) -> CompileResult<CompiledLanguage>

Deserializes and validates an artifact before returning it. Invalid JSON, unsupported formats, and invalid normalized references or checks produce diagnostics. Only checked compilation and loading construct a CompiledLanguage; direct Serde deserialization of image tables does not produce an executable handle.

parse and parse_named ​

rust
pub fn parse(language: &CompiledLanguage, source: &str) -> ParseResult;
pub fn parse_named(language: &CompiledLanguage, file: &str, source: &str) -> ParseResult;

Both parse from the declared entry and require the input to be consumed apart from selected trivia. parse uses <source> as the file name. parse_named preserves the caller's file label in AST and target-source diagnostic spans. Neither function loads source from disk.

rust
fn inspect(language: &your_language::CompiledLanguage) {
    let result = your_language::parse_named(language, "settings.txt", "source text");
    if result.has_errors() {
        for diagnostic in &result.diagnostics {
            eprintln!("{}: {}", diagnostic.code, diagnostic.message);
        }
    }
    if let Some(ast) = result.ast {
        println!("{}", ast.kind);
    }
}

ParseResult ​

rust
pub struct ParseResult {
    pub ast: Option<AstNode>,
    pub diagnostics: Vec<Diagnostic>,
}
impl ParseResult {
    pub fn has_errors(&self) -> bool;
}

has_errors() checks for error severity. Warnings/help alone do not count as errors. A parse failure has no AST; a successful match with a constraint error can retain its AST. Callers should inspect both fields rather than equating AST presence with validity.

Frontend inspection ​

rust
pub fn parse_yl(file: &str, source: &str) -> CompileResult<syntax::Module>;

Parses one YL source into a spanned surface AST without resolving imports or validating the complete language. The public syntax module models declarations, grammar expressions, condition expressions, argument lists, and source spans. Use this API for source inspection; use compilation for executable language validation.

The image module exposes indexed executable tables for inspection and Serde support. CompiledLanguage::executable_image() provides a read-only view. The ir module contains compiler normalization types; these recursive types are not the serialized format and are not reconstructed by the loader. Artifact documentation describes the intended boundary. Generated Rust documentation gives exhaustive field and enum definitions:

sh
cargo doc --no-deps --open

Experimental native analysis ​

SemanticEngine provides registry-aware compile, analyze, and compile_and_analyze methods, plus optional checked artifact loading. The engine loads authored reference and type libraries over generic attachment queries and supports custom native libraries through the same interface. The parse APIs above return syntax; CLI language checks also execute authored diagnostics.

format_yl ​

rust
pub fn format_yl(file: &str, source: &str) -> CompileResult<String>;

Formats a YL definition module from memory. The file label is used only in diagnostic spans; the function does not read or write files or resolve imports. The editor uses this formatter to replace a definition document with the returned text.

rust
let formatted = your_language::format_yl("language.yl", "node Name=/[a-z]+/ entry Name")?;
assert_eq!(your_language::format_yl("language.yl", &formatted)?, formatted);

The formatter uses the actual lexer and parser. It preserves comments and raw string/regex spelling, then verifies token preservation and parse-equivalence apart from spans. The standalone structural boundary marker is normalized to the top of its semantics block; all other tokens retain their order, and meaning operations are never reordered. Invalid syntax returns the same structured frontend diagnostics. Unsupported preservation failures return yl.format_equivalence with no formatted output. Default formatting is deterministic and idempotent, with no hard line wrapping. See CLI formatting for file-writing and check modes.

Match alignment options ​

rust
use your_language::{format_yl_with_options, FormatOptions};

let options = FormatOptions { align_match_arrows: true };
let formatted = format_yl_with_options("language.yl", source, options)?;
assert_eq!(format_yl_with_options("language.yl", &formatted, options)?, formatted);

FormatOptions::default() and format_yl align meaning-match arrows as part of canonical formatting. The editor receives the same layout through the default formatter API or CLI. Alignment uses individual meaning-match blocks, and the normal token and AST preservation checks still apply. The explicit library option align_match_arrows: false can request unaligned arrows; there is no CLI opt-out. See CLI formatting for the alignment limits and header exclusions.

Declarative languages. Reusable tools.