module stutter import os import vile.scheme pub enum Output { quiet stderr } pub enum Defaults { // Use the embedded program only when the optional user file is absent. fallback // Evaluate the embedded program before the user file, in the same scope. overlay } // Config describes a Vile configuration program. Bindings such as gap := 4 // map directly onto fields when decoded; native procedures add app behavior. pub struct Config { pub: name string @[required] path string default_path string required bool defaults string defaults_mode Defaults skip_file bool evals []string primitives map[string]scheme.NativeFn aliases map[string]string // Syntax for defaults, parse, eval and evals; files select by extension. syntax scheme.SourceSyntax = .vile output Output max_steps int = 1_000_000 after_defaults fn () = unsafe { nil } } // Reader owns the evaluator, including the scope retained by deferred callbacks. // Every Config read creates a fresh Reader, so separate loads never share state. @[heap] pub struct Reader { pub: config Config pub mut: machine &scheme.VM } // config_path returns the per-user path, honoring XDG_CONFIG_HOME. pub fn config_path(name string) string { base := if os.getenv('XDG_CONFIG_HOME') != '' { os.getenv('XDG_CONFIG_HOME') } else { os.join_path(os.home_dir(), '.config') } return os.join_path(base, name, 'config.vile') } // selected_path resolves the explicit, application-default, or XDG file path. pub fn (c Config) selected_path() string { if c.path != '' { return c.path } if c.default_path != '' { return c.default_path } return config_path(c.name) } // reader creates the evaluator before reading, for applications which need to // connect runtime callbacks to that same evaluator. pub fn (c Config) reader() !&Reader { mut m := scheme.new_with_options(max_steps: c.max_steps)! input := m.input_port(ConfigIO{})! output := m.output_port(ConfigIO{ output: c.output })! m.set_input_port(input)! m.set_output_port(output)! mut r := &Reader{ config: c, machine: m } for name, primitive in c.primitives { m.register(name, primitive)! } for alias, target in c.aliases { m.define(alias, m.lookup(target)!)! } return r } // read is suitable for a global initializer. Invalid configuration prints a // diagnostic to stderr and exits with status 1. Use read_checked to handle errors. pub fn (c Config) read() &Reader { return c.read_checked() or { eprintln(err) exit(1) } } // read_checked creates a fresh reader and returns configuration errors. pub fn (c Config) read_checked() !&Reader { mut r := c.reader()! r.load()! return r } // parse evaluates exactly source, without discovering a file or adding defaults. pub fn (c Config) parse(source string) !&Reader { mut r := c.reader()! r.eval(source, '<${c.name} config>')! return r } // load evaluates defaults, the selected file, then command-line expressions. pub fn (mut r Reader) load() ! { c := r.config path := c.selected_path() // Check an explicitly requested or required file before running defaults. if !c.skip_file && (c.path != '' || c.required) && !os.exists(path) { return error('configuration does not exist: ${path}') } has_file := !c.skip_file && os.exists(path) if c.defaults_mode == .overlay || !has_file { if c.defaults != '' { r.eval(c.defaults, '<${c.name} defaults>')! } if c.after_defaults != unsafe { nil } { c.after_defaults() } } if has_file { // File extensions select Vile (.vile) or Scheme (all other extensions). r.machine.eval_file(os.real_path(path)) or { if scheme.is_control_transfer(err) { return err } return error('config ${path}: ${err.msg()}') } } for source in c.evals { r.eval(source, '<${c.name} --eval>')! } } // eval evaluates source in this reader's scope, labeling errors with its origin. pub fn (mut r Reader) eval(source string, label string) !scheme.Value { if r.config.syntax == .scheme { return r.machine.eval(source) or { if scheme.is_control_transfer(err) { return err } return error('${label}: ${err.msg()}') } } return r.machine.eval_alt(source) or { if scheme.is_control_transfer(err) { return err } return error('${label}: ${err.msg()}') } } // call invokes a deferred configuration callback in its original lexical scope. pub fn (mut r Reader) call(action scheme.Value) !scheme.Value { return r.machine.call(action, []scheme.Value{}) or { if scheme.is_control_transfer(err) { return err } return error('<${r.config.name} callback>: ${err.msg()}') } } // value reads a binding from this reader's current global environment. pub fn (r &Reader) value(name string) !scheme.Value { return r.machine.lookup(name) } // decode applies bindings to a V struct, retaining base defaults for absent // names. A hyphenated binding takes precedence over its underscored spelling. pub fn (r &Reader) decode[T](base T) !T { mut result := base mut values := map[string]scheme.Value{} $for field in T.fields { name := field.name.replace('_', '-') if value := r.value(name) { values[field.name] = value } else if value := r.value(field.name) { values[field.name] = value } } apply_values(mut result, values, []string{})! return result } // Default ports never read stdin and discard output unless stderr is selected. struct ConfigIO { output Output } fn (_ ConfigIO) read(mut _buffer []u8) !int { return 0 } fn (h ConfigIO) write(buffer []u8) !int { if h.output == .stderr { eprint(buffer.bytestr()) } return buffer.len }