stutter / config.v
180 lines · 161 sloc · 5.44 KB · 0c355e9d3499f38b7165fd530ac3b1c25dbf93b2
Raw
1module stutter
2
3import os
4import vile.scheme
5
6pub enum Output {
7 quiet
8 stderr
9}
10
11pub enum Defaults {
12 // Use the embedded program only when the optional user file is absent.
13 fallback
14 // Evaluate the embedded program before the user file, in the same scope.
15 overlay
16}
17
18// Config describes a Vile configuration program. Bindings such as gap := 4
19// map directly onto fields when decoded; native procedures add app behavior.
20pub struct Config {
21pub:
22 name string @[required]
23 path string
24 default_path string
25 required bool
26 defaults string
27 defaults_mode Defaults
28 skip_file bool
29 evals []string
30 primitives map[string]scheme.NativeFn
31 aliases map[string]string
32 // Syntax for defaults, parse, eval and evals; files select by extension.
33 syntax scheme.SourceSyntax = .vile
34 output Output
35 max_steps int = 1_000_000
36 after_defaults fn () = unsafe { nil }
37}
38
39// Reader owns the evaluator, including the scope retained by deferred callbacks.
40// Every Config read creates a fresh Reader, so separate loads never share state.
41@[heap]
42pub struct Reader {
43pub:
44 config Config
45pub mut:
46 machine &scheme.VM
47}
48
49// config_path returns the per-user path, honoring XDG_CONFIG_HOME.
50pub fn config_path(name string) string {
51 base := if os.getenv('XDG_CONFIG_HOME') != '' {
52 os.getenv('XDG_CONFIG_HOME')
53 } else {
54 os.join_path(os.home_dir(), '.config')
55 }
56 return os.join_path(base, name, 'config.vile')
57}
58
59// selected_path resolves the explicit, application-default, or XDG file path.
60pub fn (c Config) selected_path() string {
61 if c.path != '' { return c.path }
62 if c.default_path != '' { return c.default_path }
63 return config_path(c.name)
64}
65
66// reader creates the evaluator before reading, for applications which need to
67// connect runtime callbacks to that same evaluator.
68pub fn (c Config) reader() !&Reader {
69 mut m := scheme.new_with_options(max_steps: c.max_steps)!
70 input := m.input_port(ConfigIO{})!
71 output := m.output_port(ConfigIO{ output: c.output })!
72 m.set_input_port(input)!
73 m.set_output_port(output)!
74 mut r := &Reader{ config: c, machine: m }
75 for name, primitive in c.primitives { m.register(name, primitive)! }
76 for alias, target in c.aliases { m.define(alias, m.lookup(target)!)! }
77 return r
78}
79
80// read is suitable for a global initializer. Invalid configuration prints a
81// diagnostic to stderr and exits with status 1. Use read_checked to handle errors.
82pub fn (c Config) read() &Reader {
83 return c.read_checked() or {
84 eprintln(err)
85 exit(1)
86 }
87}
88
89// read_checked creates a fresh reader and returns configuration errors.
90pub fn (c Config) read_checked() !&Reader {
91 mut r := c.reader()!
92 r.load()!
93 return r
94}
95
96// parse evaluates exactly source, without discovering a file or adding defaults.
97pub fn (c Config) parse(source string) !&Reader {
98 mut r := c.reader()!
99 r.eval(source, '<${c.name} config>')!
100 return r
101}
102
103// load evaluates defaults, the selected file, then command-line expressions.
104pub fn (mut r Reader) load() ! {
105 c := r.config
106 path := c.selected_path()
107 // Check an explicitly requested or required file before running defaults.
108 if !c.skip_file && (c.path != '' || c.required) && !os.exists(path) {
109 return error('configuration does not exist: ${path}')
110 }
111 has_file := !c.skip_file && os.exists(path)
112 if c.defaults_mode == .overlay || !has_file {
113 if c.defaults != '' { r.eval(c.defaults, '<${c.name} defaults>')! }
114 if c.after_defaults != unsafe { nil } { c.after_defaults() }
115 }
116 if has_file {
117 // File extensions select Vile (.vile) or Scheme (all other extensions).
118 r.machine.eval_file(os.real_path(path)) or {
119 if scheme.is_control_transfer(err) { return err }
120 return error('config ${path}: ${err.msg()}')
121 }
122 }
123 for source in c.evals { r.eval(source, '<${c.name} --eval>')! }
124}
125
126// eval evaluates source in this reader's scope, labeling errors with its origin.
127pub fn (mut r Reader) eval(source string, label string) !scheme.Value {
128 if r.config.syntax == .scheme {
129 return r.machine.eval(source) or {
130 if scheme.is_control_transfer(err) { return err }
131 return error('${label}: ${err.msg()}')
132 }
133 }
134 return r.machine.eval_alt(source) or {
135 if scheme.is_control_transfer(err) { return err }
136 return error('${label}: ${err.msg()}')
137 }
138}
139
140// call invokes a deferred configuration callback in its original lexical scope.
141pub fn (mut r Reader) call(action scheme.Value) !scheme.Value {
142 return r.machine.call(action, []scheme.Value{}) or {
143 if scheme.is_control_transfer(err) { return err }
144 return error('<${r.config.name} callback>: ${err.msg()}')
145 }
146}
147
148// value reads a binding from this reader's current global environment.
149pub fn (r &Reader) value(name string) !scheme.Value {
150 return r.machine.lookup(name)
151}
152
153// decode applies bindings to a V struct, retaining base defaults for absent
154// names. A hyphenated binding takes precedence over its underscored spelling.
155pub fn (r &Reader) decode[T](base T) !T {
156 mut result := base
157 mut values := map[string]scheme.Value{}
158 $for field in T.fields {
159 name := field.name.replace('_', '-')
160 if value := r.value(name) {
161 values[field.name] = value
162 } else if value := r.value(field.name) {
163 values[field.name] = value
164 }
165 }
166 apply_values(mut result, values, []string{})!
167 return result
168}
169
170// Default ports never read stdin and discard output unless stderr is selected.
171struct ConfigIO {
172 output Output
173}
174
175fn (_ ConfigIO) read(mut _buffer []u8) !int { return 0 }
176
177fn (h ConfigIO) write(buffer []u8) !int {
178 if h.output == .stderr { eprint(buffer.bytestr()) }
179 return buffer.len
180}
181