#![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, format_type, substitute_generics_in_typenode,
AnalyzeOptions, AnalyzedTree, MainSignature, SchemaDef, 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, TypeNode};
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 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, default_value_t = 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,
},
#[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>,
},
#[cfg(feature = "cli-lsp")]
Lsp,
}
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,
} => cmd_check(file, backend, trust, max_source_bytes, require_hash)?,
Commands::HostPolicy {
target,
profile,
format,
} => cmd_host_policy(target, profile, format)?,
Commands::Fmt {
check,
stdout,
files,
} => {
run_fmt(check, stdout, files)?;
}
#[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 raw_args: serde_json::Map<String, JsonValue> =
serde_json::from_str(args_json).map_err(|e| {
format!("--args must be a JSON object keyed by `#main(...)` parameter names: {e}")
})?;
let param_types: HashMap<&str, &TypeNode> = signature
.params
.iter()
.map(|param| (param.name.as_str(), ¶m.type_node))
.collect();
let mut args = HashMap::with_capacity(raw_args.len());
for (name, json) in raw_args {
let value = if let Some(type_hint) = param_types.get(name.as_str()) {
let type_hint = *type_hint;
decode_json_for_type(json, type_hint, tree).map_err(|e| {
format!(
"--args value for `{name}` cannot be decoded as {}: {e}",
format_type(type_hint)
)
})?
} else {
targetless_json_to_value(json)?
};
args.insert(name, value);
}
Ok(args)
}
fn decode_json_for_type(
json: JsonValue,
type_hint: &TypeNode,
tree: &AnalyzedTree,
) -> Result<Value, String> {
if type_hint.is_optional {
let mut inner_type = type_hint.clone();
inner_type.is_optional = false;
return decode_json_for_option(json, Some(&inner_type), tree);
}
if type_key(type_hint) == "Option" {
return decode_json_for_option(json, type_hint.generics.first(), tree);
}
if type_key(type_hint) == "Result" {
return decode_json_for_result(
json,
type_hint.generics.first(),
type_hint.generics.get(1),
tree,
);
}
if let Some(value) = decode_json_for_builtin_scalar(json.clone(), type_hint) {
return value;
}
match type_key(type_hint).as_str() {
"Tuple" => decode_json_array_as_tuple_or_targetless(json, &type_hint.generics, tree),
"List" => decode_json_array_as_list_or_targetless(json, type_hint.generics.first(), tree),
"Dict" => decode_json_object_as_dict_or_targetless(json, type_hint.generics.get(1), tree),
"Enum" => decode_json_for_enum(json, type_hint, tree),
_ => {
if let Some(def) = schema_def_for_type(type_hint, tree) {
if !def.variants.is_empty() {
return decode_json_for_tagged_enum_schema(json, type_hint, def, tree);
}
}
if let Some(elements) = schema_tuple_elements_for_type(type_hint, tree) {
decode_json_array_as_tuple_or_targetless(json, &elements, tree)
} else if let Some(fields) = schema_fields_for_type(type_hint, tree) {
decode_json_object_as_schema_or_targetless(json, &fields, tree)
} else {
targetless_json_to_value(json)
}
}
}
}
fn decode_json_for_builtin_scalar(
json: JsonValue,
type_hint: &TypeNode,
) -> Option<Result<Value, String>> {
match type_key(type_hint).as_str() {
"Any" => Some(targetless_json_to_value(json)),
"Bool" => Some(match json {
JsonValue::Bool(value) => Ok(Value::Bool(value)),
other => Err(format!("expected JSON bool, got {}", json_kind(&other))),
}),
"Int" => Some(match json {
JsonValue::Number(value) => value
.as_i64()
.map(Value::Int)
.ok_or_else(|| "expected JSON integer in i64 range".to_string()),
other => Err(format!("expected JSON integer, got {}", json_kind(&other))),
}),
"Float" => Some(match json {
JsonValue::Number(value) => value
.as_f64()
.map(|value| Value::Float(value.into()))
.ok_or_else(|| "expected finite JSON number".to_string()),
other => Err(format!("expected JSON number, got {}", json_kind(&other))),
}),
"Number" => Some(match json {
JsonValue::Number(value) => {
if let Some(int) = value.as_i64() {
Ok(Value::Int(int))
} else {
value
.as_f64()
.map(|value| Value::Float(value.into()))
.ok_or_else(|| "expected finite JSON number".to_string())
}
}
other => Err(format!("expected JSON number, got {}", json_kind(&other))),
}),
"String" => Some(match json {
JsonValue::String(value) => Ok(Value::String(value.into())),
other => Err(format!("expected JSON string, got {}", json_kind(&other))),
}),
_ => None,
}
}
fn json_kind(value: &JsonValue) -> &'static str {
match value {
JsonValue::Null => "null",
JsonValue::Bool(_) => "bool",
JsonValue::Number(_) => "number",
JsonValue::String(_) => "string",
JsonValue::Array(_) => "array",
JsonValue::Object(_) => "object",
}
}
fn decode_json_for_option(
json: JsonValue,
inner_type: Option<&TypeNode>,
tree: &AnalyzedTree,
) -> Result<Value, String> {
match json {
JsonValue::Null => Ok(Value::option_none()),
JsonValue::String(name) if name == "None" => Ok(Value::option_none()),
JsonValue::Object(mut map) if map.len() == 1 && map.contains_key("None") => {
let payload = map.remove("None").expect("checked None payload");
match payload {
JsonValue::Null => Ok(Value::option_none()),
JsonValue::Object(obj) if obj.is_empty() => Ok(Value::option_none()),
_ => Err("Option.None expects null or an empty object payload".to_string()),
}
}
JsonValue::Object(mut map) if map.len() == 1 && map.contains_key("Some") => {
let payload = map.remove("Some").expect("checked Some payload");
decode_json_single_payload(payload, "value", inner_type, tree).map(Value::option_some)
}
other => {
decode_json_single_payload(other, "value", inner_type, tree).map(Value::option_some)
}
}
}
fn decode_json_for_result(
json: JsonValue,
ok_type: Option<&TypeNode>,
err_type: Option<&TypeNode>,
tree: &AnalyzedTree,
) -> Result<Value, String> {
let JsonValue::Object(mut map) = json else {
return Err(
r#"Result<T, E> expects an externally tagged object: {"Ok": ...} or {"Err": ...}"#
.to_string(),
);
};
if map.len() != 1 {
return Err("Result<T, E> expects exactly one variant key: Ok or Err".to_string());
}
if let Some(payload) = map.remove("Ok") {
return decode_json_single_payload(payload, "value", ok_type, tree).map(Value::result_ok);
}
if let Some(payload) = map.remove("Err") {
return decode_json_single_payload(payload, "error", err_type, tree).map(Value::result_err);
}
let name = map.keys().next().cloned().unwrap_or_default();
Err(format!(
"object key `{name}` is not a Result variant; expected Ok or Err"
))
}
fn decode_json_single_payload(
payload: JsonValue,
field_name: &str,
field_type: Option<&TypeNode>,
tree: &AnalyzedTree,
) -> Result<Value, String> {
let Some(field_type) = field_type else {
return targetless_json_to_value(payload);
};
match decode_json_for_type(payload.clone(), field_type, tree) {
Ok(value) => Ok(value),
Err(direct_err) => match payload {
JsonValue::Object(mut map) if map.len() == 1 && map.contains_key(field_name) => {
let inner = map.remove(field_name).expect("checked payload field");
decode_json_for_type(inner, field_type, tree)
}
_ => Err(direct_err),
},
}
}
fn decode_json_array_as_tuple_or_targetless(
json: JsonValue,
element_types: &[TypeNode],
tree: &AnalyzedTree,
) -> Result<Value, String> {
match json {
JsonValue::Array(items) => {
let mut values = Vec::with_capacity(items.len());
for (idx, item) in items.into_iter().enumerate() {
let value = match element_types.get(idx) {
Some(slot_type) => decode_json_for_type(item, slot_type, tree)?,
None => targetless_json_to_value(item)?,
};
values.push(value);
}
Ok(Value::tuple(values))
}
other => targetless_json_to_value(other),
}
}
fn decode_json_array_as_list_or_targetless(
json: JsonValue,
item_type: Option<&TypeNode>,
tree: &AnalyzedTree,
) -> Result<Value, String> {
match json {
JsonValue::Array(items) => {
let mut values = Vec::with_capacity(items.len());
for item in items {
let value = match item_type {
Some(item_type) => decode_json_for_type(item, item_type, tree)?,
None => targetless_json_to_value(item)?,
};
values.push(value);
}
Ok(Value::list(values))
}
other => targetless_json_to_value(other),
}
}
fn decode_json_object_as_dict_or_targetless(
json: JsonValue,
value_type: Option<&TypeNode>,
tree: &AnalyzedTree,
) -> Result<Value, String> {
match json {
JsonValue::Object(map) => {
let mut values = Vec::with_capacity(map.len());
for (key, item) in map {
let value = match value_type {
Some(value_type) => decode_json_for_type(item, value_type, tree)?,
None => targetless_json_to_value(item)?,
};
values.push((key, value));
}
Ok(Value::dict(values))
}
other => targetless_json_to_value(other),
}
}
fn decode_json_object_as_schema_or_targetless(
json: JsonValue,
field_types: &HashMap<String, TypeNode>,
tree: &AnalyzedTree,
) -> Result<Value, String> {
match json {
JsonValue::Object(map) => {
let mut values = Vec::with_capacity(map.len());
for (key, item) in map {
let value = match field_types.get(&key) {
Some(field_type) => decode_json_for_type(item, field_type, tree)?,
None => targetless_json_to_value(item)?,
};
values.push((key, value));
}
Ok(Value::dict(values))
}
other => targetless_json_to_value(other),
}
}
fn decode_json_for_tagged_enum_schema(
json: JsonValue,
type_hint: &TypeNode,
def: &SchemaDef,
tree: &AnalyzedTree,
) -> Result<Value, String> {
let enum_name = def.name.clone().unwrap_or_else(|| type_key(type_hint));
match json {
JsonValue::String(name) => decode_json_string_as_enum_unit(name, &enum_name, def),
JsonValue::Object(map) => {
if map.len() != 1 {
return Err(format!(
"enum `{enum_name}` expects an externally tagged object with exactly one variant key"
));
}
let (variant_name, payload) = map
.into_iter()
.next()
.expect("checked exactly one externally tagged enum entry");
decode_json_object_as_enum_variant(variant_name, payload, type_hint, def, tree)
}
other => targetless_json_to_value(other),
}
}
fn decode_json_string_as_enum_unit(
name: String,
enum_name: &str,
def: &SchemaDef,
) -> Result<Value, String> {
let matching: Vec<_> = def
.variants
.iter()
.filter(|variant| variant.name == name)
.collect();
match matching.as_slice() {
[variant] if variant.fields.is_empty() => Ok(Value::variant_dict(
Vec::<(String, Value)>::new(),
variant.name.clone(),
enum_name.to_string(),
)),
[variant] => Err(format!(
"string `{}` names enum variant `{}` but that variant requires payload fields",
name, variant.name
)),
[] => Err(format!(
"string `{name}` does not name a unit variant of enum `{enum_name}`"
)),
_ => Err(format!(
"string `{name}` is ambiguous for enum `{enum_name}`"
)),
}
}
fn decode_json_object_as_enum_variant(
variant_name: String,
payload: JsonValue,
type_hint: &TypeNode,
def: &SchemaDef,
tree: &AnalyzedTree,
) -> Result<Value, String> {
let enum_name = def.name.clone().unwrap_or_else(|| type_key(type_hint));
let variant = def
.variants
.iter()
.find(|variant| variant.name == variant_name)
.ok_or_else(|| {
format!("object key `{variant_name}` is not a variant of enum `{enum_name}`")
})?;
let fields = substituted_variant_fields(variant, def, &type_hint.generics)?;
if fields.is_empty() {
return match payload {
JsonValue::Object(map) if map.is_empty() => Ok(Value::variant_dict(
Vec::<(String, Value)>::new(),
variant.name.clone(),
enum_name,
)),
_ => Err(format!(
"unit enum variant `{}` expects an empty object payload",
variant.name
)),
};
}
let values = if variant_fields_are_tuple_payload(&fields) {
decode_json_payload_as_tuple_variant(payload, &fields, tree, &variant.name)?
} else {
decode_json_payload_as_struct_variant(payload, &fields, tree, &variant.name)?
};
Ok(Value::variant_dict(values, variant.name.clone(), enum_name))
}
fn substituted_variant_fields(
variant: &relon_analyzer::schema::EnumVariant,
def: &SchemaDef,
concrete_args: &[TypeNode],
) -> Result<Vec<(String, TypeNode)>, String> {
variant
.fields
.iter()
.map(|field| {
let type_hint = field.type_hint.as_ref().ok_or_else(|| {
format!(
"enum variant `{}` field `{}` has no static type",
variant.name, field.name
)
})?;
Ok((
field.name.clone(),
substitute_schema_type(type_hint, &def.generics, concrete_args),
))
})
.collect()
}
fn variant_fields_are_tuple_payload(fields: &[(String, TypeNode)]) -> bool {
!fields.is_empty()
&& fields
.iter()
.enumerate()
.all(|(idx, (name, _))| *name == idx.to_string())
}
fn decode_json_payload_as_tuple_variant(
payload: JsonValue,
fields: &[(String, TypeNode)],
tree: &AnalyzedTree,
variant_name: &str,
) -> Result<Vec<(String, Value)>, String> {
let JsonValue::Array(items) = payload else {
return Err(format!(
"tuple enum variant `{variant_name}` expects a JSON array payload"
));
};
if items.len() != fields.len() {
return Err(format!(
"tuple enum variant `{variant_name}` expects {} elements, got {}",
fields.len(),
items.len()
));
}
fields
.iter()
.zip(items)
.map(|((name, field_type), item)| {
decode_json_for_type(item, field_type, tree).map(|value| (name.clone(), value))
})
.collect()
}
fn decode_json_payload_as_struct_variant(
payload: JsonValue,
fields: &[(String, TypeNode)],
tree: &AnalyzedTree,
variant_name: &str,
) -> Result<Vec<(String, Value)>, String> {
let JsonValue::Object(mut map) = payload else {
return Err(format!(
"struct enum variant `{variant_name}` expects a JSON object payload"
));
};
let mut values = Vec::with_capacity(fields.len());
for (name, field_type) in fields {
let item = map
.remove(name)
.ok_or_else(|| format!("enum variant `{variant_name}` is missing field `{name}`"))?;
values.push((name.clone(), decode_json_for_type(item, field_type, tree)?));
}
if !map.is_empty() {
let mut names: Vec<_> = map.keys().cloned().collect();
names.sort();
return Err(format!(
"enum variant `{variant_name}` received unknown field(s): {}",
names.join(", ")
));
}
Ok(values)
}
fn decode_json_for_enum(
json: JsonValue,
type_hint: &TypeNode,
tree: &AnalyzedTree,
) -> Result<Value, String> {
let arity = match &json {
JsonValue::Array(items) => items.len(),
_ => return targetless_json_to_value(json),
};
let matching_tuple_alts: Vec<&TypeNode> = type_hint
.generics
.iter()
.filter(|alt| type_accepts_tuple_array(alt, arity, tree))
.collect();
if matching_tuple_alts.len() == 1 {
decode_json_for_type(json, matching_tuple_alts[0], tree)
} else {
targetless_json_to_value(json)
}
}
fn type_accepts_tuple_array(type_hint: &TypeNode, arity: usize, tree: &AnalyzedTree) -> bool {
if type_key(type_hint) == "Tuple" {
return type_hint.generics.len() == arity;
}
matches!(
schema_tuple_elements_for_type(type_hint, tree),
Some(elements) if elements.len() == arity
)
}
fn targetless_json_to_value(json: JsonValue) -> Result<Value, String> {
if json.is_null() {
return Err("JSON null needs an Option<T> target type".to_string());
}
serde_json::from_value::<Value>(json).map_err(|e| format!("invalid JSON value: {e}"))
}
fn schema_tuple_elements_for_type(
type_hint: &TypeNode,
tree: &AnalyzedTree,
) -> Option<Vec<TypeNode>> {
if let Some(def) = local_schema_def_for_type(type_hint, tree) {
if let Some(elements) = &def.tuple_elements {
return Some(substitute_schema_types(
elements,
&def.generics,
&type_hint.generics,
));
}
}
let key = type_key(type_hint);
let imports = tree.workspace_import_index.as_ref()?;
let elements = imports.imported_tuple_schemas.get(&key)?;
let generics = imports
.imported_schema_generics
.get(&key)
.cloned()
.unwrap_or_default();
Some(substitute_schema_types(
elements,
&generics,
&type_hint.generics,
))
}
fn schema_fields_for_type(
type_hint: &TypeNode,
tree: &AnalyzedTree,
) -> Option<HashMap<String, TypeNode>> {
if let Some(def) = local_schema_def_for_type(type_hint, tree) {
return Some(substitute_schema_fields_from_def(def, &type_hint.generics));
}
let key = type_key(type_hint);
let imports = tree.workspace_import_index.as_ref()?;
let fields = imports.imported_schemas.get(&key)?;
let generics = imports
.imported_schema_generics
.get(&key)
.cloned()
.unwrap_or_default();
Some(substitute_schema_fields(
fields,
&generics,
&type_hint.generics,
))
}
fn local_schema_def_for_type<'a>(
type_hint: &TypeNode,
tree: &'a AnalyzedTree,
) -> Option<&'a SchemaDef> {
if type_hint.path.len() != 1 {
return None;
}
let name = &type_hint.path[0];
let decl = tree.root_schemas.iter().find(|decl| &decl.name == name)?;
tree.schemas.get(&decl.schema_node.id)
}
fn schema_def_for_type<'a>(type_hint: &TypeNode, tree: &'a AnalyzedTree) -> Option<&'a SchemaDef> {
if let Some(def) = local_schema_def_for_type(type_hint, tree) {
return Some(def);
}
let key = type_key(type_hint);
tree.workspace_import_index
.as_ref()?
.imported_schema_defs
.get(&key)
}
fn substitute_schema_fields_from_def(
def: &SchemaDef,
concrete_args: &[TypeNode],
) -> HashMap<String, TypeNode> {
let fields = def.fields.iter().filter_map(|field| {
let type_hint = field.type_hint.as_ref()?;
Some((field.name.clone(), type_hint.clone()))
});
substitute_schema_fields_from_iter(fields, &def.generics, concrete_args)
}
fn substitute_schema_fields(
fields: &HashMap<String, TypeNode>,
generic_names: &[String],
concrete_args: &[TypeNode],
) -> HashMap<String, TypeNode> {
substitute_schema_fields_from_iter(
fields
.iter()
.map(|(name, type_hint)| (name.clone(), type_hint.clone())),
generic_names,
concrete_args,
)
}
fn substitute_schema_fields_from_iter(
fields: impl Iterator<Item = (String, TypeNode)>,
generic_names: &[String],
concrete_args: &[TypeNode],
) -> HashMap<String, TypeNode> {
fields
.map(|(name, type_hint)| {
(
name,
substitute_schema_type(&type_hint, generic_names, concrete_args),
)
})
.collect()
}
fn substitute_schema_types(
types: &[TypeNode],
generic_names: &[String],
concrete_args: &[TypeNode],
) -> Vec<TypeNode> {
types
.iter()
.map(|type_hint| substitute_schema_type(type_hint, generic_names, concrete_args))
.collect()
}
fn substitute_schema_type(
type_hint: &TypeNode,
generic_names: &[String],
concrete_args: &[TypeNode],
) -> TypeNode {
let subst: HashMap<String, TypeNode> = generic_names
.iter()
.cloned()
.zip(concrete_args.iter().cloned())
.collect();
if subst.is_empty() {
type_hint.clone()
} else {
substitute_generics_in_typenode(type_hint, &subst)
}
}
fn type_key(type_hint: &TypeNode) -> String {
type_hint.path.join(".")
}
#[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,
) -> 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,
);
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)));
}
let has_main = workspace
.modules
.get(&cache_namespace)
.and_then(|tree| tree.main_signature.as_ref())
.is_some();
println!("ok: analyzer");
match backend {
BackendArg::TreeWalk => {
println!("backend tree-walk: compatible (reference evaluator)");
Ok(())
}
BackendArg::CraneliftAot => {
if trust {
warn_trust_unsupported_on_aot();
}
check_cranelift_compat(&content, has_main, "cranelift-aot", true)
}
BackendArg::Auto => {
if !has_main {
println!("backend auto: compatible (library-mode routes to tree-walk)");
return Ok(());
}
if relon::is_trivial_scalar_main(&content) {
println!("backend auto: compatible (trivial #main routes to tree-walk)");
return Ok(());
}
check_cranelift_compat(&content, has_main, "auto/cranelift-aot", false)
}
}
}
fn check_cranelift_compat(
content: &str,
has_main: bool,
label: &str,
strict: bool,
) -> miette::Result<()> {
if !has_main {
let message = format!("{label}: incompatible (cranelift-aot requires `#main(...)`)");
return if strict {
Err(miette::miette!("{message}"))
} else {
println!("backend {message}; auto will route to tree-walk");
Ok(())
};
}
match AotEvaluator::from_source(content) {
Ok(_) => {
println!("backend {label}: compatible");
Ok(())
}
Err(e) if e.is_unsupported_shape() && !strict => {
println!("backend {label}: not compiled ({e}); auto will fall back to tree-walk");
Ok(())
}
Err(e) => Err(miette::miette!("{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(())
}
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(())
}
}