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
use crate::builtin::*;
use crate::compiler_info::CodeArea;
use crate::compiler_types::*;
use crate::globals::Globals;
use crate::levelstring::*;
use crate::value::{value_equality, Value};
use crate::value_storage::{clone_value, store_val_m, StoredValue};
//use std::boxed::Box;
use std::collections::HashMap;
use internment::Intern;
use crate::compiler::NULL_STORAGE;
#[derive(Debug, Clone, PartialEq)]
pub struct Context {
// broken doesn't mean something is wrong with it, it just means
// a break statement ( or similar) has been used :)
pub broken: Option<(BreakType, CodeArea)>,
pub start_group: Group,
pub func_id: FnIdPtr,
pub fn_context_change_stack: Vec<CodeArea>,
variables: HashMap<Intern<String>, Vec<(StoredValue, i16)>>,
pub return_value: StoredValue,
pub return_value2: StoredValue,
pub root_context_ptr: *mut FullContext,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum BreakType {
// used for return statements
Macro(Option<StoredValue>, bool),
// used for Break statements
Loop,
// used for continue statements
ContinueLoop,
// used for switch cases
Switch(StoredValue),
// used for contexts
}
#[derive(Debug, Clone)]
pub enum FullContext {
Single(Context),
Split(Box<FullContext>, Box<FullContext>),
}
impl FullContext {
pub fn new() -> Self {
let mut new = FullContext::Single(Context::new());
new.inner().root_context_ptr = &mut new;
new
}
pub fn inner(&mut self) -> &mut Context {
match self {
Self::Single(c) => c,
_ => unreachable!("Called 'inner' on a split value"),
}
}
pub fn inner_value(&mut self) -> (&mut Context, StoredValue) {
let context = self.inner();
let val = context.return_value;
(context, val)
}
pub fn stack(list: &mut impl Iterator<Item = Self>) -> Option<Self> {
let first = list.next()?;
match Self::stack(list) {
Some(second) => Some(FullContext::Split(first.into(), second.into())),
None => Some(first),
}
}
pub fn enter_scope(&mut self) {
for context in self.with_breaks() {
for stack in context.inner().variables.values_mut() {
for (_, layers) in stack.iter_mut() {
*layers += 1;
}
}
}
}
pub fn exit_scope(&mut self) {
for context in self.with_breaks() {
for stack in context.inner().variables.values_mut() {
for (_, layers) in stack.iter_mut() {
*layers -= 1;
}
}
for stack in context.inner().variables.values_mut() {
if stack.last().unwrap().1 < 0 {
stack.pop();
}
}
context.inner().variables.retain(|_, s| !s.is_empty())
}
// let mut removed = HashSet::new();
// for context in self.with_breaks() {
// for (_, layers) in context.inner().variables.values_mut() {
// *layers -= 1;
// }
// removed.extend(context.inner().variables.values().filter_map(|(v, l)| {
// if *l < 0 {
// Some(v)
// } else {
// None
// }
// }));
// context.inner().variables.retain(|_, (_, l)| *l >= 0)
// }
// let mut all_removed = HashSet::new();
// for v in removed {
// all_removed.extend(get_all_ptrs_used(v, globals));
// }
// all_removed
}
pub fn reset_return_vals(&mut self) {
for c in self.with_breaks() {
let c = c.inner();
(*c).return_value = NULL_STORAGE;
(*c).return_value2 = NULL_STORAGE;
}
}
pub fn set_variable_and_clone(
&mut self,
name: Intern<String>,
val: StoredValue,
layer: i16,
constant: bool,
globals: &mut Globals,
area: CodeArea,
) {
for c in self.iter() {
// reset all variables per context
let fn_context = c.inner().start_group;
(*c.inner()).new_variable(
name,
clone_value(val, globals, fn_context, constant, area),
layer,
);
}
}
pub fn set_variable_and_store(
&mut self,
name: Intern<String>,
val: Value,
layer: i16,
constant: bool,
globals: &mut Globals,
area: CodeArea,
) {
for c in self.iter() {
// reset all variables per context
let fn_context = c.inner().start_group;
(*c.inner()).new_variable(
name,
store_val_m(val.clone(), globals, fn_context, constant, area),
layer,
);
}
}
pub fn disable_breaks(&mut self, breaktype: BreakType) {
for fc in self.with_breaks() {
if let Some((b, _)) = &mut fc.inner().broken {
if std::mem::discriminant(b) == std::mem::discriminant(&breaktype) {
(*fc.inner()).broken = None;
}
}
}
}
pub fn with_breaks(&mut self) -> ContextIterWithBreaks {
ContextIterWithBreaks::new(self)
}
pub fn iter(&mut self) -> ContextIter {
ContextIter::new(self)
}
}
/// Iterator type for a binary tree.
/// This is a generator that progresses through an in-order traversal.
pub struct ContextIter<'a> {
right_nodes: Vec<&'a mut FullContext>,
current_node: Option<&'a mut FullContext>,
}
pub struct ContextIterWithBreaks<'a> {
right_nodes: Vec<&'a mut FullContext>,
current_node: Option<&'a mut FullContext>,
}
impl<'a> ContextIter<'a> {
fn new(node: &'a mut FullContext) -> ContextIter<'a> {
let mut iter = ContextIter {
right_nodes: vec![],
current_node: None,
};
iter.add_left_subtree(node);
iter
}
/// Consume a binary tree node, traversing its left subtree and
/// adding all branches to the right to the `right_nodes` field
/// while setting the current node to the left-most child.
fn add_left_subtree(&mut self, mut node: &'a mut FullContext) {
loop {
match node {
FullContext::Split(left, right) => {
self.right_nodes.push(&mut **right);
node = &mut **left;
}
val @ FullContext::Single(_) => {
self.current_node = Some(val);
break;
}
}
}
}
}
impl<'a> ContextIterWithBreaks<'a> {
fn new(node: &'a mut FullContext) -> ContextIterWithBreaks<'a> {
let mut iter = ContextIterWithBreaks {
right_nodes: vec![],
current_node: None,
};
iter.add_left_subtree(node);
iter
}
/// Consume a binary tree node, traversing its left subtree and
/// adding all branches to the right to the `right_nodes` field
/// while setting the current node to the left-most child.
fn add_left_subtree(&mut self, mut node: &'a mut FullContext) {
loop {
match node {
FullContext::Split(left, right) => {
self.right_nodes.push(&mut **right);
node = &mut **left;
}
val @ FullContext::Single(_) => {
self.current_node = Some(val);
break;
}
}
}
}
}
impl<'a> Iterator for ContextIter<'a> {
type Item = &'a mut FullContext;
fn next(&mut self) -> Option<Self::Item> {
// Get the item we're going to return.
let result = self.current_node.take();
// Now add the next left subtree
// (this is the "recursive call")
if let Some(node) = self.right_nodes.pop() {
self.add_left_subtree(node);
}
match result {
Some(c) => {
if c.inner().broken.is_some() {
self.next()
} else {
Some(c)
}
}
None => None,
}
}
}
impl<'a> Iterator for ContextIterWithBreaks<'a> {
type Item = &'a mut FullContext;
fn next(&mut self) -> Option<Self::Item> {
// Get the item we're going to return.
let result = self.current_node.take();
// Now add the next left subtree
// (this is the "recursive call")
if let Some(node) = self.right_nodes.pop() {
self.add_left_subtree(node);
}
result
}
}
impl Context {
fn new() -> Context {
Context {
start_group: Group::new(0),
//spawn_triggered: false,
variables: HashMap::new(),
//return_val: Box::new(Value::Null),
//self_val: None,
func_id: 0,
broken: None,
fn_context_change_stack: Vec::new(),
return_value: NULL_STORAGE,
return_value2: NULL_STORAGE,
root_context_ptr: std::ptr::null_mut(),
}
}
pub fn next_fn_id(&mut self, globals: &mut Globals) {
(*globals).func_ids.push(FunctionId {
parent: Some(self.func_id),
obj_list: Vec::new(),
width: None,
});
self.func_id = globals.func_ids.len() - 1;
}
pub fn get_variable(&self, name: Intern<String>) -> Option<StoredValue> {
self.variables.get(&name).map(|a| a.last().unwrap().0)
}
pub fn new_variable(&mut self, name: Intern<String>, val: StoredValue, layer: i16) {
match self.variables.get_mut(&name) {
Some(stack) => stack.push((val, layer)),
None => {
self.variables.insert(name, vec![(val, layer)]);
}
}
}
pub fn get_variables(&self) -> &HashMap<Intern<String>, Vec<(StoredValue, i16)>> {
&self.variables
}
pub fn set_all_variables(&mut self, vars: HashMap<Intern<String>, Vec<(StoredValue, i16)>>) {
(*self).variables = vars;
}
}
//will merge one set of context, returning false if no mergable contexts were found
pub fn merge_contexts(contexts: &mut Vec<Context>, globals: &mut Globals) -> bool {
let mut mergable_ind = Vec::<usize>::new();
let mut ref_c = 0;
loop {
if ref_c >= contexts.len() {
return false;
}
for (i, c) in contexts.iter().enumerate() {
if i == ref_c {
continue;
}
let ref_c = &contexts[ref_c];
if (ref_c.broken == None) != (c.broken == None) {
continue;
}
let mut not_eq = false;
//check variables are equal
for (key, stack) in &c.variables {
for (i, (val, _)) in stack.iter().enumerate() {
if !value_equality(ref_c.variables[key][i].0, *val, globals) {
not_eq = true;
break;
}
}
}
if not_eq {
continue;
}
//check implementations are equal
// for (key, val) in &c.implementations {
// for (key2, val) in val {
// if globals.stored_values[ref_c.implementations[key][key2]] != globals.stored_values[*val] {
// not_eq = true;
// break;
// }
// }
// }
// if not_eq {
// continue;
// }
//everything is equal, add to list
mergable_ind.push(i);
}
if mergable_ind.is_empty() {
ref_c += 1;
} else {
break;
}
}
let new_group = Group::next_free(&mut globals.closed_groups);
//add spawn triggers
let mut add_spawn_trigger = |context: &Context| {
let mut params = HashMap::new();
params.insert(51, ObjParam::Group(new_group));
params.insert(1, ObjParam::Number(1268.0));
(*globals).trigger_order += 1;
(*globals).func_ids[context.func_id].obj_list.push((
GdObj {
params,
..context_trigger(context, &mut globals.uid_counter)
}
.context_parameters(context),
globals.trigger_order,
))
};
add_spawn_trigger(&contexts[ref_c]);
for i in mergable_ind.iter() {
add_spawn_trigger(&contexts[*i])
}
(*contexts)[ref_c].start_group = new_group;
(*contexts)[ref_c].next_fn_id(globals);
for i in mergable_ind.iter().rev() {
(*contexts).swap_remove(*i);
}
true
}
//will merge one set of context, returning false if no mergable contexts were found