~dcreager/swanson-lang

ref: 8ab6a4cd0171e40ef1659d68c4dd7d02bb7e363f swanson-lang/rust/swanson-binary/src/lib.rs -rw-r--r-- 23.2 KiB
8ab6a4cdDouglas Creager Add remaining unsigned arithmetic operators 3 months ago
                                                                                
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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
// -*- coding: utf-8 -*-
// ------------------------------------------------------------------------------------------------
// Copyright © 2021, Swanson Project.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
// in compliance with the License.  You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied.  See the License for the specific language governing permissions and
// limitations under the License.
// ------------------------------------------------------------------------------------------------

use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::collections::HashMap;

use bytes::Buf;
use bytes::BufMut;
use bytes::Bytes;
use bytes::BytesMut;
use swanson_ast::s0;
use swanson_ast::Location;
use swanson_ast::Name;
use swanson_ast::SourceFile;
use swanson_ast::Span;
use swanson_ast::Spanned;
use thiserror::Error;

/// Indicates that an error occurred while trying to parse the content of an SL library.
#[derive(Clone, Debug, Eq, Error, PartialEq)]
#[error("invalid SL file")]
pub struct ParseError;

#[derive(Clone, Eq, PartialEq)]
pub struct SLLibrary {
    modules: BTreeMap<Spanned<Name>, s0::Module>,
}

impl SLLibrary {
    pub fn new() -> SLLibrary {
        SLLibrary {
            modules: BTreeMap::new(),
        }
    }

    pub fn add_module(&mut self, module: s0::Module) {
        self.modules.insert(module.name().clone(), module);
    }

    pub fn from_sl_buf(buf: Bytes) -> Result<SLLibrary, ParseError> {
        let mut parser = Parser::new(buf);
        let modules = parser.parse_file()?;
        Ok(SLLibrary { modules })
    }

    pub fn to_sl_buf(&self) -> BytesMut {
        Writer::new().write_file(self)
    }
}

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

    use itertools::Itertools;

    #[test]
    fn can_roundtrip_sl_files() {
        let modules = vec![
            s0!(r#"
                module empty {
                  $load:
                  containing ()
                  receiving ($loaded)
                  {
                    $module = closure containing () -> module;
                    -> $loaded;
                  }
                  module:
                  containing ()
                  ::drop receiving ($return)
                  {
                    -> $return;
                  }
                }
            "#),
            s0!(r#"
                module noop {
                  $load:
                  containing ()
                  receiving ($loaded)
                  {
                    $module = closure containing () -> main;
                    -> $loaded;
                  }
                  main:
                  containing ()
                  receiving ($finish)
                  {
                    -> $finish succeed;
                  }
                }
            "#),
            s0!(r#"
                module fslist.can_create_empty_list {
                  $load:
                    containing ()
                    receiving ($loaded, ds.fslist)
                  {
                    $module = closure containing (ds.fslist) -> main;
                    -> $loaded;
                  }
                  main:
                    containing (ds.fslist)
                    receiving ($finish)
                  {
                    $return = closure containing ($finish) -> main@1;
                    -> ds.fslist nil.new;
                  }
                  main@1:
                    containing ($finish)
                    receiving ($_, $0)
                  {
                    ds.fslist = rename $_;
                    list = rename $0;
                    $return = closure containing ($finish, list) -> main@2;
                    -> ds.fslist drop;
                  }
                  main@2:
                    containing ($finish, list)
                    receiving ()
                  {
                    $return = closure containing ($finish) -> main@3;
                    -> list drop;
                  }
                  main@3:
                    containing ($finish)
                    receiving ()
                  {
                    -> $finish succeed;
                  }
                }
            "#),
            s0!(r#"
                module control {
                  $load:
                    containing ()
                    receiving ($loaded)
                  {
                    $module = closure containing () -> module;
                    -> $loaded;
                  }
                  module:
                    containing ()
                    ::clone receiving ($return)
                    {
                      $_ = closure containing () -> module;
                      $0 = closure containing () -> module;
                      -> $return;
                    }
                    ::drop receiving ($return)
                    {
                      -> $return;
                    }
                    ::while receiving ($condition, $return)
                    {
                      loop = closure containing ($condition, $return) -> while.loop;
                      -> loop;
                    }
                  while.loop:
                    containing ($condition, $return)
                    receiving ()
                  {
                    $return = closure containing ($return) -> while.loop@1;
                    -> $condition;
                  }
                  while.loop@1:
                    containing ($return)
                    receiving ($0, $body)
                  {
                    $evaluate = closure containing ($body, $return) -> while.loop@2;
                    -> $0 evaluate;
                  }
                  while.loop@2:
                    containing ($body, $return)
                    ::true receiving ()
                    {
                      $return = closure containing ($return) -> while.loop@3;
                      -> $body iterate;
                    }
                    ::false receiving ()
                    {
                      -> $body finish;
                    }
                  while.loop@3:
                    containing ($return)
                    receiving ($condition)
                  {
                    loop = closure containing ($condition, $return) -> while.loop;
                    -> loop;
                  }
                }
            "#),
        ];

        for size in 0..=modules.len() {
            for combo in modules.iter().combinations(size) {
                let mut library = SLLibrary::new();
                for module in combo {
                    library.add_module(module.clone());
                }
                let sl_buf = library.to_sl_buf().freeze();
                let parsed = SLLibrary::from_sl_buf(sl_buf).expect("Could not parse SL file");
                assert!(library == parsed);
            }
        }
    }
}

//-------------------------------------------------------------------------------------------------
// Writing

struct Writer {
    buf: BytesMut,
    binaries: HashMap<Vec<u8>, u32>,
}

impl Writer {
    fn new() -> Writer {
        Writer {
            buf: BytesMut::new(),
            binaries: HashMap::new(),
        }
    }

    fn write_varint(&mut self, value: u32) {
        if value < (1 << 7) {
            // 1xxxxxxx
            self.buf.put_u8((value | 0x80) as u8);
        } else if value < (1 << 14) {
            // 01xxxxxx xxxxxxxx
            self.buf.put_u16((value | 0x4000) as u16);
        } else if value < (1 << 21) {
            // 001xxxxx xxxxxxxx xxxxxxxx
            let value = value | 0x200000;
            // my kingdom for put_u24
            self.buf.put_u8((value >> 16) as u8);
            self.buf.put_u16((value & 0xffff) as u16);
        } else if value < (1 << 28) {
            // 0001xxxx xxxxxxxx xxxxxxxx xxxxxxxx
            self.buf.put_u32(value | 0x10000000);
        } else {
            unreachable!();
        }
    }

    fn write_file(mut self, library: &SLLibrary) -> BytesMut {
        self.write_header();
        self.write_binaries(library);
        self.write_modules(library);
        self.buf
    }

    fn write_header(&mut self) {
        self.buf.put_u32(0x534C4942);
        self.buf.put_u32(1);
    }

    fn write_binaries(&mut self, library: &SLLibrary) {
        struct Binaries<'a>(BTreeSet<&'a [u8]>);
        let mut binaries = Binaries(BTreeSet::new());
        impl<'a> Binaries<'a> {
            fn add_name<'b: 'a>(&mut self, name: &'b Spanned<Name>) {
                self.0.insert(name.wrapped().as_bytes());
                self.0.insert(
                    name.annotation()
                        .source
                        .as_path()
                        .to_str()
                        .unwrap()
                        .as_bytes(),
                );
            }
        }

        for module in library.modules.values() {
            binaries.add_name(module.name());
            for block in module.blocks() {
                binaries.add_name(&block.name);
                for name in &block.containing {
                    binaries.add_name(&name);
                }
                for branch in &block.branches {
                    binaries.add_name(&branch.name);
                    for name in &branch.receiving {
                        binaries.add_name(name);
                    }
                    for stmt in &branch.statements {
                        match stmt {
                            s0::Statement::CreateAtom(stmt) => {
                                binaries.add_name(&stmt.dest);
                            }
                            s0::Statement::CreateClosure(stmt) => {
                                binaries.add_name(&stmt.dest);
                                binaries.add_name(&stmt.block_name);
                                for name in &stmt.close_over {
                                    binaries.add_name(name);
                                }
                            }
                            s0::Statement::CreateLiteral(stmt) => {
                                binaries.add_name(&stmt.dest);
                                binaries.0.insert(&stmt.value);
                            }
                            s0::Statement::Rename(stmt) => {
                                binaries.add_name(&stmt.dest);
                                binaries.add_name(&stmt.source);
                            }
                        }
                    }
                    binaries.add_name(&branch.invocation.target);
                    binaries.add_name(&branch.invocation.branch);
                }
            }
        }

        let binaries = binaries.0;
        self.buf.reserve(
            binaries.iter().map(|b| b.len()).sum::<usize>()
                + std::mem::size_of::<u32>() * (1 + binaries.len()),
        );
        self.write_varint(binaries.len() as u32);
        for (idx, binary) in binaries.iter().enumerate() {
            let content = binary.to_vec();
            self.write_varint(binary.len() as u32);
            self.buf.extend_from_slice(&content);
            self.binaries.insert(content, idx as u32);
        }
    }

    fn get_binary(&self, content: &[u8]) -> u32 {
        *self.binaries.get(content).unwrap()
    }

    fn write_name(&mut self, name: &Spanned<Name>) {
        let span = name.annotation();
        self.write_varint(self.get_binary(name.wrapped().as_bytes()));
        self.write_varint(self.get_binary(span.source.as_path().to_str().unwrap().as_bytes()));
        self.write_varint(span.start.line as u32);
        self.write_varint(span.start.column as u32);
        self.write_varint(span.end.line as u32);
        self.write_varint(span.end.column as u32);
    }

    fn write_modules(&mut self, library: &SLLibrary) {
        self.write_varint(library.modules.len() as u32);
        for module in library.modules.values() {
            self.write_module(module);
        }
    }

    fn write_module(&mut self, module: &s0::Module) {
        self.write_name(module.name());
        self.write_varint(module.blocks().len() as u32);
        for block in module.blocks() {
            self.write_block(block);
        }
    }

    fn write_block(&mut self, block: &s0::Block) {
        self.write_name(&block.name);
        self.write_varint(block.containing.len() as u32);
        for name in &block.containing {
            self.write_name(name);
        }
        self.write_varint(block.branches.len() as u32);
        for branch in &block.branches {
            self.write_branch(branch);
        }
    }

    fn write_branch(&mut self, branch: &s0::Branch) {
        self.write_name(&branch.name);
        self.write_varint(branch.receiving.len() as u32);
        for name in &branch.receiving {
            self.write_name(name);
        }
        for stmt in &branch.statements {
            self.write_statement(stmt);
        }
        self.write_invocation(&branch.invocation);
    }

    fn write_statement(&mut self, stmt: &s0::Statement) {
        match stmt {
            s0::Statement::CreateAtom(stmt) => self.write_create_atom(stmt),
            s0::Statement::CreateClosure(stmt) => self.write_create_closure(stmt),
            s0::Statement::CreateLiteral(stmt) => self.write_create_literal(stmt),
            s0::Statement::Rename(stmt) => self.write_rename(stmt),
        }
    }

    fn write_create_atom(&mut self, stmt: &s0::CreateAtom) {
        self.buf.put_u8(b'A');
        self.write_name(&stmt.dest);
    }

    fn write_create_closure(&mut self, stmt: &s0::CreateClosure) {
        self.buf.put_u8(b'C');
        self.write_name(&stmt.dest);
        self.write_varint(stmt.resolved as u32);
        self.write_varint(stmt.close_over.len() as u32);
        for name in &stmt.close_over {
            self.write_name(name);
        }
    }

    fn write_create_literal(&mut self, stmt: &s0::CreateLiteral) {
        self.buf.put_u8(b'L');
        self.write_name(&stmt.dest);
        self.write_varint(self.get_binary(&stmt.value));
    }

    fn write_rename(&mut self, stmt: &s0::Rename) {
        self.buf.put_u8(b'R');
        self.write_name(&stmt.dest);
        self.write_name(&stmt.source);
    }

    fn write_invocation(&mut self, invocation: &s0::Invocation) {
        self.buf.put_u8(b'I');
        self.write_name(&invocation.target);
        self.write_name(&invocation.branch);
    }
}

//-------------------------------------------------------------------------------------------------
// Reading

struct Parser {
    buf: Bytes,
    binaries: Vec<Vec<u8>>,
}

impl Parser {
    fn new(buf: Bytes) -> Parser {
        Parser {
            buf,
            binaries: Vec::new(),
        }
    }

    fn parse_varint(&mut self) -> Result<u32, ParseError> {
        if self.buf.remaining() < 1 {
            return Err(ParseError);
        }
        let a = self.buf.get_u8();
        match a.leading_zeros() {
            0 => {
                // 1xxxxxxx
                return Ok((a & 0x7f) as u32);
            }
            1 => {
                // 01xxxxxx xxxxxxxx
                if self.buf.remaining() < 1 {
                    return Err(ParseError);
                }
                let a = (a & 0x3f) as u32;
                let b = self.buf.get_u8() as u32;
                Ok(a << 8 | b)
            }
            2 => {
                // 001xxxxx xxxxxxxx xxxxxxxx
                if self.buf.remaining() < 2 {
                    return Err(ParseError);
                }
                let a = (a & 0x1f) as u32;
                let b = self.buf.get_u16() as u32;
                Ok(a << 16 | b)
            }
            3 => {
                // 0001xxxx xxxxxxxx xxxxxxxx xxxxxxxx
                if self.buf.remaining() < 3 {
                    return Err(ParseError);
                }
                let a = (a & 0x0f) as u32;
                let b = self.buf.get_u8() as u32;
                let c = self.buf.get_u16() as u32;
                Ok(a << 24 | b << 16 | c)
            }
            _ => Err(ParseError),
        }
    }

    fn parse_file(&mut self) -> Result<BTreeMap<Spanned<Name>, s0::Module>, ParseError> {
        self.parse_header()?;
        self.parse_binaries()?;
        self.parse_modules()
    }

    fn parse_header(&mut self) -> Result<(), ParseError> {
        if self.buf.remaining() < std::mem::size_of::<u32>() * 2 {
            return Err(ParseError);
        }

        let magic = self.buf.get_u32();
        if magic != 0x534C4942 {
            return Err(ParseError);
        }

        let version = self.buf.get_u32();
        if version != 1 {
            return Err(ParseError);
        }

        Ok(())
    }

    fn parse_binaries(&mut self) -> Result<(), ParseError> {
        let binaries_count = self.parse_varint()?;
        self.binaries.reserve(binaries_count as usize);
        for _ in 0..binaries_count {
            let name_length = self.parse_varint()? as usize;
            if self.buf.remaining() < name_length {
                return Err(ParseError);
            }
            let mut content = vec![0; name_length];
            self.buf.copy_to_slice(&mut content);
            self.binaries.push(content);
        }

        Ok(())
    }

    fn parse_name(&mut self) -> Result<Spanned<Name>, ParseError> {
        let content = self.parse_varint()? as usize;
        let source_file = self.parse_varint()? as usize;
        let start_line = self.parse_varint()? as usize;
        let start_column = self.parse_varint()? as usize;
        let end_line = self.parse_varint()? as usize;
        let end_column = self.parse_varint()? as usize;

        if content >= self.binaries.len() {
            return Err(ParseError);
        }
        let name = Name::from_vec(self.binaries[content].clone());

        if source_file >= self.binaries.len() {
            return Err(ParseError);
        }
        let source = match SourceFile::from_vec(self.binaries[source_file].clone()) {
            Ok(source_file) => source_file,
            Err(_) => return Err(ParseError),
        };

        let span = Span {
            source,
            start: Location {
                line: start_line,
                column: start_column,
            },
            end: Location {
                line: end_line,
                column: end_column,
            },
        };

        Ok(span.wrap(name))
    }

    fn parse_modules(&mut self) -> Result<BTreeMap<Spanned<Name>, s0::Module>, ParseError> {
        let module_count = self.parse_varint()? as usize;
        let mut modules = BTreeMap::new();
        for _ in 0..module_count {
            let module = self.parse_module()?;
            if modules.insert(module.name().clone(), module).is_some() {
                // Duplicate module
                return Err(ParseError);
            }
        }

        Ok(modules)
    }

    fn parse_module(&mut self) -> Result<s0::Module, ParseError> {
        let name = self.parse_name()?;
        let block_count = self.parse_varint()? as usize;
        let mut blocks = Vec::with_capacity(block_count);
        for _ in 0..block_count {
            blocks.push(self.parse_block()?);
        }

        // Fix up the blocks.  For each "create closure" statement that we encountered, we had the
        // _index_ of the closure's block, but we didn't yet know the _name_ of the block.  Now
        // that we've parsed all of the blocks, we do!
        let block_names = blocks
            .iter()
            .map(|block| block.name.clone())
            .collect::<Vec<_>>();
        for block in &mut blocks {
            for branch in &mut block.branches {
                for stmt in &mut branch.statements {
                    match stmt {
                        s0::Statement::CreateClosure(stmt) => {
                            stmt.block_name = block_names[stmt.resolved].clone();
                        }
                        _ => (),
                    }
                }
            }
        }

        Ok(s0::Module::new(name, blocks))
    }

    fn parse_block(&mut self) -> Result<s0::Block, ParseError> {
        let name = self.parse_name()?;
        let containing_count = self.parse_varint()? as usize;
        let mut containing = Vec::with_capacity(containing_count);
        for _ in 0..containing_count {
            containing.push(self.parse_name()?);
        }

        let branch_count = self.parse_varint()? as usize;
        let mut branches = Vec::with_capacity(branch_count);
        for _ in 0..branch_count {
            branches.push(self.parse_branch()?);
        }

        Ok(s0::Block {
            name,
            containing,
            branches,
        })
    }

    fn parse_branch(&mut self) -> Result<s0::Branch, ParseError> {
        let name = self.parse_name()?;
        let receiving_count = self.parse_varint()? as usize;
        let mut receiving = Vec::with_capacity(receiving_count);
        for _ in 0..receiving_count {
            receiving.push(self.parse_name()?);
        }

        let mut statements = Vec::new();
        while let Some(stmt) = self.parse_statement()? {
            statements.push(stmt);
        }

        let invocation = self.parse_invocation()?;

        Ok(s0::Branch {
            name,
            receiving,
            statements,
            invocation,
        })
    }

    fn parse_statement(&mut self) -> Result<Option<s0::Statement>, ParseError> {
        if self.buf.remaining() < std::mem::size_of::<u8>() {
            return Err(ParseError);
        }
        let code = self.buf.get_u8();
        match code {
            b'A' => Ok(Some(self.parse_create_atom()?)),
            b'C' => Ok(Some(self.parse_create_closure()?)),
            b'L' => Ok(Some(self.parse_create_literal()?)),
            b'R' => Ok(Some(self.parse_rename()?)),
            b'I' => Ok(None),
            _ => Err(ParseError),
        }
    }

    fn parse_create_atom(&mut self) -> Result<s0::Statement, ParseError> {
        let dest = self.parse_name()?;
        Ok(s0::CreateAtom { dest }.into())
    }

    fn parse_create_closure(&mut self) -> Result<s0::Statement, ParseError> {
        let dest = self.parse_name()?;
        let block_index = self.parse_varint()?;
        let close_over_count = self.parse_varint()?;
        let mut stmt = s0::CreateClosure {
            dest,
            close_over: Vec::with_capacity(close_over_count as usize),
            block_name: Span::wrap_default(Name::from("")), // we'll fix this up later
            resolved: block_index as usize,
        };
        for _ in 0..close_over_count {
            stmt.close_over.push(self.parse_name()?);
        }
        Ok(stmt.into())
    }

    fn parse_create_literal(&mut self) -> Result<s0::Statement, ParseError> {
        let dest = self.parse_name()?;
        let value = self.parse_varint()? as usize;
        let value = self.binaries[value].clone();
        Ok(s0::CreateLiteral { dest, value }.into())
    }

    fn parse_rename(&mut self) -> Result<s0::Statement, ParseError> {
        let dest = self.parse_name()?;
        let source = self.parse_name()?;
        Ok(s0::Rename { dest, source }.into())
    }

    fn parse_invocation(&mut self) -> Result<s0::Invocation, ParseError> {
        let target = self.parse_name()?;
        let branch = self.parse_name()?;
        Ok(s0::Invocation { target, branch })
    }
}