tokay 0.6.3

Tokay is a programming language designed for ad-hoc parsing.
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
//! Intermediate value representation
use super::*;
use crate::compiler::Compiler;
use crate::reader::Offset;
use crate::value::{Object, RefValue, Value};
use crate::Error;
use num::ToPrimitive;
use std::cell::RefCell;
use std::rc::Rc;

/** Intermediate value

Intermediate values are values that result during the compile process based on current information
from the syntax tree and symbol table information.

These can be memory locations of variables, static values, functions or values whose definition is
still pending.
*/

#[derive(Clone, PartialEq, Eq)]
pub(in crate::compiler) enum ImlValue {
    Void,
    Shared(Rc<RefCell<ImlValue>>),

    // Resolved
    Value(RefValue),                    // Compile-time static value
    Local(usize),                       // Runtime local variable
    Global(usize),                      // Runtime global variable
    Parselet(Rc<RefCell<ImlParselet>>), // Parselet

    // Unresolved
    Name {
        // Unresolved name
        offset: Option<Offset>, // Source offset
        generic: bool,          // Generic name, to be resolved during compilation
        name: String,           // Identifier
    },
    Instance {
        // Parselet instance
        offset: Option<Offset>, // Source offset
        target: Box<ImlValue>,  // Instance target
        config: Vec<(Option<Offset>, Option<String>, ImlValue)>, // Constant configuration
    },
}

impl ImlValue {
    /// Try to resolve immediatelly, otherwise push shared reference to compiler's unresolved ImlValue.
    pub fn try_resolve(mut self, compiler: &mut Compiler) -> Self {
        if self.resolve(compiler) {
            return self;
        }

        let shared = Self::Shared(Rc::new(RefCell::new(self)));
        compiler.usages.push(shared.clone());
        shared
    }

    /// Resolve unresolved ImlValue. Returns true in case the provided value is (already) resolved.
    pub fn resolve(&mut self, compiler: &mut Compiler) -> bool {
        match self {
            Self::Shared(value) => value.borrow_mut().resolve(compiler),
            Self::Name { name, .. } => {
                if let Some(value) = compiler.get(&name) {
                    *self = value;
                    true
                } else {
                    false
                }
            }
            /*
            Self::Instance {
                target,
                ..
            } if matches!(target, ImlValue::Name(_)) => {
                // Try to resolve target
                if target.resolve(compiler) {
                    // On success, try to resolve the entire instance
                    return self.resolve(compiler);
                }
            }
            Self::Instance {
                target:
                    ImlValue::Parselet {
                        parselet,
                        constants,
                    },
                config,
                offset,
            } => {
                todo!();
            }
            */
            _ => true,
        }
    }

    pub fn into_refvalue(self) -> RefValue {
        match self {
            Self::Value(value) => value,
            _ => unreachable!("{:?} cannot be unwrapped", self),
        }
    }

    /// Check whether intermediate value represents callable,
    /// and when its callable if with or without arguments.
    pub fn is_callable(&self, without_arguments: bool) -> bool {
        match self {
            Self::Shared(value) => value.borrow().is_callable(without_arguments),
            Self::Value(value) => value.is_callable(without_arguments),
            Self::Parselet(parselet) => {
                let parselet = parselet.borrow();

                if without_arguments {
                    parselet.signature.len() == 0
                        || parselet
                            .signature
                            .iter()
                            .all(|arg| !matches!(arg.1, Self::Void))
                } else {
                    true
                }
            }
            _ => false,
        }
    }

    /// Check whether intermediate value represents consuming
    pub fn is_consuming(&self) -> bool {
        match self {
            Self::Shared(value) => value.borrow().is_consuming(),
            Self::Name { name, .. } => crate::utils::identifier_is_consumable(name),
            Self::Value(value) => value.is_consuming(),
            Self::Parselet(parselet) => parselet.borrow().consuming,
            _ => false,
        }
    }

    /** Generates code for a value load. For several, oftenly used values, there exists a direct operation pendant,
    which makes storing the static value obsolete. Otherwise, *value* will be registered and a static load operation
    is returned. */
    pub fn compile_load(&self, program: &mut ImlProgram, ops: &mut Vec<Op>) {
        match self {
            ImlValue::Shared(value) => return value.borrow().compile_load(program, ops),
            ImlValue::Value(value) => match &*value.borrow() {
                Value::Void => return ops.push(Op::PushVoid),
                Value::Null => return ops.push(Op::PushNull),
                Value::True => return ops.push(Op::PushTrue),
                Value::False => return ops.push(Op::PushFalse),
                Value::Int(i) => match i.to_i64() {
                    Some(0) => return ops.push(Op::Push0),
                    Some(1) => return ops.push(Op::Push1),
                    _ => {}
                },
                _ => {}
            },
            ImlValue::Parselet(_) => {}
            ImlValue::Local(addr) => return ops.push(Op::LoadFast(*addr)),
            ImlValue::Global(addr) => return ops.push(Op::LoadGlobal(*addr)),
            ImlValue::Name { name, .. } => {
                program.errors.push(Error::new(
                    None,
                    format!("Use of unresolved symbol '{}'", name),
                ));

                return;
            }
            _ => todo!(),
        }

        ops.push(Op::LoadStatic(program.register(self)))
    }

    /** Generates code for a value call. */
    pub fn compile_call(
        &self,
        program: &mut ImlProgram,
        args: Option<(usize, bool)>,
        ops: &mut Vec<Op>,
    ) {
        match self {
            ImlValue::Shared(value) => return value.borrow().compile_call(program, args, ops),
            ImlValue::Local(addr) => ops.push(Op::LoadFast(*addr)),
            ImlValue::Global(addr) => ops.push(Op::LoadGlobal(*addr)),
            ImlValue::Name { name, .. } => {
                program.errors.push(Error::new(
                    None,
                    format!("Call to unresolved symbol '{}'", name),
                ));
                return;
            }
            value => {
                // When value is a parselet, check for accepted constant configuration
                /*
                if let ImlValue::Parselet {
                    parselet: _,
                    constants,
                } = value
                {
                    if !constants.is_empty() {
                        let mut required = Vec::new();

                        for (name, default) in constants {
                            if matches!(default, ImlValue::Void) {
                                required.push(name.to_string());
                            }
                        }

                        if !required.is_empty() {
                            program.errors.push(Error::new(
                                offset.clone(),
                                format!(
                                    "On call to '{}', missing generic constants for {}",
                                    value,
                                    required.join(", ")
                                ),
                            ));

                            return 0;
                        }
                    }
                }
                */
                let idx = program.register(value);

                match args {
                    // Qualified call
                    Some((args, nargs)) => {
                        if args == 0 && !nargs {
                            ops.push(Op::CallStatic(idx));
                        } else if args > 0 && !nargs {
                            ops.push(Op::CallStaticArg(Box::new((idx, args))));
                        } else {
                            ops.push(Op::CallStaticArgNamed(Box::new((idx, args))));
                        }
                    }
                    // Call or load
                    None => {
                        if value.is_callable(true) {
                            ops.push(Op::CallStatic(idx));
                        } else {
                            ops.push(Op::LoadStatic(idx));
                        }
                    }
                }

                return;
            }
            _ => todo!(),
        }

        match args {
            // Qualified call
            Some((args, nargs)) => {
                if args == 0 && nargs == false {
                    ops.push(Op::Call);
                } else if args > 0 && nargs == false {
                    ops.push(Op::CallArg(args));
                } else {
                    ops.push(Op::CallArgNamed(args));
                }
            }
            // Call or load
            None => ops.push(Op::CallOrCopy),
        }
    }
}

impl std::fmt::Debug for ImlValue {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Void => write!(f, "void"),
            Self::Shared(value) => value.borrow().fmt(f),
            Self::Value(v) => v.borrow().fmt(f),
            Self::Parselet { .. } => write!(f, "{}", self),
            Self::Local(addr) => write!(f, "local@{}", addr),
            Self::Global(addr) => write!(f, "global@{}", addr),
            Self::Name { name, .. } => write!(f, "{}", name),
            _ => todo!(),
        }
    }
}

impl std::fmt::Display for ImlValue {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Void => write!(f, "void"),
            Self::Shared(value) => value.borrow().fmt(f),
            Self::Value(value) => write!(f, "{}", value.repr()),
            Self::Parselet(parselet) => {
                write!(
                    f,
                    "{}",
                    parselet
                        .borrow()
                        .name
                        .as_deref()
                        .unwrap_or("<anonymous parselet>")
                )?;

                /*
                if !constants.is_empty() {
                    write!(f, "<")?;
                    for (i, (name, value)) in constants.iter().enumerate() {
                        if matches!(value, ImlValue::Void) {
                            write!(f, "{}{}", if i > 0 { ", " } else { "" }, name)?;
                        } else {
                            write!(f, "{}{}:{}", if i > 0 { ", " } else { "" }, name, value)?;
                        }
                    }
                    write!(f, ">")?;
                }
                */

                Ok(())
            }
            Self::Name { name, .. } => write!(f, "{}", name),
            _ => todo!(),
        }
    }
}

/*
impl std::fmt::Display for ImlValue {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Void => write!(f, "void"),
            Self::Unknown(name) | Self::Undefined(name) => write!(f, "{}", name),
            Self::Value(value) => write!(f, "{}", value.repr()),
            Self::Parselet {
                parselet,
                constants,
            } => {
                write!(
                    f,
                    "{}",
                    parselet
                        .borrow()
                        .name
                        .as_deref()
                        .unwrap_or("<anonymous parselet>")
                )?;

                if !constants.is_empty() {
                    write!(f, "<")?;
                    for (i, (name, value)) in constants.iter().enumerate() {
                        if matches!(value, ImlValue::Void) {
                            write!(f, "{}{}", if i > 0 { ", " } else { "" }, name)?;
                        } else {
                            write!(f, "{}{}:{}", if i > 0 { ", " } else { "" }, name, value)?;
                        }
                    }
                    write!(f, ">")?;
                }

                Ok(())
            }
            Self::Local(addr) => write!(f, "local@{}", addr),
            Self::Global(addr) => write!(f, "global@{}", addr),
            Self::Symbol {
                name,
                gen_by_seq,
                gen_by_name,
            } => {
                write!(f, "{}", target)?;

                let mut first = true;

                for item in gen_by_seq {
                    write!(f, "{}{}", if !first { ", " } else { "<" }, item)?;
                    first = false;
                }

                for (name, item) in gen_by_name.iter() {
                    write!(f, "{}{}:{}", if !first { ", " } else { "<" }, name, item)?;
                    first = false;
                }

                if !first {
                    write!(f, ">")?;
                }

                Ok(())
            }
        }
    }
}
*/

impl std::hash::Hash for ImlValue {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        match self {
            Self::Value(v) => {
                state.write_u8('v' as u8);
                v.hash(state)
            }
            Self::Parselet(parselet) => {
                state.write_u8('p' as u8);
                parselet.borrow().hash(state);
                //constants.iter().collect::<Vec<_>>().hash(state);
            }
            other => unreachable!("{:?} is unhashable", other),
        }
    }
}

impl From<RefValue> for ImlValue {
    fn from(value: RefValue) -> Self {
        Self::Value(value)
    }
}