brainstem 0.1.0

A Brainfuck compiler and interpreter library, with a BrainStem frontend 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
use anyhow::{Context as AnyhowContext, Result, anyhow, bail};
use std::cell::RefCell;
use std::collections::hash_map::Entry;
use std::collections::{HashMap, HashSet};
use std::fmt::{Debug, Error, Formatter};
use std::rc::{Rc, Weak};

#[derive(Debug, Clone, Copy)]
pub enum StackFrameOffset {
    Above,
    Below,
}

pub trait VariableLike: Debug {
    fn address(&self) -> isize;
    fn stackframe(&self) -> Option<StackFrameOffset> {
        None
    }
}

pub struct Variable {
    name: String,
    is_temp: bool,
    address: isize,
    size: usize,
    // Store a weak reference to avoid a reference cycle.
    context: Weak<RefCell<Context>>,
}

impl Variable {
    pub fn is_temp(&self) -> bool {
        self.is_temp
    }
}

impl Debug for Variable {
    fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), Error> {
        if self.size == 1 {
            write!(fmt, "{}{{{}}}", self.name, self.address)
        } else {
            write!(fmt, "{}{{{};{}}}", self.name, self.address, self.size)
        }
    }
}

impl VariableLike for Variable {
    fn address(&self) -> isize {
        self.address
    }
}

impl VariableLike for Rc<Variable> {
    fn address(&self) -> isize {
        self.address
    }
}

impl Drop for Variable {
    fn drop(&mut self) {
        // Attempt to upgrade the weak reference.
        if let Some(ctx) = self.context.upgrade() {
            // Deregister self from the context.
            ctx.borrow_mut()
                .deregister(&self.name, self.address, self.size)
                .unwrap();
        }
    }
}

pub trait VariableExt {
    fn successor(&self, offset: isize) -> Successor;
    fn size(&self) -> usize;
    fn in_stackframe_above(&self) -> VariableInAdjacentStackFrame;
    fn in_stackframe_below(&self) -> VariableInAdjacentStackFrame;
}

impl VariableExt for Rc<Variable> {
    fn successor(&self, offset: isize) -> Successor {
        Successor {
            original: self.clone(),
            offset,
        }
    }
    fn in_stackframe_above(&self) -> VariableInAdjacentStackFrame {
        VariableInAdjacentStackFrame {
            original: self.clone(),
            stackframe: StackFrameOffset::Above,
        }
    }
    fn in_stackframe_below(&self) -> VariableInAdjacentStackFrame {
        VariableInAdjacentStackFrame {
            original: self.clone(),
            stackframe: StackFrameOffset::Below,
        }
    }
    fn size(&self) -> usize {
        self.size
    }
}

pub struct Successor {
    original: Rc<Variable>,
    offset: isize,
}

impl VariableExt for Successor {
    fn successor(&self, offset: isize) -> Successor {
        Successor {
            original: self.original.clone(),
            offset: self.offset + offset,
        }
    }
    fn in_stackframe_above(&self) -> VariableInAdjacentStackFrame {
        VariableInAdjacentStackFrame {
            original: self.original.clone(),
            stackframe: StackFrameOffset::Above,
        }
    }
    fn in_stackframe_below(&self) -> VariableInAdjacentStackFrame {
        VariableInAdjacentStackFrame {
            original: self.original.clone(),
            stackframe: StackFrameOffset::Below,
        }
    }
    fn size(&self) -> usize {
        self.original.size
    }
}

impl Debug for Successor {
    fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), Error> {
        let neg = if self.offset < 0 { "neg" } else { "" };
        write!(
            fmt,
            "Successor({:?}; {}{})",
            self.original,
            neg,
            self.offset.abs()
        )
    }
}

impl VariableLike for Successor {
    fn address(&self) -> isize {
        self.original.address + self.offset
    }
}

pub struct VariableInAdjacentStackFrame {
    original: Rc<dyn VariableLike>,
    stackframe: StackFrameOffset,
}

impl Debug for VariableInAdjacentStackFrame {
    fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), Error> {
        write!(
            fmt,
            "VariableInAdjacentStackFrame({:?}; {:?})",
            self.original, self.stackframe
        )
    }
}

impl VariableLike for VariableInAdjacentStackFrame {
    fn address(&self) -> isize {
        self.original.address()
    }
    fn stackframe(&self) -> Option<StackFrameOffset> {
        Some(self.stackframe)
    }
}

pub trait AsVariableLikeRef<'a> {
    // Associated type: The concrete type T that implements VariableLike
    // We need this because copy is generic over T, not dyn VariableLike
    type Target: VariableLike + 'a;
    fn as_variable_like_ref(&'a self) -> &'a Self::Target;
}

// --- Implement the Helper Trait for Expected Input Types ---

// 1. Implement for Rc<Variable>
impl<'a> AsVariableLikeRef<'a> for Rc<Variable> {
    type Target = Variable; // The T for copy will be Variable
    fn as_variable_like_ref(&'a self) -> &'a Variable {
        // Dereference the Rc to get the underlying Variable
        self // Equivalent to self.as_ref() or &*self.deref()
    }
}

// 2. Implement for Variable itself
// This handles cases where you pass `&Variable`. The method call `var_ref.as_variable_like_ref()`
// will implicitly dereference var_ref (from &Variable to Variable) and call this impl.
impl<'a> AsVariableLikeRef<'a> for Variable {
    type Target = Variable; // The T for copy will be Variable
    fn as_variable_like_ref(&'a self) -> &'a Variable {
        // 'self' is already the &Variable we need
        self
    }
}

// 3. Implement for other VariableLike types (e.g., Successor) if needed
impl<'a> AsVariableLikeRef<'a> for Successor {
    type Target = Successor; // The T for copy will be Successor
    fn as_variable_like_ref(&'a self) -> &'a Successor {
        self
    }
}

impl<'a> AsVariableLikeRef<'a> for VariableInAdjacentStackFrame {
    type Target = VariableInAdjacentStackFrame;
    fn as_variable_like_ref(&'a self) -> &'a VariableInAdjacentStackFrame {
        self
    }
}

#[derive(Debug)]
pub struct Context {
    variables: HashMap<String, Weak<Variable>>,
    used_addresses: HashSet<isize>,
    temp_count: usize,
    scoped_variable_store: Vec<Vec<Rc<Variable>>>,
}

impl Context {
    pub fn new() -> Rc<RefCell<Self>> {
        Rc::new(RefCell::new(Self {
            variables: HashMap::new(),
            used_addresses: HashSet::new(),
            temp_count: 0,
            scoped_variable_store: vec![Vec::new()],
        }))
    }

    pub fn get_variable(&self, name: &str) -> Result<Rc<Variable>> {
        self.variables
            .get(name)
            .and_then(|weak_var| weak_var.upgrade())
            .with_context(|| format!("Variable {} not found", name))
    }

    fn deregister(&mut self, name: &str, address: isize, size: usize) -> Result<()> {
        for i in 0..size {
            self.used_addresses.remove(&(address + i as isize));
        }
        self.variables.remove(name);
        Ok(())
    }

    pub fn push_scope(&mut self) {
        self.scoped_variable_store.push(Vec::new());
    }

    pub fn pop_scope(&mut self) -> Result<()> {
        let scoped_vars = self.scoped_variable_store.pop();
        if scoped_vars.is_none() {
            return Err(anyhow!("No scope to pop"));
        }
        // We need to manually drop the variables in the current scope.
        // Otherwise they would try to deregister themselves when they go out of scope, while we still hold the borrow_mut.
        // This would fail, because they would also try to borrow_mut the context.
        for mut var in scoped_vars.unwrap() {
            self.deregister(&var.name, var.address, var.size)?;
            Rc::get_mut(&mut var).unwrap().context = Weak::new(); // Clear the context reference
        }
        Ok(())
    }

    fn add_impl(
        context: &Rc<RefCell<Self>>,
        name: &str,
        is_temp: bool,
        size: usize,
    ) -> Result<Rc<Variable>> {
        let weak_ctx = Rc::downgrade(context);
        let mut ctx = context.borrow_mut();
        let address = ctx.find_next_free(size);
        let v = match ctx.variables.entry(name.to_string()) {
            Entry::Occupied(_) => bail!("Variable {} already exists", name),
            Entry::Vacant(entry) => {
                let variable = Rc::new(Variable {
                    name: name.to_string(),
                    is_temp,
                    address,
                    size,
                    context: weak_ctx,
                });
                entry.insert(Rc::downgrade(&variable));
                for i in 0..size {
                    ctx.used_addresses.insert(variable.address + i as isize);
                }
                variable
            }
        };
        if !is_temp {
            ctx.scoped_variable_store
                .last_mut()
                .unwrap()
                .push(v.clone());
        }
        Ok(v)
    }

    fn add_temp_impl(context: &Rc<RefCell<Self>>, size: usize) -> Result<Rc<Variable>> {
        let name;
        {
            let temp_count = &mut context.borrow_mut().temp_count;
            name = format!("__temp{}", temp_count);
            *temp_count += 1;
        }
        Self::add_impl(context, &name, true, size)
    }

    fn find_next_free(&self, size: usize) -> isize {
        let top_address = self.used_addresses.iter().max().map_or(0, |&x| x + 1);
        let mut address = 0;
        while address < top_address {
            let mut is_free = true;
            for i in 0..size {
                if self.used_addresses.contains(&(address + i as isize)) {
                    is_free = false;
                    address += 1 + i as isize;
                    break;
                }
            }
            if is_free {
                return address;
            }
        }
        top_address
    }

    pub fn next_adress_after_top(&self) -> usize {
        self.used_addresses
            .iter()
            .filter(|&&x| x >= 0)
            .max()
            .map_or(0, |&x| x as usize + 1)
    }

    // TODO: This should also work with &str.
    pub fn get_variable_names(&self) -> Vec<String> {
        self.variables.keys().cloned().collect::<Vec<_>>()
    }
}

pub trait ContextExt {
    fn add_with_size(&self, name: &str, size: usize) -> Result<Rc<Variable>>;
    fn add(&self, name: &str) -> Result<Rc<Variable>>;
    fn add_temp(&self) -> Result<Rc<Variable>>;
    fn add_temp_with_size(&self, size: usize) -> Result<Rc<Variable>>;
}

impl ContextExt for Rc<RefCell<Context>> {
    fn add_with_size(&self, name: &str, size: usize) -> Result<Rc<Variable>> {
        Context::add_impl(self, name, false, size)
    }
    fn add(&self, name: &str) -> Result<Rc<Variable>> {
        Context::add_impl(self, name, false, 1)
    }
    fn add_temp(&self) -> Result<Rc<Variable>> {
        Context::add_temp_impl(self, 1)
    }
    fn add_temp_with_size(&self, size: usize) -> Result<Rc<Variable>> {
        Context::add_temp_impl(self, size)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_add() {
        let ctx = Context::new();
        let var1 = ctx.add_with_size("var1", 4).unwrap();
        let var2 = ctx.add_with_size("var2", 2).unwrap();

        assert_eq!(var1.name, "var1");
        assert_eq!(var1.size, 4);
        assert_eq!(var1.address, 0);

        assert_eq!(var2.name, "var2");
        assert_eq!(var2.size, 2);
        assert_eq!(var2.address, 4);
    }

    #[test]
    fn test_add_collision() {
        let ctx = Context::new();
        let _var1 = ctx.add_with_size("foo", 4).unwrap();
        assert!(ctx.add_with_size("foo", 2).is_err());
    }

    #[test]
    fn test_add_after_drop() {
        let ctx = Context::new();
        let _v1 = ctx.add_with_size("var1", 4);
        {
            let _v2 = ctx.add_temp();
            assert_eq!(ctx.add_temp().unwrap().address, 5); // Address after var2
        }
        // var2 goes out of scope
        assert_eq!(ctx.add_temp().unwrap().address, 4); // Address after var1
    }
}