#![forbid(unsafe_code)]
use clap::{Parser, Subcommand, ValueEnum};
use miette::{IntoDiagnostic, LabeledSpan, NamedSource, Report};
use relon::{Evaluator as EvaluatorTrait, ResolverChainLoader, Scope, Value};
use relon_analyzer::{
analyze_entry_with_options, analyze_with_options, AnalyzeOptions, AnalyzedTree, MainSignature,
WorkspaceDiagnostic, WorkspaceTree,
};
use relon_codegen_cranelift::AotEvaluator;
use relon_evaluator::module::FilesystemModuleResolver;
use relon_evaluator::{Capabilities, Context, ResourceBudget, TreeWalkEvaluator};
use relon_parser::{parse_document, ParseDocumentError};
use serde_json::{json, Value as JsonValue};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
#[derive(Debug, Clone, Copy, Default, ValueEnum, PartialEq, Eq)]
enum BackendArg {
#[default]
#[value(name = "auto")]
Auto,
#[value(name = "tree-walk")]
TreeWalk,
#[value(name = "cranelift-aot")]
CraneliftAot,
}
#[derive(Debug, Clone, Copy, Default, ValueEnum, PartialEq, Eq)]
enum BudgetArg {
#[default]
#[value(name = "off")]
Off,
#[value(name = "dev")]
Dev,
#[value(name = "untrusted")]
Untrusted,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
struct RunBudget {
max_source_bytes: Option<usize>,
max_steps: Option<u64>,
max_value_elements: Option<usize>,
max_output_bytes: Option<usize>,
}
struct RunCommand {
file: PathBuf,
pretty: bool,
lite: bool,
args: Option<String>,
trust: bool,
backend: BackendArg,
budget: BudgetArg,
max_source_bytes: Option<usize>,
max_steps: Option<u64>,
max_value_elements: Option<usize>,
max_output_bytes: Option<usize>,
require_hash: bool,
}
impl RunBudget {
const DEV_MAX_SOURCE_BYTES: usize = 1024 * 1024;
const DEV_MAX_STEPS: u64 = ResourceBudget::DEV_MAX_STEPS;
const DEV_MAX_VALUE_ELEMENTS: usize = ResourceBudget::DEV_MAX_VALUE_ELEMENTS;
const DEV_MAX_OUTPUT_BYTES: usize = 16 * 1024 * 1024;
const UNTRUSTED_MAX_SOURCE_BYTES: usize = 256 * 1024;
const UNTRUSTED_MAX_STEPS: u64 = ResourceBudget::UNTRUSTED_MAX_STEPS;
const UNTRUSTED_MAX_VALUE_ELEMENTS: usize = ResourceBudget::UNTRUSTED_MAX_VALUE_ELEMENTS;
const UNTRUSTED_MAX_OUTPUT_BYTES: usize = 8 * 1024 * 1024;
fn from_cli(
profile: BudgetArg,
max_source_bytes: Option<usize>,
max_steps: Option<u64>,
max_value_elements: Option<usize>,
max_output_bytes: Option<usize>,
) -> Self {
let mut budget = match profile {
BudgetArg::Off => Self::default(),
BudgetArg::Dev => Self {
max_source_bytes: Some(Self::DEV_MAX_SOURCE_BYTES),
max_steps: Some(Self::DEV_MAX_STEPS),
max_value_elements: Some(Self::DEV_MAX_VALUE_ELEMENTS),
max_output_bytes: Some(Self::DEV_MAX_OUTPUT_BYTES),
},
BudgetArg::Untrusted => Self {
max_source_bytes: Some(Self::UNTRUSTED_MAX_SOURCE_BYTES),
max_steps: Some(Self::UNTRUSTED_MAX_STEPS),
max_value_elements: Some(Self::UNTRUSTED_MAX_VALUE_ELEMENTS),
max_output_bytes: Some(Self::UNTRUSTED_MAX_OUTPUT_BYTES),
},
};
if let Some(max_source_bytes) = max_source_bytes {
budget.max_source_bytes = Some(max_source_bytes);
}
if let Some(max_steps) = max_steps {
budget.max_steps = Some(max_steps);
}
if let Some(max_value_elements) = max_value_elements {
budget.max_value_elements = Some(max_value_elements);
}
if let Some(max_output_bytes) = max_output_bytes {
budget.max_output_bytes = Some(max_output_bytes);
}
budget
}
fn has_evaluator_limits(self) -> bool {
self.max_steps.is_some() || self.max_value_elements.is_some()
}
fn apply_to_capabilities(self, caps: &mut Capabilities) {
if let Some(max_steps) = self.max_steps {
caps.max_steps = Some(max_steps);
}
if let Some(max_value_elements) = self.max_value_elements {
caps.max_value_elements = Some(max_value_elements);
}
}
}
#[derive(Debug, Clone, Copy, Default, ValueEnum, PartialEq, Eq)]
enum HostPolicyTargetArg {
#[default]
#[value(name = "wasmtime")]
Wasmtime,
}
#[derive(Debug, Clone, Copy, Default, ValueEnum, PartialEq, Eq)]
enum HostPolicyProfileArg {
#[value(name = "dev")]
Dev,
#[default]
#[value(name = "untrusted")]
Untrusted,
}
impl HostPolicyProfileArg {
fn as_str(self) -> &'static str {
match self {
Self::Dev => "dev",
Self::Untrusted => "untrusted",
}
}
}
#[derive(Debug, Clone, Copy, Default, ValueEnum, PartialEq, Eq)]
enum CheckFormatArg {
#[default]
#[value(name = "human")]
Human,
#[value(name = "json")]
Json,
}
#[derive(Debug, Clone, Copy, Default, ValueEnum, PartialEq, Eq)]
enum HostPolicyFormatArg {
#[default]
#[value(name = "json")]
Json,
#[value(name = "rust")]
Rust,
}
#[derive(Debug, Clone, Copy)]
struct WasmtimeHostPolicy {
profile: HostPolicyProfileArg,
fuel: u64,
epoch_deadline_ticks: u64,
wall_clock_timeout_ms: u64,
memory_size_bytes: usize,
table_elements: usize,
instances: usize,
tables: usize,
memories: usize,
output_bytes: usize,
}
impl WasmtimeHostPolicy {
fn from_profile(profile: HostPolicyProfileArg) -> Self {
match profile {
HostPolicyProfileArg::Dev => Self {
profile,
fuel: RunBudget::DEV_MAX_STEPS,
epoch_deadline_ticks: 1,
wall_clock_timeout_ms: 5_000,
memory_size_bytes: 64 * 1024 * 1024,
table_elements: 10_000,
instances: 1,
tables: 8,
memories: 1,
output_bytes: RunBudget::DEV_MAX_OUTPUT_BYTES,
},
HostPolicyProfileArg::Untrusted => Self {
profile,
fuel: RunBudget::UNTRUSTED_MAX_STEPS,
epoch_deadline_ticks: 1,
wall_clock_timeout_ms: 1_000,
memory_size_bytes: 16 * 1024 * 1024,
table_elements: 4_096,
instances: 1,
tables: 4,
memories: 1,
output_bytes: RunBudget::UNTRUSTED_MAX_OUTPUT_BYTES,
},
}
}
fn to_json_value(self) -> JsonValue {
json!({
"target": "wasmtime",
"profile": self.profile.as_str(),
"engine": {
"consume_fuel": true,
"epoch_interruption": true
},
"store": {
"fuel": self.fuel,
"epoch_deadline_ticks": self.epoch_deadline_ticks,
"limits": {
"memory_size_bytes": self.memory_size_bytes,
"table_elements": self.table_elements,
"instances": self.instances,
"tables": self.tables,
"memories": self.memories,
"trap_on_grow_failure": true
}
},
"host": {
"wall_clock_timeout_ms": self.wall_clock_timeout_ms,
"output_bytes": self.output_bytes,
"wasi": "deny-by-default",
"imports": "allowlist"
},
"notes": [
"Fuel is a Wasmtime instruction-cost budget, not a Relon evaluator step count.",
"Epoch interruption requires a host timer/task that calls Engine::increment_epoch().",
"Output bytes must be checked by the host after serializing the returned value."
]
})
}
fn to_rust_snippet(self) -> String {
format!(
r#"use wasmtime::{{Config, Engine, Store, StoreLimits, StoreLimitsBuilder}};
pub struct RelonVmState {{
limits: StoreLimits,
// Add host-owned state for Relon imports/functions here.
}}
pub fn build_relon_store() -> Result<(Engine, Store<RelonVmState>), wasmtime::Error> {{
let mut config = Config::new();
config.consume_fuel(true);
config.epoch_interruption(true);
let engine = Engine::new(&config)?;
let state = RelonVmState {{
limits: StoreLimitsBuilder::new()
.memory_size({memory_size_bytes})
.table_elements({table_elements})
.instances({instances})
.tables({tables})
.memories({memories})
.trap_on_grow_failure(true)
.build(),
}};
let mut store = Store::new(&engine, state);
store.limiter(|state| &mut state.limits);
store.set_fuel({fuel})?;
#[cfg(target_has_atomic = "64")]
store.set_epoch_deadline({epoch_deadline_ticks});
Ok((engine, store))
}}
// Profile: {profile}
// Host wall-clock timeout: {wall_clock_timeout_ms} ms.
// Host JSON/output byte limit: {output_bytes} bytes.
// Keep WASI denied by default and expose only audited Relon host imports.
// If epoch interruption is enabled, run a host timer/task that calls
// `engine.increment_epoch()` after the wall-clock deadline."#,
profile = self.profile.as_str(),
fuel = self.fuel,
epoch_deadline_ticks = self.epoch_deadline_ticks,
wall_clock_timeout_ms = self.wall_clock_timeout_ms,
memory_size_bytes = self.memory_size_bytes,
table_elements = self.table_elements,
instances = self.instances,
tables = self.tables,
memories = self.memories,
output_bytes = self.output_bytes,
)
}
}
#[derive(Parser)]
#[command(name = "relon")]
#[command(about = "Relon: A programmable configuration language", long_about = None)]
struct Cli {
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand)]
enum Commands {
Run {
file: PathBuf,
#[arg(
short,
long,
action = clap::ArgAction::Set,
num_args = 0..=1,
require_equals = true,
default_value_t = true,
default_missing_value = "true"
)]
pretty: bool,
#[arg(long, default_value_t = false)]
lite: bool,
#[arg(long)]
args: Option<String>,
#[arg(long)]
trust: bool,
#[arg(long, value_enum, default_value_t = BackendArg::Auto)]
backend: BackendArg,
#[arg(long, value_enum, default_value_t = BudgetArg::Off)]
budget: BudgetArg,
#[arg(long)]
max_source_bytes: Option<usize>,
#[arg(long)]
max_steps: Option<u64>,
#[arg(long)]
max_value_elements: Option<usize>,
#[arg(long)]
max_output_bytes: Option<usize>,
#[arg(long, default_value_t = false)]
require_hash: bool,
},
Check {
file: PathBuf,
#[arg(long, value_enum, default_value_t = BackendArg::Auto)]
backend: BackendArg,
#[arg(long)]
trust: bool,
#[arg(long)]
max_source_bytes: Option<usize>,
#[arg(long, default_value_t = false)]
require_hash: bool,
#[arg(long, value_enum, default_value_t = CheckFormatArg::Human)]
format: CheckFormatArg,
},
#[command(name = "host-policy")]
HostPolicy {
#[arg(long, value_enum, default_value_t = HostPolicyTargetArg::Wasmtime)]
target: HostPolicyTargetArg,
#[arg(long, value_enum, default_value_t = HostPolicyProfileArg::Untrusted)]
profile: HostPolicyProfileArg,
#[arg(long, value_enum, default_value_t = HostPolicyFormatArg::Json)]
format: HostPolicyFormatArg,
},
Fmt {
#[arg(long)]
check: bool,
#[arg(long)]
stdout: bool,
files: Vec<PathBuf>,
},
Cache {
#[command(subcommand)]
action: CacheAction,
},
#[cfg(feature = "cli-lsp")]
Lsp,
}
#[derive(Subcommand)]
enum CacheAction {
Stats,
Clean,
}
fn try_parse_run_fast(argv: &[std::ffi::OsString]) -> Option<Commands> {
let mut iter = argv.iter().skip(1);
let sub = iter.next()?;
if sub != "run" {
return None;
}
let mut file: Option<PathBuf> = None;
let mut lite = false;
let mut args: Option<String> = None;
while let Some(tok) = iter.next() {
let s = tok.to_str()?;
if s == "--lite" {
if lite {
return None;
}
lite = true;
} else if s == "--args" {
if args.is_some() {
return None;
}
let v = iter.next()?.to_str()?.to_string();
args = Some(v);
} else if s.starts_with("--") || s.starts_with('-') {
return None;
} else {
if file.is_some() {
return None;
}
file = Some(PathBuf::from(tok));
}
}
let file = file?;
Some(Commands::Run {
file,
pretty: true,
lite,
args,
trust: false,
backend: BackendArg::Auto,
budget: BudgetArg::Off,
max_steps: None,
max_value_elements: None,
max_output_bytes: None,
max_source_bytes: None,
require_hash: false,
})
}
fn main() -> miette::Result<()> {
let profile_main_entry = std::time::Instant::now();
let profile_enabled = std::env::var_os("RELON_CLI_PROFILE").is_some();
if profile_enabled {
let entry_us = profile_main_entry.elapsed().as_micros();
eprintln!(
"[relon-cli profile] main_entry +{entry_us:>6}us (total {entry_us}us)"
);
}
let argv: Vec<std::ffi::OsString> = std::env::args_os().collect();
let command = match try_parse_run_fast(&argv) {
Some(cmd) => {
if profile_enabled {
let total_us = profile_main_entry.elapsed().as_micros();
eprintln!(
"[relon-cli profile] argv_fast_run +{total_us:>6}us (total {total_us}us)"
);
}
cmd
}
None => {
let cli = Cli::parse();
if profile_enabled {
let total_us = profile_main_entry.elapsed().as_micros();
eprintln!(
"[relon-cli profile] clap::parse +{total_us:>6}us (total {total_us}us)"
);
}
cli.command
}
};
match command {
Commands::Run {
file,
pretty,
lite,
args,
trust,
backend,
budget,
max_steps,
max_value_elements,
max_output_bytes,
max_source_bytes,
require_hash,
} => cmd_run(RunCommand {
file,
pretty,
lite,
args,
trust,
backend,
budget,
max_source_bytes,
max_steps,
max_value_elements,
max_output_bytes,
require_hash,
})?,
Commands::Check {
file,
backend,
trust,
max_source_bytes,
require_hash,
format,
} => cmd_check(file, backend, trust, max_source_bytes, require_hash, format)?,
Commands::HostPolicy {
target,
profile,
format,
} => cmd_host_policy(target, profile, format)?,
Commands::Fmt {
check,
stdout,
files,
} => {
run_fmt(check, stdout, files)?;
}
Commands::Cache { action } => cmd_cache(action)?,
#[cfg(feature = "cli-lsp")]
Commands::Lsp => {
relon_lsp::server::run_stdio()
.map_err(|e| miette::miette!("language server exited with error: {e}"))?;
}
}
Ok(())
}
const TRUST_UNSUPPORTED_ON_AOT: &str =
"[relon-cli] warning: --trust has no effect on the cranelift-AOT backend \
(single file, no host-fn registry): it grants no runtime native-fn \
capability, and the `#import` paths --trust would open are not stitched \
by this backend. Use --backend tree-walk if your \
program relies on --trust.";
fn warn_trust_unsupported_on_aot() {
eprintln!("{TRUST_UNSUPPORTED_ON_AOT}");
}
fn cmd_host_policy(
target: HostPolicyTargetArg,
profile: HostPolicyProfileArg,
format: HostPolicyFormatArg,
) -> miette::Result<()> {
match target {
HostPolicyTargetArg::Wasmtime => {
let policy = WasmtimeHostPolicy::from_profile(profile);
match format {
HostPolicyFormatArg::Json => {
let output =
serde_json::to_string_pretty(&policy.to_json_value()).into_diagnostic()?;
println!("{output}");
}
HostPolicyFormatArg::Rust => {
println!("{}", policy.to_rust_snippet());
}
}
}
}
Ok(())
}
fn parse_main_args_json(
args_json: &str,
signature: &MainSignature,
tree: &AnalyzedTree,
) -> Result<HashMap<String, Value>, String> {
let json: JsonValue = serde_json::from_str(args_json).map_err(|error| {
format!("--args must be a JSON object keyed by `#main(...)` parameter names: {error}")
})?;
relon::decode_main_args(json, signature, tree).map_err(|error| format!("--{error}"))
}
#[allow(clippy::too_many_arguments)]
fn enforce_source_size(path: &Path, limit: Option<usize>) -> miette::Result<()> {
let Some(limit) = limit else {
return Ok(());
};
let actual = std::fs::metadata(path)
.into_diagnostic()
.map_err(|e| e.wrap_err(format!("Failed to stat file {:?}", path)))?
.len() as usize;
if actual > limit {
return Err(miette::miette!(
"Relon source exceeded --max-source-bytes: actual {actual} bytes, limit {limit} bytes"
));
}
Ok(())
}
fn cmd_check(
file: PathBuf,
backend: BackendArg,
trust: bool,
max_source_bytes: Option<usize>,
require_hash: bool,
format: CheckFormatArg,
) -> miette::Result<()> {
let canonical_file = std::fs::canonicalize(&file)
.into_diagnostic()
.map_err(|e| e.wrap_err(format!("Failed to resolve file {:?}", file)))?;
enforce_source_size(&canonical_file, max_source_bytes)?;
let content = std::fs::read_to_string(&canonical_file)
.into_diagnostic()
.map_err(|e| e.wrap_err(format!("Failed to read file {:?}", canonical_file)))?;
let cache_namespace = canonical_file.to_string_lossy().to_string();
let entry_dir = canonical_file
.parent()
.unwrap_or(Path::new("."))
.to_path_buf();
let mut loader = if trust {
ResolverChainLoader::trusted()
} else {
ResolverChainLoader::sandboxed()
};
let analyze_options = AnalyzeOptions {
require_hash,
..AnalyzeOptions::default()
};
let workspace = analyze_entry_with_options(
cache_namespace.clone(),
&content,
entry_dir,
&mut loader,
&analyze_options,
);
match format {
CheckFormatArg::Human => render_check_human(
&workspace,
&cache_namespace,
&content,
&file,
backend,
trust,
),
CheckFormatArg::Json => {
render_check_json(&workspace, &cache_namespace, &content, backend, trust)
}
}
}
fn render_check_human(
workspace: &WorkspaceTree,
cache_namespace: &str,
content: &str,
file: &Path,
backend: BackendArg,
trust: bool,
) -> miette::Result<()> {
if workspace.has_errors() {
let mut messages: Vec<String> = workspace
.workspace_diagnostics
.iter()
.filter(|d| d.severity() == relon_analyzer::Severity::Error)
.map(|d| d.to_string())
.collect();
for (id, tree) in &workspace.modules {
for d in &tree.diagnostics {
if d.severity() == relon_analyzer::Severity::Error {
messages.push(format!("[{id}] {d}"));
}
}
}
let joined = messages.join("\n - ");
return Err(
miette::miette!("Analyzer reported errors:\n - {joined}").with_source_code(
NamedSource::new(file.to_string_lossy(), content.to_string()),
),
);
}
println!("ok: analyzer");
if trust && backend == BackendArg::CraneliftAot {
warn_trust_unsupported_on_aot();
}
match backend_compat_verdict(workspace, cache_namespace, content, backend) {
BackendCompatVerdict::Compatible(line) => {
println!("backend {line}");
Ok(())
}
BackendCompatVerdict::Incompatible(message) => Err(miette::miette!("{message}")),
}
}
fn render_check_json(
workspace: &WorkspaceTree,
cache_namespace: &str,
content: &str,
backend: BackendArg,
trust: bool,
) -> miette::Result<()> {
let mut entries: Vec<JsonValue> = Vec::new();
for d in &workspace.workspace_diagnostics {
let mut entry = check_diagnostic_json(
d,
d.severity(),
d.to_string(),
cache_namespace,
Some(content),
);
if let WorkspaceDiagnostic::ModuleParseError { path, .. } = d {
if path == cache_namespace {
if let Err(parse_err) = parse_document(content) {
if let Some(span) = parse_err.source_span() {
entry["start"] = json_position(content, span.offset());
entry["end"] = json_position(content, span.offset() + span.len());
}
}
}
}
entries.push(entry);
}
let mut module_ids: Vec<&String> = workspace.modules.keys().collect();
module_ids.sort();
for id in module_ids {
let tree = &workspace.modules[id];
let module_source = if id == cache_namespace {
Some(content.to_string())
} else {
std::fs::read_to_string(id).ok()
};
for d in &tree.diagnostics {
entries.push(check_diagnostic_json(
d,
d.severity(),
d.to_string(),
id,
module_source.as_deref(),
));
}
}
if workspace.has_errors() {
print_check_json(&entries)?;
let error_count = workspace.all_error_diagnostics().len();
return Err(miette::miette!(
"relon check found {error_count} error diagnostic(s); see the JSON output on stdout"
));
}
if trust && backend == BackendArg::CraneliftAot {
warn_trust_unsupported_on_aot();
}
match backend_compat_verdict(workspace, cache_namespace, content, backend) {
BackendCompatVerdict::Compatible(_) => {
print_check_json(&entries)?;
Ok(())
}
BackendCompatVerdict::Incompatible(message) => {
entries.push(json!({
"code": "relon::check::backend_incompatible",
"severity": "error",
"message": message,
"file": cache_namespace,
"start": JsonValue::Null,
"end": JsonValue::Null,
"help": JsonValue::Null,
}));
print_check_json(&entries)?;
Err(miette::miette!("{message}"))
}
}
}
fn print_check_json(entries: &[JsonValue]) -> miette::Result<()> {
let rendered = serde_json::to_string_pretty(&entries).into_diagnostic()?;
println!("{rendered}");
Ok(())
}
fn check_diagnostic_json(
diag: &dyn miette::Diagnostic,
severity: relon_analyzer::Severity,
message: String,
file: &str,
source: Option<&str>,
) -> JsonValue {
let code = diag.code().map(|c| c.to_string());
let help = diag.help().map(|h| h.to_string());
let span = diag
.labels()
.and_then(|mut labels| labels.next())
.map(|label| *label.inner());
let (start, end) = match (span, source) {
(Some(span), Some(src)) => (
json_position(src, span.offset()),
json_position(src, span.offset() + span.len()),
),
_ => (JsonValue::Null, JsonValue::Null),
};
json!({
"code": code,
"severity": match severity {
relon_analyzer::Severity::Error => "error",
relon_analyzer::Severity::Warning => "warning",
},
"message": message,
"file": file,
"start": start,
"end": end,
"help": help,
})
}
fn json_position(source: &str, byte_offset: usize) -> JsonValue {
let mut offset = byte_offset.min(source.len());
while offset > 0 && !source.is_char_boundary(offset) {
offset -= 1;
}
let before = &source[..offset];
let line = before.bytes().filter(|b| *b == b'\n').count() + 1;
let line_start = before.rfind('\n').map(|i| i + 1).unwrap_or(0);
let column = before[line_start..].chars().count() + 1;
json!({ "line": line, "column": column })
}
enum BackendCompatVerdict {
Compatible(String),
Incompatible(String),
}
fn backend_compat_verdict(
workspace: &WorkspaceTree,
cache_namespace: &str,
content: &str,
backend: BackendArg,
) -> BackendCompatVerdict {
let has_main = workspace
.modules
.get(cache_namespace)
.and_then(|tree| tree.main_signature.as_ref())
.is_some();
match backend {
BackendArg::TreeWalk => BackendCompatVerdict::Compatible(
"tree-walk: compatible (reference evaluator)".to_string(),
),
BackendArg::CraneliftAot => {
cranelift_compat_verdict(content, has_main, "cranelift-aot", true)
}
BackendArg::Auto => {
if !has_main {
return BackendCompatVerdict::Compatible(
"auto: compatible (library-mode routes to tree-walk)".to_string(),
);
}
if relon::is_trivial_scalar_main(content) {
return BackendCompatVerdict::Compatible(
"auto: compatible (trivial #main routes to tree-walk)".to_string(),
);
}
cranelift_compat_verdict(content, has_main, "auto/cranelift-aot", false)
}
}
}
fn cranelift_compat_verdict(
content: &str,
has_main: bool,
label: &str,
strict: bool,
) -> BackendCompatVerdict {
if !has_main {
let message = format!("{label}: incompatible (cranelift-aot requires `#main(...)`)");
return if strict {
BackendCompatVerdict::Incompatible(message)
} else {
BackendCompatVerdict::Compatible(format!("{message}; auto will route to tree-walk"))
};
}
match AotEvaluator::from_source(content) {
Ok(_) => BackendCompatVerdict::Compatible(format!("{label}: compatible")),
Err(e) if e.is_unsupported_shape() && !strict => BackendCompatVerdict::Compatible(format!(
"{label}: not compiled ({e}); auto will fall back to tree-walk"
)),
Err(e) => BackendCompatVerdict::Incompatible(format!("{label}: incompatible: {e}")),
}
}
fn cmd_run(command: RunCommand) -> miette::Result<()> {
let RunCommand {
file,
pretty,
lite,
args,
trust,
backend,
budget,
max_source_bytes,
max_steps,
max_value_elements,
max_output_bytes,
require_hash,
} = command;
let profile_phases = std::env::var_os("RELON_CLI_PROFILE").is_some();
let phase_start = std::time::Instant::now();
let mut last_phase_at = phase_start;
let mut phase = |label: &str| {
if !profile_phases {
return;
}
let now = std::time::Instant::now();
let total_us = now.duration_since(phase_start).as_micros();
let delta_us = now.duration_since(last_phase_at).as_micros();
eprintln!("[relon-cli profile] {label:<24} +{delta_us:>6}us (total {total_us}us)");
last_phase_at = now;
};
let run_budget = RunBudget::from_cli(
budget,
max_source_bytes,
max_steps,
max_value_elements,
max_output_bytes,
);
let effective_backend = match (lite, run_budget.has_evaluator_limits(), backend) {
(true, _, BackendArg::Auto | BackendArg::TreeWalk)
| (false, true, BackendArg::Auto)
| (false, _, BackendArg::TreeWalk) => BackendArg::TreeWalk,
(true, _, other) => {
return Err(miette::miette!(
"--lite forces `--backend tree-walk`; remove the explicit `--backend {:?}` or drop `--lite`",
other
));
}
(false, true, BackendArg::CraneliftAot) => {
return Err(miette::miette!(
"evaluator resource budgets (--budget dev|untrusted, --max-steps, --max-value-elements) \
currently require `--backend tree-walk`; cranelift-aot does not honor these CLI limits"
));
}
(false, false, other) => other,
};
let canonical_file = std::fs::canonicalize(&file)
.into_diagnostic()
.map_err(|e| e.wrap_err(format!("Failed to resolve file {:?}", file)))?;
phase("canonicalize");
enforce_source_size(&canonical_file, run_budget.max_source_bytes)?;
let content = std::fs::read_to_string(&canonical_file)
.into_diagnostic()
.map_err(|e| e.wrap_err(format!("Failed to read file {:?}", canonical_file)))?;
phase("read_to_string");
let cache_namespace = canonical_file.to_string_lossy().to_string();
let entry_dir = canonical_file
.parent()
.unwrap_or(Path::new("."))
.to_path_buf();
let mut loader = if trust {
ResolverChainLoader::trusted()
} else {
ResolverChainLoader::sandboxed()
};
let prelite_node = if !lite {
relon_parser::parse_document_fast(&content)
} else {
relon_parser::parse_document_fast(&content)
};
let trivial_default = !lite
&& match &prelite_node {
Some(node) => relon::is_trivial_scalar_main_node(node),
None => relon::is_trivial_scalar_main(&content),
};
phase("trivial_classify");
let lite_analyze = lite || trivial_default;
let analyze_options = AnalyzeOptions {
require_hash,
skip_core_schemas: lite_analyze,
trivial_main_fast_path: lite_analyze,
..AnalyzeOptions::default()
};
let workspace = if lite_analyze {
let parsed = match prelite_node {
Some(node) => Ok(node),
None => relon_parser::parse_document(&content),
};
match parsed {
Ok(node) => {
phase("[lite] parse_only");
let arc_node = Arc::new(node);
let entry_relaxed = arc_node.directives.iter().any(|d| {
d.name == relon_parser::directive::RELAXED
|| d.name == relon_parser::directive::UNSTRICT
});
let entry_strict = analyze_options.strict_mode && !entry_relaxed;
let mut eff = analyze_options.clone();
eff.strict_mode = entry_strict;
let tree = analyze_with_options(&arc_node, &eff);
phase("[lite] analyze");
if tree.imports.is_empty() {
let mut ws = WorkspaceTree::new();
ws.entry_id = cache_namespace.clone();
ws.strict_mode = entry_strict;
ws.import_graph.insert(cache_namespace.clone(), Vec::new());
ws.modules.insert(cache_namespace.clone(), Arc::new(tree));
ws.nodes.insert(cache_namespace.clone(), arc_node);
phase("[lite] synth_ws");
ws
} else {
phase("[lite] has_imports_fallback");
analyze_entry_with_options(
cache_namespace.clone(),
&content,
entry_dir,
&mut loader,
&analyze_options,
)
}
}
Err(parse_err) => {
phase("[lite] parse_failed");
let mut ws = WorkspaceTree::new();
ws.entry_id = cache_namespace.clone();
ws.workspace_diagnostics
.push(WorkspaceDiagnostic::ModuleParseError {
path: cache_namespace.clone(),
message: parse_err.to_string(),
range: miette::SourceSpan::from((0usize, 0usize)),
});
ws
}
}
} else {
if profile_phases {
let _ = relon_parser::parse_document(&content);
phase("[probe] parse_only");
}
let ws = analyze_entry_with_options(
cache_namespace.clone(),
&content,
entry_dir,
&mut loader,
&analyze_options,
);
phase("analyze_entry");
ws
};
if workspace.has_errors() {
if let Some(parse_msg) =
workspace
.workspace_diagnostics
.iter()
.find_map(|d| match d {
relon_analyzer::WorkspaceDiagnostic::ModuleParseError {
path, message, ..
} if path == &cache_namespace => Some(message.clone()),
_ => None,
})
{
if let Err(e) = parse_document(&content) {
let report = if let Some(span) = e.source_span() {
let label = match &e {
ParseDocumentError::Parse { .. } => "parse error",
ParseDocumentError::TrailingInput { .. } => "invalid trailing input",
};
miette::miette!(
labels = vec![LabeledSpan::new_with_span(Some(label.to_string()), span)],
"Parse error: {}",
e
)
} else {
miette::miette!("Parse error: {}", e)
};
return Err(
report.with_source_code(NamedSource::new(file.to_string_lossy(), content))
);
}
return Err(miette::miette!("Parse error in entry module: {parse_msg}")
.with_source_code(NamedSource::new(file.to_string_lossy(), content)));
}
let mut messages: Vec<String> = workspace
.workspace_diagnostics
.iter()
.filter(|d| d.severity() == relon_analyzer::Severity::Error)
.map(|d| d.to_string())
.collect();
for (id, tree) in &workspace.modules {
for d in &tree.diagnostics {
if d.severity() == relon_analyzer::Severity::Error {
messages.push(format!("[{id}] {d}"));
}
}
}
let joined = messages.join("\n - ");
return Err(miette::miette!("Analyzer reported errors:\n - {joined}")
.with_source_code(NamedSource::new(file.to_string_lossy(), content)));
}
let entry_node = workspace
.nodes
.get(&cache_namespace)
.map(|arc| (**arc).clone())
.expect("workspace passed has_errors check but entry node missing");
let workspace = Arc::new(workspace);
let ctx = {
let mut ctx = Context::sandboxed()
.with_root(entry_node)
.with_workspace(Arc::clone(&workspace));
let mut caps = if trust {
Capabilities::all_granted()
} else {
Capabilities::default()
};
run_budget.apply_to_capabilities(&mut caps);
if trust || run_budget.has_evaluator_limits() {
ctx = ctx.with_capabilities(caps);
}
if trust {
ctx.prepend_module_resolver(Arc::new(FilesystemModuleResolver::trusted()));
#[cfg(feature = "cli-remote-http")]
ctx.prepend_module_resolver(Arc::new(
relon_evaluator::module::RemoteHttpResolver::new(),
));
}
Arc::new({
let mut ctx = ctx;
if lite_analyze {
relon_evaluator::TreeWalkEvaluator::prepare_in_place_lite(&mut ctx);
} else {
relon_evaluator::TreeWalkEvaluator::prepare_in_place(&mut ctx);
}
ctx
})
};
let _root_loading_guard = ctx.enter_loading_module(cache_namespace.clone());
let evaluator = TreeWalkEvaluator::new(Arc::clone(&ctx));
phase("context+tw_evaluator");
let scope = std::sync::Arc::new(Scope {
current_dir: canonical_file
.parent()
.unwrap_or(std::path::Path::new("."))
.to_string_lossy()
.into_owned()
.into(),
cache_namespace: cache_namespace.clone().into(),
..Scope::default()
});
let has_main = workspace
.modules
.get(&cache_namespace)
.and_then(|tree| tree.main_signature.as_ref())
.is_some();
let result = if has_main {
let args_json = match args.as_deref() {
Some("-") => {
use std::io::Read;
let mut buf = String::new();
std::io::stdin()
.read_to_string(&mut buf)
.into_diagnostic()
.map_err(|e| e.wrap_err("Failed to read --args from stdin"))?;
buf
}
Some(other) => other.to_string(),
None => {
return Err(miette::miette!(
"File declares `#main(...)`; pass --args '<json>' (or --args -) to provide host arguments"
)
.with_source_code(NamedSource::new(file.to_string_lossy(), content)));
}
};
let entry_tree = workspace
.modules
.get(&cache_namespace)
.expect("workspace passed has_main check but entry tree missing");
let signature = entry_tree
.main_signature
.as_ref()
.expect("workspace passed has_main check but entry signature missing");
let args_map = parse_main_args_json(&args_json, signature, entry_tree).map_err(|e| {
miette::miette!("{e}")
.with_source_code(NamedSource::new(file.to_string_lossy(), content.clone()))
})?;
phase("backend_select");
match effective_backend {
BackendArg::Auto => {
if trivial_default {
phase("default_trivial_tree_walk");
evaluator.run_main(&scope, args_map).map_err(|e| {
Report::new(e).with_source_code(NamedSource::new(
file.to_string_lossy(),
content.clone(),
))
})?
} else {
if trust {
warn_trust_unsupported_on_aot();
}
let cache_dir = relon_codegen_cranelift::default_cache_dir();
let aot_opt = match AotEvaluator::from_cache_dir(&content, &cache_dir) {
Ok(opt) => opt,
Err(e) => {
eprintln!(
"[relon-cli] AOT cache load failed: {e}; falling back to from_source"
);
None
}
};
phase("default_cache_probe");
let aot = match aot_opt {
Some(a) => Some(a),
None => match AotEvaluator::from_source_with_cache(&content, &cache_dir) {
Ok(a) => Some(a),
Err(e) if e.is_unsupported_shape() => {
eprintln!(
"[relon-cli] auto backend: compiled (cranelift-AOT) path can't \
express this #main shape ({e}); falling back to the tree-walk \
interpreter — this run forgoes AOT acceleration"
);
phase("default_unsupported_tree_walk");
None
}
Err(e) => {
return Err(miette::miette!("auto backend setup: {e}")
.with_source_code(NamedSource::new(
file.to_string_lossy(),
content.clone(),
)));
}
},
};
match aot {
Some(aot) => EvaluatorTrait::run_main(&aot, args_map).map_err(|e| {
Report::new(e).with_source_code(NamedSource::new(
file.to_string_lossy(),
content.clone(),
))
})?,
None => evaluator.run_main(&scope, args_map).map_err(|e| {
Report::new(e).with_source_code(NamedSource::new(
file.to_string_lossy(),
content.clone(),
))
})?,
}
}
}
BackendArg::TreeWalk => evaluator.run_main(&scope, args_map).map_err(|e| {
Report::new(e)
.with_source_code(NamedSource::new(file.to_string_lossy(), content.clone()))
})?,
BackendArg::CraneliftAot => {
if trust {
warn_trust_unsupported_on_aot();
}
let aot = AotEvaluator::from_source(&content).map_err(|e| {
miette::miette!("cranelift-aot backend setup: {e}")
.with_source_code(NamedSource::new(file.to_string_lossy(), content.clone()))
})?;
EvaluatorTrait::run_main(&aot, args_map).map_err(|e| {
Report::new(e)
.with_source_code(NamedSource::new(file.to_string_lossy(), content.clone()))
})?
}
}
} else {
if args.is_some() {
return Err(miette::miette!(
"--args was provided but the file has no `#main(...)` signature"
)
.with_source_code(NamedSource::new(file.to_string_lossy(), content)));
}
if matches!(backend, BackendArg::CraneliftAot) {
return Err(miette::miette!(
"cranelift-aot backend only supports `#main(...)` entries; the file declares no signature"
)
.with_source_code(NamedSource::new(file.to_string_lossy(), content)));
}
evaluator.eval_root(&scope).map_err(|e| {
Report::new(e)
.with_source_code(NamedSource::new(file.to_string_lossy(), content.clone()))
})?
};
phase("evaluate");
let final_val = relon::to_json_value(result).map_err(|e| {
miette::miette!("{}", e)
.with_source_code(NamedSource::new(file.to_string_lossy(), content.clone()))
})?;
phase("to_json_value");
let output = if pretty {
serde_json::to_string_pretty(&final_val).into_diagnostic()?
} else {
serde_json::to_string(&final_val).into_diagnostic()?
};
phase("serialise_json");
if let Some(limit) = run_budget.max_output_bytes {
let actual = output.len();
if actual > limit {
return Err(miette::miette!(
"JSON output exceeded --max-output-bytes: actual {actual} bytes, limit {limit} bytes"
)
.with_source_code(NamedSource::new(file.to_string_lossy(), content)));
}
}
println!("{}", output);
phase("println");
Ok(())
}
const CACHE_ARTIFACT_KINDS: &[(&str, &str)] = &[
(relon_object_cache::CACHE_FILE_SUFFIX, "native objects"),
(
relon_codegen_cranelift::object_cache_integration::IR_CACHE_FILE_SUFFIX,
"IR blobs",
),
(
relon_codegen_cranelift::schema_cache::SCHEMA_CACHE_FILE_SUFFIX,
"schema blobs",
),
];
#[derive(Default)]
struct CacheScan {
artifacts: Vec<(PathBuf, u64, usize)>,
unrelated: usize,
}
fn scan_cache_dir(cache_dir: &Path) -> miette::Result<CacheScan> {
let mut scan = CacheScan::default();
let entries = match std::fs::read_dir(cache_dir) {
Ok(entries) => entries,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(scan),
Err(e) => {
return Err(miette::miette!(
"failed to read cache directory {}: {e}",
cache_dir.display()
));
}
};
for entry in entries {
let entry =
entry.map_err(|e| miette::miette!("failed to list {}: {e}", cache_dir.display()))?;
let path = entry.path();
let name = entry.file_name();
let name = name.to_string_lossy();
let kind = CACHE_ARTIFACT_KINDS
.iter()
.position(|(suffix, _)| name.ends_with(suffix));
match kind {
Some(kind) if path.is_file() => {
let size = entry
.metadata()
.map_err(|e| miette::miette!("failed to stat {}: {e}", path.display()))?
.len();
scan.artifacts.push((path, size, kind));
}
_ => scan.unrelated += 1,
}
}
Ok(scan)
}
fn cmd_cache(action: CacheAction) -> miette::Result<()> {
let cache_dir = relon_codegen_cranelift::default_cache_dir();
let scan = scan_cache_dir(&cache_dir)?;
println!("cache dir: {}", cache_dir.display());
match action {
CacheAction::Stats => {
let mut per_kind = [0usize; CACHE_ARTIFACT_KINDS.len()];
let mut total_bytes = 0u64;
for (_, size, kind) in &scan.artifacts {
per_kind[*kind] += 1;
total_bytes += size;
}
let breakdown: Vec<String> = CACHE_ARTIFACT_KINDS
.iter()
.zip(per_kind)
.map(|((_, label), count)| format!("{count} {label}"))
.collect();
println!(
"entries: {} ({})",
scan.artifacts.len(),
breakdown.join(", ")
);
println!("total bytes: {total_bytes}");
if scan.unrelated > 0 {
println!("unrelated entries (not counted): {}", scan.unrelated);
}
}
CacheAction::Clean => {
let mut removed = 0usize;
let mut freed = 0u64;
for (path, size, _) in &scan.artifacts {
std::fs::remove_file(path)
.map_err(|e| miette::miette!("failed to remove {}: {e}", path.display()))?;
removed += 1;
freed += size;
}
println!("removed {removed} cache artifact(s), freed {freed} bytes");
if scan.unrelated > 0 {
println!("unrelated entries left untouched: {}", scan.unrelated);
}
}
}
Ok(())
}
fn run_fmt(check: bool, stdout: bool, files: Vec<PathBuf>) -> miette::Result<()> {
if files.is_empty() {
return Err(miette::miette!("expected at least one file"));
}
let mut failed_check = false;
for file in &files {
let source = std::fs::read_to_string(file)
.into_diagnostic()
.map_err(|e| e.wrap_err(format!("failed to read {}", file.display())))?;
let formatted = relon_fmt::format_source(&source)
.map_err(|e| miette::miette!("{}: {e}", file.display()))?;
if check {
if formatted != source {
eprintln!("{} is not formatted", file.display());
failed_check = true;
}
continue;
}
if stdout {
print!("{formatted}");
} else if formatted != source {
std::fs::write(file, formatted)
.into_diagnostic()
.map_err(|e| e.wrap_err(format!("failed to write {}", file.display())))?;
}
}
if failed_check {
Err(miette::miette!("one or more files were not formatted"))
} else {
Ok(())
}
}