resynth 0.4.0

A packet synthesis language
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
use std::cmp::Ordering;
use std::collections::HashMap;
use std::fmt::{Debug, Display, Formatter};
use std::io::Write;

use derive_more::Display;

use crate::args::{ArgSpec, ArgVec, Args};
use crate::err::Error;
use crate::err::Error::TypeError;
use crate::object::ObjRef;
use crate::sym::Symbol;
use crate::val::{Typed, Val, ValDef, ValType};

/// Argument declarator
#[derive(Debug, Clone, Copy, PartialEq, Eq, Display)]
pub enum ArgDecl {
    #[display("{}", _0)]
    Positional(ValType),
    #[display("{} = {}", _0.val_type(), _0)]
    Optional(ValDef),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Display)]
#[display("{}: {}", name, typ)]
pub struct ArgDesc {
    pub name: &'static str,
    pub typ: ArgDecl,
}

/// Defines a function or method for the resynth stdlib
#[derive(Debug)]
pub struct FuncDef {
    pub name: &'static str,
    pub return_type: ValType,
    /// Invariant: All Positionals must come first, then all Optional
    pub args: &'static [ArgDesc],
    pub arg_pos: fn(name: &str) -> Option<usize>,
    /// minimum number of args: ie. number of positionals
    pub min_args: usize,
    pub collect_type: ValType,
    pub exec: fn(args: Args) -> Result<Val, Error>,
    pub doc: &'static str,
}

impl Eq for FuncDef {}
impl PartialEq for FuncDef {
    fn eq(&self, other: &FuncDef) -> bool {
        std::ptr::eq(self as *const FuncDef, other as *const FuncDef)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SymDesc {
    pub name: &'static str,
    pub sym: Symbol,
}

/// Applies to anything with a symbol table which is documented into a documentation page
/// ie. classes and modules
pub trait Documented {
    fn symtab(&self) -> &'static [SymDesc];
    fn front_matter(&self) -> &'static str;

    fn symbol_set<F>(&self, flt: F) -> Vec<SymDesc>
    where
        F: FnMut(&SymDesc) -> bool,
    {
        let mut ret: Vec<SymDesc> = self.symtab().iter().cloned().filter(flt).collect();
        ret.sort();
        ret.shrink_to_fit();
        ret
    }

    fn modules(&self) -> Vec<SymDesc> {
        self.symbol_set(|&x| matches!(x.sym, Symbol::Module(_)))
    }

    fn functions(&self) -> Vec<SymDesc> {
        self.symbol_set(|&x| matches!(x.sym, Symbol::Func(_)))
    }

    fn classes(&self) -> Vec<SymDesc> {
        self.symbol_set(|&x| matches!(x.sym, Symbol::Class(_)))
    }

    fn constants(&self) -> Vec<SymDesc> {
        self.symbol_set(|&x| matches!(x.sym, Symbol::Val(_)))
    }

    fn write_docs<W: Write>(&self, wr: &mut W) -> Result<(), std::io::Error> {
        wr.write_all(self.front_matter().as_bytes())?;

        let submods = self.modules();
        let funcs = self.functions();
        let classes = self.classes();
        let consts = self.constants();

        wr.write_all(b"\n## Index\n\n")?;

        if !submods.is_empty() {
            wr.write_all(b"\n### Modules\n\n")?;
            for SymDesc { name, sym: _ } in &submods {
                wr.write_all(format!("- [{}]({}/README.md)\n", name, name,).as_bytes())?;
            }
        }

        if !classes.is_empty() {
            wr.write_all(b"\n### Classes\n\n")?;
            for SymDesc { name, sym: _ } in &classes {
                wr.write_all(format!("- [{}]({}.md)\n", name, name,).as_bytes())?;
            }
        }

        if !funcs.is_empty() {
            wr.write_all(b"\n### Functions\n\n")?;
            for SymDesc { name, sym: _ } in &funcs {
                wr.write_all(format!("- [{}](#{})\n", name, name,).as_bytes())?;
            }
        }

        if !consts.is_empty() {
            wr.write_all(b"\n### Constants\n\n")?;
            wr.write_all(b"| Name | Value |\n")?;
            wr.write_all(b"| ---- | ----- |\n")?;
            for SymDesc { name, sym } in &consts {
                if let Symbol::Val(val) = sym {
                    wr.write_all(
                        format!("| {} | `({}){}` |\n", name, val.val_type(), val,).as_bytes(),
                    )?;
                }
            }
        }

        if !funcs.is_empty() {
            wr.write_all(b"\n\n")?;
            for SymDesc { name, sym } in &funcs {
                if let Symbol::Func(func) = sym {
                    assert_eq!(*name, func.name);
                    func.write_docs(wr)?;
                }
            }
        }

        Ok(())
    }
}

impl PartialOrd for SymDesc {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for SymDesc {
    fn cmp(&self, other: &Self) -> Ordering {
        self.name.cmp(other.name)
    }
}

/// Defines a module for the resynth stdlib
#[derive(Debug)]
pub struct Module {
    pub name: &'static str,
    pub symtab: &'static [SymDesc],
    pub lookup: fn(name: &str) -> Option<usize>,
    pub doc: &'static str,
}

impl Documented for Module {
    fn symtab(&self) -> &'static [SymDesc] {
        self.symtab
    }

    fn front_matter(&self) -> &'static str {
        self.doc
    }
}

impl Module {
    pub fn get(&self, name: &str) -> Option<&'static Symbol> {
        match (self.lookup)(name) {
            Some(idx) => Some(&self.symtab[idx].sym),
            None => None,
        }
    }
}

/// Defines a module for the resynth stdlib
#[derive(Debug)]
pub struct ClassDef {
    pub name: &'static str,
    pub symtab: &'static [SymDesc],
    pub lookup: fn(name: &str) -> Option<usize>,
    pub doc: &'static str,
}

impl Documented for ClassDef {
    fn symtab(&self) -> &'static [SymDesc] {
        self.symtab
    }

    fn front_matter(&self) -> &'static str {
        self.doc
    }
}

impl ClassDef {
    pub fn get(&self, name: &str) -> Option<&'static Symbol> {
        match (self.lookup)(name) {
            Some(idx) => Some(&self.symtab[idx].sym),
            None => None,
        }
    }
}

pub trait Class {
    fn def(&self) -> &'static ClassDef;

    fn get(&self, name: &str) -> Option<&'static Symbol> {
        self.def().get(name)
    }

    fn symbols(&self) -> &'static [SymDesc] {
        self.def().symtab
    }

    fn class_name(&self) -> &'static str {
        self.def().name
    }

    fn doc(&self) -> &'static str {
        self.def().doc
    }
}

struct ArgPrep {
    positional: Vec<Val>,
    named: HashMap<String, Val>,
    extra: Vec<Val>,
}

/// Invariant: No argument may be supplied with a value more than once
/// Invariant: No argument can be ambiguous as to where it belongs
///
/// Rules:
///  P-FIRST Positonal args must be supplied first
///  P-NAME-OPTIONAL Positionals may be named or not
///  ANON-FIRST If one positional is named, all subsequent positionals + optionals must be named
///  COLLECT-NAME-OPTS if func has collect args, optionals MUST be named
///  NOCOLLECT-ANON-OPTS if func doesn't have collect args, optionals MAY be anonymous
///  COLLECT-AFTER-NAMED collect args must come after the last named arg
impl FuncDef {
    pub fn is_collect(&self) -> bool {
        self.collect_type != ValType::Void
    }

    fn split_args(&self, args: Vec<ArgSpec>) -> Result<ArgPrep, Error> {
        enum State {
            Anon,
            Optional,
            CollectOnly,
        }
        let mut positional: Vec<Val> = Vec::new();
        let mut named: HashMap<String, Val> = HashMap::new();
        let mut extra: Vec<Val> = Vec::new();
        let mut state = State::Anon;

        for arg in args {
            loop {
                match state {
                    State::Anon => {
                        if !arg.is_anon() {
                            state = State::Optional;
                            continue;
                        } else if self.is_collect() && positional.len() >= self.min_args {
                            // If we have collect args, then any optionals must be named
                            state = State::CollectOnly;
                            continue;
                        } else if positional.len() >= self.args.len() {
                            if self.is_collect() {
                                state = State::CollectOnly;
                                continue;
                            }
                            println!(
                                "ERR: {}: Too many arguments: {} > {}",
                                self.name,
                                positional.len(),
                                self.args.len()
                            );
                            return Err(TypeError);
                        } else {
                            positional.push(arg.val);
                            break;
                        }
                    }
                    State::Optional => {
                        if arg.is_anon() {
                            state = State::CollectOnly;
                            continue;
                        }

                        let name = arg.name.unwrap();

                        let arg_pos = (self.arg_pos)(&name);

                        if arg_pos.is_none() {
                            println!("ERR: {}: No such argument: \"{}\"", self.name, &name);
                            return Err(TypeError);
                        }

                        let arg_index = arg_pos.unwrap();

                        // Invariant: No argument may be supplied with a value more than once

                        // a) If the index of the arg is one of the positionals we've already got,
                        // then a positional has been specified by position, and is now attempting
                        // to be specified by name. So nope.
                        if arg_index < positional.len() {
                            println!(
                                "ERR: {}: Positional argument \"{}\" multiply specified",
                                self.name, &name
                            );
                            return Err(TypeError);
                        }

                        // b) if we've named the same arg twice then that's also not allowed.
                        if named.contains_key(&name) {
                            println!(
                                "ERR: {}: Optional argument \"{}\" multiply specified",
                                self.name, &name
                            );
                            return Err(TypeError);
                        }

                        named.insert(name, arg.val);
                        break;
                    }
                    State::CollectOnly => {
                        if !self.is_collect() {
                            println!("ERR: {}: Unexpected collect-arguments", self.name);
                            return Err(TypeError);
                        }
                        if arg.is_named() {
                            println!(
                                "ERR: {}: Unexpected named argument: \"{}\"",
                                self.name,
                                arg.name.unwrap()
                            );
                            return Err(TypeError);
                        }
                        extra.push(arg.val);
                        break;
                    }
                }
            }
        }

        positional.shrink_to_fit();
        named.shrink_to_fit();
        extra.shrink_to_fit();

        Ok(ArgPrep {
            positional,
            named,
            extra,
        })
    }

    pub fn argvec(&self, this: Option<ObjRef>, args: Vec<ArgSpec>) -> Result<ArgVec, Error> {
        let ArgPrep {
            positional,
            mut named,
            extra,
        } = self.split_args(args)?;
        let nr_positional = positional.len();
        let nr_named = named.len();
        let nr_specified = nr_positional + nr_named;

        // Now do some basic sanity checks to stup us shooting ourselves in the foot later
        if nr_specified < self.min_args {
            println!(
                "ERR: {}: Not enough specified args: {} ({} + {}) < {}",
                self.name, nr_specified, nr_positional, nr_named, self.min_args
            );
            return Err(TypeError);
        }

        let mut args: Vec<Val> = Vec::with_capacity(self.args.len());

        // 1. push anon vals to start with
        for a in positional {
            args.push(a);
        }

        // either all positional and optional args are supplied and then everything else is in
        // extra OR some positional/optional have been named, in which case all the collect args
        // are in extra assert!(args.len() <= self.args.len());

        // 2. Take named positionals and optionals
        for ArgDesc { name, typ } in self.args.iter().skip(nr_positional) {
            if let Some(val) = named.remove(*name) {
                // positional or optional specified by name, push it
                args.push(val);
            } else if let ArgDecl::Optional(dfl) = typ {
                // not specified, but we're optional, so take the default
                args.push((*dfl).into());
            } else {
                // not specified, and we're mandatory, barf
                println!(
                    "ERR: {}: Positional argument \"{}\" not specified",
                    self.name, name
                );
                return Err(TypeError);
            }
        }

        assert!(named.is_empty());

        // 3. Final type-check of all positional args
        for (ArgDesc { name, typ }, arg) in self.args.iter().zip(args.iter()) {
            if !match typ {
                ArgDecl::Positional(typ) => typ.compatible_with(arg),
                ArgDecl::Optional(dfl) => dfl.arg_compatible(arg),
            } {
                println!(
                    "ERR: {}: Argument type-check failed for {:?}",
                    self.name, name
                );
                return Err(TypeError);
            }
        }

        // 4. Type-check the collect-args
        if extra.iter().any(|x| !self.collect_type.compatible_with(x)) {
            println!("ERR: {}: Collect argument of wrong type", self.name);
            return Err(TypeError);
        }

        Ok(ArgVec::new(this, args, extra))
    }

    pub fn args(&self, this: Option<ObjRef>, args: Vec<ArgSpec>) -> Result<Args, Error> {
        Ok(self.argvec(this, args)?.into())
    }

    pub fn write_docs<W: Write>(&self, wr: &mut W) -> Result<(), std::io::Error> {
        wr.write_all(format!("\n## {}\n", self.name).as_bytes())?;
        wr.write_all(b"```resynth\n")?;
        wr.write_all(format!("{}\n", self).as_bytes())?;
        wr.write_all(b"```\n")?;
        wr.write_all(self.doc.as_bytes())?;
        wr.write_all(b"\n")?;
        Ok(())
    }
}

impl Display for FuncDef {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
        writeln!(f, "resynth fn {} (", self.name)?;

        for arg in self.args.iter() {
            writeln!(f, "    {},", arg)?;
        }

        if !self.collect_type.is_nil() {
            writeln!(f, "    =>\n    *collect_args: {},", self.collect_type)?;
        }

        write!(f, ") -> {};", self.return_type)
    }
}