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
//! ImlProgram glues ImlParselet, ImlOp and ImlValue together to produce a VM program.
use super::*;
use crate::reader::Offset;
use crate::value::Parselet;
use crate::vm::Program;
use crate::Error;
use crate::{Object, RefValue};
use indexmap::{indexmap, IndexMap, IndexSet};
use log;
use std::collections::{HashMap, HashSet};
#[derive(Debug)]
pub(in crate::compiler) struct ImlProgram {
main: ImlValue,
statics: IndexMap<ImlValue, Option<Parselet>>, // static values with optional final parselet replacement
errors: Vec<Error>, // errors collected during compilation
}
impl ImlProgram {
pub fn new(main: ImlValue) -> Self {
ImlProgram {
main: main.clone(),
statics: indexmap!(main => None),
errors: Vec::new(),
}
}
/// Push an Error to the programs's error log, with given offset and msg.
pub fn push_error(&mut self, offset: Option<Offset>, msg: String) {
self.errors.push(Error::new(offset, msg))
}
/** Registers an ImlValue in the ImlProgram's statics map and returns its index.
Only resolved values can be registered.
In case *value* already exists inside of the current statics, the existing index will be returned,
otherwiese the value is cloned and put into the statics table. */
pub fn register(&mut self, value: &ImlValue) -> usize {
match value {
ImlValue::Shared(value) => return self.register(&*value.borrow()),
ImlValue::Parselet(_) | ImlValue::Value(_) => match self.statics.get_index_of(value) {
None => return self.statics.insert_full(value.clone(), None).0,
Some(idx) => return idx,
},
ImlValue::Variable { offset, name, .. } => self.errors.push(Error::new(
offset.clone(),
format!("Variable '{}' used in static context", name),
)),
ImlValue::Generic { offset, .. } | ImlValue::Instance(ImlInstance { offset, .. }) => {
self.errors
.push(Error::new(offset.clone(), format!("Unresolved {}", value)));
}
_ => unreachable!(),
}
0
}
/** Turns the ImlProgram and its intermediate values into a final VM program ready for execution.
The finalization is done according to a grammar's point of view, as this is one of Tokays core features.
This closure algorithm runs until no more changes on any parselet configurations regarding left-recursive
and nullable parselet detection occurs.
*/
pub fn compile(mut self) -> Result<Program, Vec<Error>> {
log::info!("compiling {}", self.main);
let mut finalize = HashSet::new(); // list of consuming parselets required to be finalized
// Loop until end of statics is reached
let mut idx = 0;
// self.statics grows inside of this while loop, therefore this condition.
while idx < self.statics.len() {
log::trace!(
"idx = {: >3}, statics.len() = {: >3}",
idx,
self.statics.len()
);
// Pick only intermediate parselets, other static values are directly moved
let parselet = match self.statics.get_index_mut(idx).unwrap() {
(_, Some(_)) => unreachable!(), // may not exist!
(ImlValue::Parselet(parselet), None) => parselet.clone(),
_ => {
idx += 1;
continue;
}
};
log::trace!("idx = {: >3}, parselet = {:?}", idx, parselet.borrow().name);
// Memoize parselets required to be finalized (needs a general rework later...)
if parselet.borrow().model.borrow().is_consuming {
//fixme...
finalize.insert(parselet.clone());
}
// Compile VM parselet from intermediate parselet
// println!("...compiling {} {:?}", idx, parselet.name);
*self.statics.get_index_mut(idx).unwrap().1 = Some(parselet.compile(&mut self, idx));
idx += 1;
}
// Stop on any raised error
if !self.errors.is_empty() {
return Err(self.errors);
}
// Finalize parselets
log::debug!("{} has {} parselets to finalize", self.main, finalize.len());
for (i, parselet) in finalize.iter().enumerate() {
log::trace!(" {: >3} => {:#?}", i, parselet);
}
let leftrec = self.finalize(finalize);
// Assemble all statics to be transferred into a Program
let statics: Vec<RefValue> = self
.statics
.into_iter()
.map(|(iml, parselet)| {
if let Some(mut parselet) = parselet {
if let ImlValue::Parselet(imlparselet) = iml {
parselet.consuming = leftrec
.get(&imlparselet)
.map_or(None, |leftrec| Some(*leftrec));
//println!("{:?} => {:?}", imlparselet.borrow().name, parselet.consuming);
}
RefValue::from(parselet)
} else {
iml.unwrap()
}
})
.collect();
log::debug!("{} has {} statics compiled", self.main, statics.len());
for (i, value) in statics.iter().enumerate() {
log::trace!(" {: >3} : {:#?}", i, value);
}
Ok(Program::new(statics))
}
/** Internal function to finalize a program on a grammar's point of view.
The finalization performs a closure algorithm on every parselet to detect
- nullable parselets
- left-recursive parselets
until no more changes occur.
It can only be run on a previously compiled program without any unresolved usages.
*/
fn finalize(&mut self, parselets: HashSet<ImlRefParselet>) -> HashMap<ImlRefParselet, bool> {
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
struct Consumable {
leftrec: bool,
nullable: bool,
}
// Finalize ImlValue
fn finalize_value(
value: &ImlValue,
current: &ImlRefParselet,
visited: &mut IndexSet<ImlRefParselet>,
configs: &mut HashMap<ImlRefParselet, Consumable>,
) -> Option<Consumable> {
match value {
ImlValue::Shared(value) => {
finalize_value(&*value.borrow(), current, visited, configs)
}
ImlValue::SelfToken => Some(Consumable {
leftrec: true,
nullable: false,
}),
ImlValue::Parselet(parselet) => {
// Try to derive the parselet with current constants
let derived = parselet.derive(current).unwrap();
// The derived parselet's original must be in the configs!
let parselet = configs.get_key_value(&derived).unwrap().0.clone();
finalize_parselet(&parselet, visited, configs)
}
ImlValue::Value(callee) => {
if callee.is_consuming() {
//println!("{:?} called, which is nullable={:?}", callee, callee.is_nullable());
Some(Consumable {
leftrec: false,
nullable: callee.is_nullable(),
})
} else {
None
}
}
ImlValue::Generic { name, .. } => {
// fixme: Is this still relevant???
finalize_value(
current.borrow().generics[name].as_ref().unwrap(),
current,
visited,
configs,
)
}
_ => None,
}
}
// Finalize ImlOp
fn finalize_op(
op: &ImlOp,
current: &ImlRefParselet,
visited: &mut IndexSet<ImlRefParselet>,
configs: &mut HashMap<ImlRefParselet, Consumable>,
) -> Option<Consumable> {
match op {
ImlOp::Call { target, .. } => finalize_value(target, current, visited, configs),
ImlOp::Alt { alts } => {
let mut leftrec = false;
let mut nullable = false;
let mut consumes = false;
for alt in alts {
if let Some(consumable) = finalize_op(alt, current, visited, configs) {
leftrec |= consumable.leftrec;
nullable |= consumable.nullable;
consumes = true;
}
}
if consumes {
Some(Consumable { leftrec, nullable })
} else {
None
}
}
ImlOp::Seq { seq, .. } => {
let mut leftrec = false;
let mut nullable = true;
let mut consumes = false;
for item in seq {
if !nullable {
break;
}
if let Some(consumable) = finalize_op(item, current, visited, configs) {
leftrec |= consumable.leftrec;
nullable = consumable.nullable;
consumes = true;
}
}
if consumes {
Some(Consumable { leftrec, nullable })
} else {
None
}
}
ImlOp::If { then, else_, .. } => {
let then = finalize_op(then, current, visited, configs);
if let Some(else_) = finalize_op(else_, current, visited, configs) {
if let Some(then) = then {
Some(Consumable {
leftrec: then.leftrec || else_.leftrec,
nullable: then.nullable || else_.nullable,
})
} else {
Some(else_)
}
} else {
then
}
}
ImlOp::Loop {
initial,
condition,
body,
..
} => {
let mut ret: Option<Consumable> = None;
for part in [initial, condition, body] {
let part = finalize_op(part, current, visited, configs);
if let Some(part) = part {
ret = if let Some(ret) = ret {
Some(Consumable {
leftrec: ret.leftrec || part.leftrec,
nullable: ret.nullable || part.nullable,
})
} else {
Some(part)
}
}
}
ret
}
// default case
_ => None,
}
}
// Finalize ImlRefParselet
fn finalize_parselet(
current: &ImlRefParselet,
visited: &mut IndexSet<ImlRefParselet>,
configs: &mut HashMap<ImlRefParselet, Consumable>,
) -> Option<Consumable> {
// ... only if it's generally flagged to be consuming.
let parselet = current.borrow();
let model = parselet.model.borrow();
if !model.is_consuming {
return None;
}
//println!("- {}{}", ".".repeat(visited.len()), current);
if let Some(idx) = visited.get_index_of(current) {
// When in visited, this is a recursion
Some(Consumable {
// If the idx is 0, current is the seeked parselet, so it is left-recursive
leftrec: if idx == 0 && !current.borrow().is_generated {
configs.get_mut(current).unwrap().leftrec = true;
true
} else {
false
},
nullable: configs[current].nullable,
})
} else {
// If not already visited, add and recurse.
visited.insert(current.clone());
for part in [&model.begin, &model.body, &model.end] {
finalize_op(part, current, visited, configs);
}
visited.shift_remove(current);
Some(Consumable {
leftrec: false,
nullable: configs[current].nullable,
})
}
}
// Now, start the closure algorithm with left-recursive and nullable configurations for all parselets
// put into the finalize list.
let mut changes = true;
let mut configs = parselets
.iter()
.map(|k| {
(
k.clone(),
Consumable {
leftrec: false,
nullable: false,
},
)
})
.collect();
while changes {
changes = false;
for parselet in &parselets {
let result = finalize_parselet(parselet, &mut IndexSet::new(), &mut configs);
changes = result > configs.get(parselet).cloned();
}
}
log::debug!(
"{} has {} parselets finalized",
self.statics.keys()[0],
parselets.len()
);
for parselet in &parselets {
log::trace!(
" {} consuming={:?}",
parselet.borrow().name.as_deref().unwrap_or("(unnamed)"),
configs[&parselet]
);
}
configs.into_iter().map(|(k, v)| (k, v.leftrec)).collect()
}
}