<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
- Architecture and Pipeline Entry Points
- CMake Integration and Build Contracts
- Ownership, Lifetime, Error Handling, and Thread Safety
- Version Metadata
- Source Span Resolution and Top-Level Symbol Inspection
- Stage 1: Lexical Analysis (
lex) - Stage 2: Parsing and AST Construction (
parse,parseFile) - Stage 3: Formatting and Style Policy Validation (
format,checkStyle) - Stage 4: Multi-Module Loading (
loadModules,loadModulesFromFile) - Stage 5: Static Analysis, HIR, SZSM, Parallelizer, and Hints (
analyze,analyzeFile) - Stage 6: Code Generation and LLVM IR (
compileToLlvmIr,compileFileToLlvmIr) - Embedded Standard Kit Inspection
- Diagnostic Codes and Rendering Format
- 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:
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 Case | Recommended Entry Point(s) | Executes LLVM? |
|---|---|---|
| Syntax highlighter / token counter | lex | No |
| Formatter / AST linter / doc extractor / symbol outline | parse, parseFile, collectTopLevelSymbols, format, checkStyle | No |
| Dependency graph inspector | loadModules, loadModulesFromFile | No |
| Type checker / IDE server / escape & race analyzer / hint auditor | analyze, analyzeFile | No |
| Custom backend / IR pass / JIT / verifier | compileToLlvmIr, compileFileToLlvmIr | Yes |
2. CMake Integration and Build Contracts
CMake Consumer Configuration
Include the stag source directory via add_subdirectory and link against stag_lib:
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_libis compiled with-fno-exceptions. Allstag::apifunctions report errors throughDiagnosticEngineandok()without throwing C++ exceptions. - RTTI:
stag_libpropagates-fno-rttiwhen LLVM was built withLLVM_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:
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
Spaninside returnedToken,ast::Program,hir::Program, orDiagnosticobjects referencesFileIdindices owned by the result struct'ssourcesmember. Keep the result struct alive while resolving spans or rendering diagnostics. - Result structs are movable (
std::move).
Error Handling Contract
- Check
result.ok()before consuming parsed/analyzed/compiled outputs. - Inspect structured diagnostics via
result.diagnostics.diagnostics()(severity,code,message,span,notes,helps) or render human-readable text viaresult.renderDiagnostics(useColor). - File-reading entry points (
parseFile,loadModulesFromFile,analyzeFile,compileFileToLlvmIr) report I/O errors asSeverity::Errorwith 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>).
| Function | Return Type | Description |
|---|---|---|
stag::api::version() | std::string_view | Full semantic version string (e.g. "0.1.0" or "1.0.0-rc.1"). |
stag::api::versionMajor() | int | Major version component. |
stag::api::versionMinor() | int | Minor version component. |
stag::api::versionPatch() | int | Patch version component. |
5. Source Span Resolution and Top-Level Symbol Inspection
struct ResolvedLocation
| Field | Type | Default | Description |
|---|---|---|---|
filePath | std::string | "" | Display or filesystem path of the buffer owning the span. |
startLine | uint32_t | 0 | 1-based inclusive start line number. |
startColumn | uint32_t | 0 | 1-based inclusive start column number (byte offset in line). |
endLine | uint32_t | 0 | 1-based end line number. |
endColumn | uint32_t | 0 | 1-based end column number. |
valid | bool | false | true 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
| Field | Type | Description |
|---|---|---|
kind | SymbolKind | Declaration category. |
name | std::string | Identifier (dotted module path for Import, Type : Trait for trait Attach, test string literal for Test). |
isPublic | bool | true if declared with pub. |
isExtern | bool | true if declared with extern. |
isConst | bool | true for const, const func, and immutable static/extern const. |
span | Span | Raw byte-offset span in SourceManager. |
location | ResolvedLocation | Pre-resolved file path and 1-based line/column range. |
Functions
ResolvedLocation resolveSpan(const SourceManager &sources, Span span)std::string_view symbolKindName(SymbolKind kind) noexceptstd::vector<SymbolSummary> collectTopLevelSymbols(const ast::Program &program, const SourceManager &sources)- Returns top-level declarations sorted by ascending source offset (
span.begin). Inline methodattachblocks already nested insiderecord/choicedeclarations are omitted so declarations are not duplicated.
Input / Output Example (collectTopLevelSymbols)
Input (sample.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):
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:186. Stage 1: Lexical Analysis (lex)
struct LexOptions
| Field | Type | Default | Description |
|---|---|---|---|
trackIndentation | bool | true | Emit TokenKind::Indent and TokenKind::Dedent for indentation blocks. |
captureComments | bool | true | Record // and /* ... */ comments in LexOutput::comments. |
maxErrors | size_t | 64 | Maximum diagnostic errors recorded before truncation. |
struct LexOutput
| Member | Type | Description |
|---|---|---|
sources | SourceManager | Owns the lexed source buffer. |
diagnostics | DiagnosticEngine | Lexer diagnostics (E0001..E0099). |
fileId | FileId | FileId assigned inside sources. |
tokens | std::vector<Token> | Token sequence terminated by TokenKind::Eof. |
comments | std::vector<Comment> | Captured comments (offset range, trailing flag, raw text). |
ok() | bool | !diagnostics.hasErrors(). |
renderDiagnostics(useColor) | std::string | Formatted diagnostics with source excerpts. |
Function
[[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):
KwFunc("func"), Ident("id"), LParen("("), Ident("x"), Colon(":"),
KwI64("i64"), RParen(")"), Arrow("->"), KwI64("i64"), Eq("="),
Ident("x"), Newline, Eof7. Stage 2: Parsing and AST Construction (parse, parseFile)
struct ParseOptions
| Field | Type | Default | Description |
|---|---|---|---|
captureComments | bool | true | Capture comments in ParseOutput::comments. |
maxErrors | size_t | 64 | Maximum diagnostic errors recorded. |
struct ParseOutput
| Member | Type | Description |
|---|---|---|
sources | SourceManager | Owns the parsed source buffer. |
diagnostics | DiagnosticEngine | Lexer (E0xxx) and parser (E1xxx) diagnostics. |
fileId | FileId | FileId of the parsed buffer. |
tokens | std::vector<Token> | Full token stream. |
comments | std::vector<Comment> | Captured comments. |
program | ast::Program | Parsed AST (imports, constants, statics, externGlobals, records, choices, traits, onBlocks, functions, tests). |
ok() | bool | !diagnostics.hasErrors(). |
dumpAst() | std::string | Indented textual AST dump. |
renderDiagnostics(useColor) | std::string | Formatted diagnostics. |
Functions
[[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:
func add(a: i64, b: i64) -> i64 = a + bOutput (parsed.dumpAst()):
Program
Fn add(a: i64, b: i64) -> i64
Binary +
Ident a
Ident b8. Stage 3: Formatting and Style Policy Validation (format, checkStyle)
Formatting (format)
[[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
[[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()):
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
| Field | Type | Default | Description |
|---|---|---|---|
importPaths | std::vector<std::string> | {} | Extra search directories for use module resolution. |
virtualFiles | std::unordered_map<std::string, std::string> | {} | In-memory virtual module buffers keyed by path (useful for IDEs and unsaved editor tabs). |
kitPath | std::string | "" | Optional filesystem override for kit.* modules. |
enableEmbeddedKit | bool | true | Resolve use kit.* from the embedded Standard Kit. |
maxErrors | size_t | 64 | Diagnostic 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
[[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
| Field | Type | Default | Description |
|---|---|---|---|
load | LoadOptions | default | Module loader options. |
runMemoryAnalysis | bool | true | Execute MemoryAnalyzer (SZSM escape/borrow proofs + auto-parallelizer). |
parMode | hir::ParMode | Off | Off, Auto, Force, or Autotune. |
runHintAnalysis | bool | true | Execute HintAnalyzer (auto hints + W6001..W6008 contradiction checks). |
warningsAsErrors | bool | false | Promote all warnings to hard errors. |
struct AnalysisOutput
| Member | Type | Description |
|---|---|---|
sources | SourceManager | All loaded module buffers. |
diagnostics | DiagnosticEngine | All diagnostics across load, sema, SZSM, and hints. |
graph | ModuleGraph | Parsed AST module graph. |
hir | hir::Program | Typed HIR program (types, symbols, functions, memory effects, parallelization certificates, hints). |
memoryAnalyzed | bool | true if MemoryAnalyzer completed. |
hintsAnalyzed | bool | true if HintAnalyzer completed. |
ok() | bool | !diagnostics.hasErrors(). |
dumpHir() | std::string | Textual HIR dump. |
dumpMemoryReport() | std::string | SZSM memory effect & loop proof certificates (empty if runMemoryAnalysis == false). |
dumpParallelReport() | std::string | Auto-parallelizer decisions & cost model report (empty if runMemoryAnalysis == false). |
dumpHintReport() | std::string | Manual and inferred optimization hint report (empty if runHintAnalysis == false). |
renderDiagnostics(useColor) | std::string | Formatted diagnostics. |
Functions
[[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:
func scale_add(dst: []mut i64, src: []i64, k: i64):
for i in 0..dst.len:
dst[i] = src[i] * k + 1Outputs:
out.dumpMemoryReport():
=== 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 != jout.dumpParallelReport():
=== 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():
=== 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
| Field | Type | Default | Description |
|---|---|---|---|
load | LoadOptions | default | Module loader options. |
optLevel | OptLevel | O0 | LLVM optimization level (O0, O1, O2, O3, Os, Oz). |
parMode | hir::ParMode | Off | Auto-parallelizer mode. |
parThreads | int32_t | 0 | Worker thread count (0 = hardware core count). |
targetTriple | std::string | "" | Target triple (empty = host target). |
targetCpu | std::string | "" | Target CPU ("", "native", or explicit LLVM CPU name). |
targetFeatures | std::string | "" | Extra LLVM CPU features (e.g. "+avx2,+fma"). |
debugInfo | bool | false | Emit DWARF/CodeView debug metadata. |
runtimeChecks | bool | true | Enable bounds, division-by-zero, and overflow checks. |
warningsAsErrors | bool | false | Promote warnings to errors. |
testMode | bool | false | Emit 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
[[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):
define dso_local noundef i32 @main() local_unnamed_addr #0 {
entry:
ret i32 42
}12. Embedded Standard Kit Inspection
| Function | Return Type | Description |
|---|---|---|
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:
ERROR E2015 (app.stag:4:12): undefined identifier 'unknown_var'
4 : return unknown_var
: ^^^^^^^^^^^
summary: 1 error, 0 warnings| Code Prefix | Origin |
|---|---|
E0000 | File I/O error in *File API helpers |
E0001..E0099 | Lexer errors |
E1000..E1101 | Parser and legacy syntax errors |
E1999 | Internal formatter safety re-parse check failure |
E2000..E2199 / W2001..W2099 | Semantic analyzer errors and warnings |
E4001..E4009 | SZSM memory safety and borrow errors |
E5000..E5012 | format.json configuration and style policy errors |
E6001..E6003 / W6001..W6008 | Optimization hint syntax errors and contradiction warnings |
E8001..E8009 | Backend, target lookup, and code emission errors |
14. End-to-End Tool Examples
Example 1: Public API Extractor / Documentation Generator
#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)
#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
#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;
}