Public C++20 Interface — Include <stag/Stag.hpp> and link stag_lib. The public header exposes zero LLVM headers to downstream embedders.

Stag C++20 Embedding and Tooling API Reference

This document is the complete specification for the public C++20 library interface exposed by include/stag/Stag.hpp (namespace stag::api). External tools — linters, language servers, documentation generators, static analyzers, code formatters, refactoring utilities, test harnesses, and custom backends — include <stag/Stag.hpp> and link against stag_lib to invoke any stage of the Stag compiler in-process.


Table of Contents

  1. Architecture and Pipeline Entry Points
  2. CMake Integration and Build Contracts
  3. Ownership, Lifetime, Error Handling, and Thread Safety
  4. Version Metadata
  5. Source Span Resolution and Top-Level Symbol Inspection
  6. Stage 1: Lexical Analysis (lex)
  7. Stage 2: Parsing and AST Construction (parse, parseFile)
  8. Stage 3: Formatting and Style Policy Validation (format, checkStyle)
  9. Stage 4: Multi-Module Loading (loadModules, loadModulesFromFile)
  10. Stage 5: Static Analysis, HIR, SZSM, Parallelizer, and Hints (analyze, analyzeFile)
  11. Stage 6: Code Generation and LLVM IR (compileToLlvmIr, compileFileToLlvmIr)
  12. Embedded Standard Kit Inspection
  13. Diagnostic Codes and Rendering Format
  14. End-to-End Tool Examples

1. Architecture and Pipeline Entry Points

Each stag::api function enters the compiler pipeline at a well-defined stage and stops as soon as the requested artifact is built:

diagram
flowchart LR
    IN["UTF-8 Source Buffer or File Path"] --> S1["stag::api::lex()\n-> LexOutput (tokens, comments)"]
    S1 --> S2["stag::api::parse() / parseFile()\n-> ParseOutput (ast::Program, dumpAst)"]
    S2 --> SYM["stag::api::collectTopLevelSymbols()\n-> vector<SymbolSummary>"]
    S2 --> S3A["stag::api::format()\n-> FormatOutput (beta, E1999 check)"]
    S2 --> S3B["stag::api::checkStyle()\n-> StyleCheckOutput (E5001..E5012)"]
    S2 --> S4["stag::api::loadModules()\n-> ModuleLoadOutput (ModuleGraph)"]
    S4 --> S5["stag::api::analyze() / analyzeFile()\n-> AnalysisOutput (HIR, SZSM, Par, Hints)"]
    S5 --> S6["stag::api::compileToLlvmIr()\n-> CompileIrOutput (verified LLVM IR)"]
Use CaseRecommended Entry Point(s)Executes LLVM?
Syntax highlighter / token counterlexNo
Formatter / AST linter / doc extractor / symbol outlineparse, parseFile, collectTopLevelSymbols, format, checkStyleNo
Dependency graph inspectorloadModules, loadModulesFromFileNo
Type checker / IDE server / escape & race analyzer / hint auditoranalyze, analyzeFileNo
Custom backend / IR pass / JIT / verifiercompileToLlvmIr, compileFileToLlvmIrYes

2. CMake Integration and Build Contracts

CMake Consumer Configuration

Include the stag source directory via add_subdirectory and link against stag_lib:

cmake
cmake_minimum_required(VERSION 3.20)
project(my_stag_tool LANGUAGES CXX)

set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)

# Disable compiler tests when embedding stag_lib in an external project.
set(STAG_BUILD_TESTS OFF CACHE BOOL "" FORCE)
add_subdirectory(path/to/stag)

add_executable(my_stag_tool main.cpp)
target_link_libraries(my_stag_tool PRIVATE stag_lib)

stag_lib exports its public include path (include/) and required LLVM include directories and compile definitions automatically via CMake PUBLIC target properties.

Build Requirements and Flags

  • C++ Standard: C++20 (-std=c++20).
  • LLVM Dependency: LLVM 20 or newer (find_package(LLVM REQUIRED CONFIG)).
  • Exceptions: stag_lib is compiled with -fno-exceptions. All stag::api functions report errors through DiagnosticEngine and ok() without throwing C++ exceptions.
  • RTTI: stag_lib propagates -fno-rtti when LLVM was built with LLVM_ENABLE_RTTI=OFF.
  • Single-Include Header: #include <stag/Stag.hpp> transitively includes all public Stag compiler headers (Ast.hpp, Diagnostics.hpp, Driver.hpp, EmbeddedKit.hpp, FormatConfig.hpp, Formatter.hpp, HintAnalysis.hpp, Hir.hpp, Lexer.hpp, MemoryAnalysis.hpp, ModuleLoader.hpp, Optimizer.hpp, Parser.hpp, Sema.hpp, SourceManager.hpp, Token.hpp, Type.hpp).

3. Ownership, Lifetime, Error Handling, and Thread Safety

Ownership Model

Every result object returned by stag::api is self-owning:

text
Result Object (e.g. ParseOutput / AnalysisOutput)
├── sources      (SourceManager)     <-- owns all source file buffers & line tables
├── diagnostics  (DiagnosticEngine)  <-- owns all Diagnostic records (Spans point into `sources`)
└── program / graph / hir            <-- owns AST/HIR trees (Spans point into `sources`)
  • Any Span inside returned Token, ast::Program, hir::Program, or Diagnostic objects references FileId indices owned by the result struct's sources member. Keep the result struct alive while resolving spans or rendering diagnostics.
  • Result structs are movable (std::move).

Error Handling Contract

  1. Check result.ok() before consuming parsed/analyzed/compiled outputs.
  2. Inspect structured diagnostics via result.diagnostics.diagnostics() (severity, code, message, span, notes, helps) or render human-readable text via result.renderDiagnostics(useColor).
  3. File-reading entry points (parseFile, loadModulesFromFile, analyzeFile, compileFileToLlvmIr) report I/O errors as Severity::Error with diagnostic code "E0000".

Thread Safety

Each call to stag::api::* instantiates isolated SourceManager, DiagnosticEngine, and (when emitting IR) llvm::LLVMContext objects on the stack/result struct. Independent calls from multiple threads share no mutable global state.


4. Version Metadata

All version values are populated at CMake configure time from the repository VERSION file (or -DSTAG_VERSION=<semver>).

FunctionReturn TypeDescription
stag::api::version()std::string_viewFull semantic version string (e.g. "0.1.0" or "1.0.0-rc.1").
stag::api::versionMajor()intMajor version component.
stag::api::versionMinor()intMinor version component.
stag::api::versionPatch()intPatch version component.

5. Source Span Resolution and Top-Level Symbol Inspection

struct ResolvedLocation

FieldTypeDefaultDescription
filePathstd::string""Display or filesystem path of the buffer owning the span.
startLineuint32_t01-based inclusive start line number.
startColumnuint32_t01-based inclusive start column number (byte offset in line).
endLineuint32_t01-based end line number.
endColumnuint32_t01-based end column number.
validboolfalsetrue if span resolved to a registered SourceFile.

enum class SymbolKind : uint8_t

Values: Import, Constant, Static, ExternGlobal, Record, Union, Choice, Trait, Attach, Function, Test.

struct SymbolSummary

FieldTypeDescription
kindSymbolKindDeclaration category.
namestd::stringIdentifier (dotted module path for Import, Type : Trait for trait Attach, test string literal for Test).
isPublicbooltrue if declared with pub.
isExternbooltrue if declared with extern.
isConstbooltrue for const, const func, and immutable static/extern const.
spanSpanRaw byte-offset span in SourceManager.
locationResolvedLocationPre-resolved file path and 1-based line/column range.

Functions

  • ResolvedLocation resolveSpan(const SourceManager &sources, Span span)
  • std::string_view symbolKindName(SymbolKind kind) noexcept
  • std::vector<SymbolSummary> collectTopLevelSymbols(const ast::Program &program, const SourceManager &sources)
  • Returns top-level declarations sorted by ascending source offset (span.begin). Inline method attach blocks already nested inside record/choice declarations are omitted so declarations are not duplicated.

Input / Output Example (collectTopLevelSymbols)

Input (sample.stag):

stag
const LIMIT: i64 = 10
pub record Vec2:
    x: i64
    y: i64
pub func add(a: i64, b: i64) -> i64 = a + b
test "basic":
    _ := add(1, 2)

Output (SymbolSummary entries):

text
constant  LIMIT  (pub=false, const=true)  @ sample.stag:1:1-1:22
record    Vec2   (pub=true,  const=false) @ sample.stag:2:1-4:11
function  add    (pub=true,  const=false) @ sample.stag:5:1-5:43
test      basic  (pub=false, const=false) @ sample.stag:6:1-7:18

6. Stage 1: Lexical Analysis (lex)

struct LexOptions

FieldTypeDefaultDescription
trackIndentationbooltrueEmit TokenKind::Indent and TokenKind::Dedent for indentation blocks.
captureCommentsbooltrueRecord // and /* ... */ comments in LexOutput::comments.
maxErrorssize_t64Maximum diagnostic errors recorded before truncation.

struct LexOutput

MemberTypeDescription
sourcesSourceManagerOwns the lexed source buffer.
diagnosticsDiagnosticEngineLexer diagnostics (E0001..E0099).
fileIdFileIdFileId assigned inside sources.
tokensstd::vector<Token>Token sequence terminated by TokenKind::Eof.
commentsstd::vector<Comment>Captured comments (offset range, trailing flag, raw text).
ok()bool!diagnostics.hasErrors().
renderDiagnostics(useColor)std::stringFormatted diagnostics with source excerpts.

Function

cpp
[[nodiscard]] LexOutput lex(std::string_view source,
                            std::string virtualPath = "<memory.stag>",
                            const LexOptions &options = {});

Input / Output Example (lex)

Input: func id(x: i64) -> i64 = x\n

Output (tokens):

text
KwFunc("func"), Ident("id"), LParen("("), Ident("x"), Colon(":"),
KwI64("i64"), RParen(")"), Arrow("->"), KwI64("i64"), Eq("="),
Ident("x"), Newline, Eof

7. Stage 2: Parsing and AST Construction (parse, parseFile)

struct ParseOptions

FieldTypeDefaultDescription
captureCommentsbooltrueCapture comments in ParseOutput::comments.
maxErrorssize_t64Maximum diagnostic errors recorded.

struct ParseOutput

MemberTypeDescription
sourcesSourceManagerOwns the parsed source buffer.
diagnosticsDiagnosticEngineLexer (E0xxx) and parser (E1xxx) diagnostics.
fileIdFileIdFileId of the parsed buffer.
tokensstd::vector<Token>Full token stream.
commentsstd::vector<Comment>Captured comments.
programast::ProgramParsed AST (imports, constants, statics, externGlobals, records, choices, traits, onBlocks, functions, tests).
ok()bool!diagnostics.hasErrors().
dumpAst()std::stringIndented textual AST dump.
renderDiagnostics(useColor)std::stringFormatted diagnostics.

Functions

cpp
[[nodiscard]] ParseOutput parse(std::string_view source,
                                std::string virtualPath = "<memory.stag>",
                                const ParseOptions &options = {});

[[nodiscard]] ParseOutput parseFile(const std::string &filePath,
                                    const ParseOptions &options = {});

Input / Output Example (parse + dumpAst)

Input:

stag
func add(a: i64, b: i64) -> i64 = a + b

Output (parsed.dumpAst()):

text
Program
  Fn add(a: i64, b: i64) -> i64
    Binary +
      Ident a
      Ident b

8. Stage 3: Formatting and Style Policy Validation (format, checkStyle)

Formatting (format)

cpp
[[nodiscard]] FormatOutput format(std::string_view source,
                                  std::string virtualPath = "<memory.stag>",
                                  const FormatOptions &options = {});

FormatOptions fields: indentWidth (4), indentStyle (Spaces | Tabs), blockStyle (Indent | Braces | End), semicolons (Optional | Required | Forbidden). Use FormatOptions::fromConfig(cfg) to derive options from a FormatConfig.

Beta Status: The formatter is currently marked beta. Before returning success = true, it runs an internal re-lex and re-parse verification pass (E1999) so parse-clean source code is never silently corrupted.

Input / Output Example (format)

Input: func add( a:i64,b:i64 ) -> i64 = a+b\n Output (out.formatted): func add(a: i64, b: i64) -> i64 = a + b\n

Configuration & Style Validation

cpp
[[nodiscard]] std::optional<FormatConfig> parseFormatConfig(std::string_view jsonText,
                                                            std::string &errorOut);

[[nodiscard]] std::optional<FormatConfig> loadFormatConfig(const std::string &configPath,
                                                           std::string &errorOut);

[[nodiscard]] std::optional<std::string> findFormatConfig(const std::string &sourcePath);

[[nodiscard]] StyleCheckOutput checkStyle(std::string_view source, const FormatConfig &config,
                                          std::string virtualPath = "<memory.stag>",
                                          bool runtimeChecksEnabled = true);

Input / Output Example (checkStyle)

Config JSON: {"require_return_type": true, "naming_functions": "snake_case"} Input: func BadName(x: i64) = x\n Output (out.ok() == false, out.renderDiagnostics()):

text
ERROR E5007 (bad.stag:1:1): function 'BadName' must declare an explicit return type (format.json: require_return_type)
ERROR E5010 (bad.stag:1:1): function name 'BadName' violates naming_functions policy 'snake_case'

9. Stage 4: Multi-Module Loading (loadModules, loadModulesFromFile)

struct LoadOptions

FieldTypeDefaultDescription
importPathsstd::vector<std::string>{}Extra search directories for use module resolution.
virtualFilesstd::unordered_map<std::string, std::string>{}In-memory virtual module buffers keyed by path (useful for IDEs and unsaved editor tabs).
kitPathstd::string""Optional filesystem override for kit.* modules.
enableEmbeddedKitbooltrueResolve use kit.* from the embedded Standard Kit.
maxErrorssize_t64Diagnostic error limit.

struct ModuleLoadOutput

Contains sources, diagnostics, graph (ModuleGraph, where graph.modules[0] is always the root module and graph.modules[i].imports holds resolved ModuleId edges), ok(), and renderDiagnostics(useColor).

Functions

cpp
[[nodiscard]] ModuleLoadOutput loadModules(std::string_view rootSource,
                                           std::string rootPath = "<memory.stag>",
                                           const LoadOptions &options = {});

[[nodiscard]] ModuleLoadOutput loadModulesFromFile(const std::string &rootFilePath,
                                                   const LoadOptions &options = {});

10. Stage 5: Static Analysis, HIR, SZSM, Parallelizer, and Hints (analyze, analyzeFile)

struct AnalyzeOptions

FieldTypeDefaultDescription
loadLoadOptionsdefaultModule loader options.
runMemoryAnalysisbooltrueExecute MemoryAnalyzer (SZSM escape/borrow proofs + auto-parallelizer).
parModehir::ParModeOffOff, Auto, Force, or Autotune.
runHintAnalysisbooltrueExecute HintAnalyzer (auto hints + W6001..W6008 contradiction checks).
warningsAsErrorsboolfalsePromote all warnings to hard errors.

struct AnalysisOutput

MemberTypeDescription
sourcesSourceManagerAll loaded module buffers.
diagnosticsDiagnosticEngineAll diagnostics across load, sema, SZSM, and hints.
graphModuleGraphParsed AST module graph.
hirhir::ProgramTyped HIR program (types, symbols, functions, memory effects, parallelization certificates, hints).
memoryAnalyzedbooltrue if MemoryAnalyzer completed.
hintsAnalyzedbooltrue if HintAnalyzer completed.
ok()bool!diagnostics.hasErrors().
dumpHir()std::stringTextual HIR dump.
dumpMemoryReport()std::stringSZSM memory effect & loop proof certificates (empty if runMemoryAnalysis == false).
dumpParallelReport()std::stringAuto-parallelizer decisions & cost model report (empty if runMemoryAnalysis == false).
dumpHintReport()std::stringManual and inferred optimization hint report (empty if runHintAnalysis == false).
renderDiagnostics(useColor)std::stringFormatted diagnostics.

Functions

cpp
[[nodiscard]] AnalysisOutput analyze(std::string_view rootSource,
                                     std::string rootPath = "<memory.stag>",
                                     const AnalyzeOptions &options = {});

[[nodiscard]] AnalysisOutput analyzeFile(const std::string &rootFilePath,
                                         const AnalyzeOptions &options = {});

Input / Output Example (analyze with parMode = Auto)

Input:

stag
func scale_add(dst: []mut i64, src: []i64, k: i64):
    for i in 0..dst.len:
        dst[i] = src[i] * k + 1

Outputs:

  • out.dumpMemoryReport():
text
=== Stag Memory & Parallelism Proof Certificates (SZSM v0.1.0) ===
func scale_add:
  effect: ArgMemReadWrite
  param dst ([]mut i64): writeonly nocapture
  param src ([]i64): readonly nocapture
  loop #0 (iv=i): [PAR-PROVED: Independent] — Bernstein-proved: W(i) ∩ W(j) = ∅ and W(i) ∩ R(j) = ∅ for all i != j
  • out.dumpParallelReport():
text
=== Stag Auto-Parallelization Report (v0.1.0, mode=auto) ===
func scale_add:
  loop #0 (iv=i): [PARALLELIZED site #0 | PAR-PROVED: Independent] cost~8cyc/iter, min_trips=14063
    proof: Bernstein-proved: W(i) ∩ W(j) = ∅ and W(i) ∩ R(j) = ∅ for all i != j
Summary: 1 loop(s) analyzed, 1 mathematically proved parallel-safe, 1 scheduled for parallel execution.
  • out.dumpHintReport():
text
=== Stag Optimization Hint Report (v0.1.0) ===
  scale_add [loop #0]: @vectorize (auto) - innermost Bernstein-proved independent/reduction loop
Summary: 1 hint(s) (1 auto, 0 manual)

11. Stage 6: Code Generation and LLVM IR (compileToLlvmIr, compileFileToLlvmIr)

struct CompileIrOptions

FieldTypeDefaultDescription
loadLoadOptionsdefaultModule loader options.
optLevelOptLevelO0LLVM optimization level (O0, O1, O2, O3, Os, Oz).
parModehir::ParModeOffAuto-parallelizer mode.
parThreadsint32_t0Worker thread count (0 = hardware core count).
targetTriplestd::string""Target triple (empty = host target).
targetCpustd::string""Target CPU ("", "native", or explicit LLVM CPU name).
targetFeaturesstd::string""Extra LLVM CPU features (e.g. "+avx2,+fma").
debugInfoboolfalseEmit DWARF/CodeView debug metadata.
runtimeChecksbooltrueEnable bounds, division-by-zero, and overflow checks.
warningsAsErrorsboolfalsePromote warnings to errors.
testModeboolfalseEmit test harness entry point for test "..." blocks.

struct CompileIrOutput

Contains sources, diagnostics, success, llvmIr (verified LLVM IR string), testNames (discovered root test "..." names), ok(), and renderDiagnostics(useColor).

Functions

cpp
[[nodiscard]] CompileIrOutput compileToLlvmIr(std::string_view rootSource,
                                              std::string rootPath = "<memory.stag>",
                                              const CompileIrOptions &options = {});

[[nodiscard]] CompileIrOutput compileFileToLlvmIr(const std::string &rootFilePath,
                                                  const CompileIrOptions &options = {});

Input / Output Example (compileToLlvmIr, optLevel = O2)

Input: func main() -> i32 = 42\n

Output (out.llvmIr, excerpt):

llvm
define dso_local noundef i32 @main() local_unnamed_addr #0 {
entry:
  ret i32 42
}

12. Embedded Standard Kit Inspection

FunctionReturn TypeDescription
listEmbeddedKitModules()std::vector<std::string_view>Returns all embedded kit/*.stag relative paths compiled into stag_lib (18 modules: kit/alloc.stag .. kit/time.stag).
getEmbeddedKitSource(relPath)std::optional<std::string_view>Returns the UTF-8 source text of an embedded kit module (e.g. "kit/io.stag"), or std::nullopt if absent.

13. Diagnostic Codes and Rendering Format

All renderDiagnostics(bool useColor) methods format diagnostics identically to stagc:

text
ERROR E2015 (app.stag:4:12): undefined identifier 'unknown_var'
  4 :     return unknown_var
    :            ^^^^^^^^^^^
summary: 1 error, 0 warnings
Code PrefixOrigin
E0000File I/O error in *File API helpers
E0001..E0099Lexer errors
E1000..E1101Parser and legacy syntax errors
E1999Internal formatter safety re-parse check failure
E2000..E2199 / W2001..W2099Semantic analyzer errors and warnings
E4001..E4009SZSM memory safety and borrow errors
E5000..E5012format.json configuration and style policy errors
E6001..E6003 / W6001..W6008Optimization hint syntax errors and contradiction warnings
E8001..E8009Backend, target lookup, and code emission errors

14. End-to-End Tool Examples

Example 1: Public API Extractor / Documentation Generator

cpp
#include <stag/Stag.hpp>
#include <iostream>

int main(int argc, char **argv) {
    if (argc < 2) return 1;

    auto parsed = stag::api::parseFile(argv[1]);
    if (!parsed.ok()) {
        std::cerr << parsed.renderDiagnostics(false);
        return 1;
    }

    for (const auto &sym : stag::api::collectTopLevelSymbols(parsed.program, parsed.sources)) {
        if (!sym.isPublic) continue;
        std::cout << stag::api::symbolKindName(sym.kind) << " " << sym.name
                  << " (" << sym.location.filePath << ":" << sym.location.startLine << ")\n";
    }
    return 0;
}

Example 2: Multi-File Virtual Overlay Static Analyzer (IDE / In-Memory Linter)

cpp
#include <stag/Stag.hpp>
#include <iostream>

int main() {
    stag::api::AnalyzeOptions opts;
    opts.load.enableEmbeddedKit = false;
    opts.load.virtualFiles["math_util.stag"] =
        "pub func square(x: i64) -> i64 = x * x\n";
    opts.runMemoryAnalysis = true;
    opts.parMode = stag::hir::ParMode::Auto;
    opts.runHintAnalysis = true;

    const char *rootSrc = R"(
use math_util (square)

func fill_squares(dst: []mut i64):
    for i in 0..dst.len:
        dst[i] = square(i)
)";

    auto res = stag::api::analyze(rootSrc, "app.stag", opts);
    if (!res.ok()) {
        std::cerr << res.renderDiagnostics(false);
        return 1;
    }

    std::cout << res.dumpMemoryReport() << "\n"
              << res.dumpParallelReport() << "\n"
              << res.dumpHintReport();
    return 0;
}

Example 3: Compiling to Optimized LLVM IR with Host CPU Targeting

cpp
#include <stag/Stag.hpp>
#include <iostream>

int main() {
    stag::api::CompileIrOptions opts;
    opts.load.enableEmbeddedKit = false;
    opts.optLevel = stag::OptLevel::O3;
    opts.targetCpu = "native";

    auto res = stag::api::compileToLlvmIr("func main() -> i32 = 42\n", "main.stag", opts);
    if (!res.ok()) {
        std::cerr << res.renderDiagnostics(false);
        return 1;
    }

    std::cout << res.llvmIr;
    return 0;
}