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
// STARK, a system for computer augmented design.
// Copyright (C) 2021 Matthew Rothlisberger

// STARK is licensed under the terms of the GNU Affero General Public
// License. See the top level LICENSE file for the license text.

// Find full copyright information in the top level COPYRIGHT file.

// <>

// src/sail/parser.rs

// Recursive descent parser which converts string slices into Sail
// objects, usually for evaluation.

// <>

use super::{core::*, memmgt, SlErrCode, SlHead};

use std::iter;
use std::str;

// struct Parser {
//     chars: iter::Peekable<str::Bytes<'static>>,
//     acc: Vec<u8>,
// }

/// Parses a textual Sail expression into a structure of Sail objects
pub fn parse(
    reg: *mut memmgt::Region,
    tbl: *mut SlHead,
    code: &str,
) -> Result<*mut SlHead, SlErrCode> {
    // Accumulator for collecting string values
    let mut acc: Vec<u8> = Vec::new();
    let mut chars = code.bytes().peekable();

    let val = read_value(&mut chars, &mut acc, reg, tbl)?;

    Ok(val)
}

// pub fn parse_bytes(tbl: *mut SlHead, code: &[u8]) -> Result<*mut SlHead, SlErrCode> {
//     let mut acc: Vec<u8> = Vec::new();
//     let mut chars = code.iter().peekable();

//     read_value(&mut chars, &mut acc, tbl, false)
// }

/// Returns the head of a Sail object structure representing a single
/// item parsed from the input stream
///
/// This is a recursive descent parser; the appropriate reader can
/// almost always be deduced from the first character
fn read_value(
    chars: &mut iter::Peekable<str::Bytes>,
    acc: &mut Vec<u8>,
    reg: *mut memmgt::Region,
    tbl: *mut SlHead,
) -> Result<*mut SlHead, SlErrCode> {
    let value;

    let mut c = *(chars.peek().ok_or(SlErrCode::ParseUnexpectedEnd)?);
    while c.is_ascii_whitespace() || c == b';' {
        if c == b';' {
            while *(chars.peek().ok_or(SlErrCode::ParseUnexpectedEnd)?) != b'\n' {
                chars.next();
            }
        }
        chars.next();
        c = *(chars.peek().ok_or(SlErrCode::ParseUnexpectedEnd)?);
    }

    match c {
        b'\'' => {
            chars.next();
            value = read_quote(chars, acc, reg, tbl)?;
        }
        b'(' => {
            chars.next();
            value = read_list(chars, acc, reg, tbl)?;
        }
        b'[' => {
            chars.next();
            value = read_vec(chars, acc, reg, tbl)?;
        }
        b'{' => {
            chars.next();
            value = read_map(chars, acc, reg, tbl)?;
        }
        b':' => {
            chars.next();
            value = read_spec_sym(chars, acc, reg, tbl, SymbolMode::Keyword)?;
            acc.clear();
        }
        b'$' => {
            chars.next();
            value = read_spec_sym(chars, acc, reg, tbl, SymbolMode::Type)?;
            acc.clear();
        }
        b'"' => {
            chars.next();
            value = read_string(chars, acc, reg, tbl)?;
            acc.clear();
        }
        b'#' => {
            chars.next();
            value = read_special(chars, acc, reg, tbl)?;
            acc.clear();
        }
        b'+' | b'-' => {
            acc.push(chars.next().unwrap());
            if chars
                .peek()
                .ok_or(SlErrCode::ParseUnexpectedEnd)?
                .is_ascii_digit()
            {
                value = read_number(chars, acc, reg, tbl)?;
            } else {
                value = read_symbol(chars, acc, reg, tbl)?;
            }
            acc.clear();
        }
        b'*' | b'/' | b'<' | b'=' | b'>' | b'_' => {
            value = read_symbol(chars, acc, reg, tbl)?;
            acc.clear();
        }
        _ if c.is_ascii_alphabetic() => {
            value = read_symbol(chars, acc, reg, tbl)?;
            acc.clear();
        }
        _ if c.is_ascii_digit() => {
            value = read_number(chars, acc, reg, tbl)?;
            acc.clear();
        }
        _ => {
            return Err(SlErrCode::ParseInvalidChar);
        }
    }
    Ok(value)
}

/// Reads a quoted expression off the input stream, into the
/// appropriate object structure
fn read_quote(
    chars: &mut iter::Peekable<str::Bytes>,
    acc: &mut Vec<u8>,
    reg: *mut memmgt::Region,
    tbl: *mut SlHead,
) -> Result<*mut SlHead, SlErrCode> {
    let start = sym_init(reg, super::SP_QUOTE.0);
    let head = ref_init(reg, start);

    let end = read_value(chars, acc, reg, tbl)?;
    set_next_list_elt(start, end);

    Ok(head)
}

/// Reads a list of values from the input stream and creates a
/// corresponding list of Sail objects
fn read_list(
    chars: &mut iter::Peekable<str::Bytes>,
    acc: &mut Vec<u8>,
    reg: *mut memmgt::Region,
    tbl: *mut SlHead,
) -> Result<*mut SlHead, SlErrCode> {
    let head = ref_make(reg);

    let mut c = *(chars.peek().ok_or(SlErrCode::ParseUnexpectedEnd)?);
    if c == b')' {
        chars.next();
        return Ok(head);
    }

    let mut count = 0;
    let mut tail = head;

    while c != b')' {
        match c {
            b';' => while chars.next().unwrap_or(b'\n') != b'\n' {},
            _ if c.is_ascii_whitespace() => {
                chars.next();
            }
            _ => {
                // append to the list tail
                tail = {
                    let next = read_value(chars, acc, reg, tbl)?;
                    if count < 1 {
                        ref_set(tail, next)
                    } else {
                        set_next_list_elt(tail, next)
                    }
                    next
                };

                count += 1;
            }
        }

        c = *(chars.peek().ok_or(SlErrCode::ParseUnexpectedEnd)?);
    }

    chars.next();
    Ok(head)
}

// TODO: What about lists, which need to be evaluated even if they appear in a vec or map
// TODO: Tighter integration between parser and evaluator likely necessary for this & symbols

/// Reads a vector from the input stream and creates the corresponding
/// Sail object
fn read_vec(
    chars: &mut iter::Peekable<str::Bytes>,
    acc: &mut Vec<u8>,
    reg: *mut memmgt::Region,
    tbl: *mut SlHead,
) -> Result<*mut SlHead, SlErrCode> {
    // TODO: allow vectors of arbitrary length
    let vec = stdvec_make(reg, 8);
    let mut c = *(chars.peek().ok_or(SlErrCode::ParseUnexpectedEnd)?);
    while c != b']' {
        match c {
            b';' => while chars.next().unwrap_or(b'\n') != b'\n' {},
            _ if c.is_ascii_whitespace() => {
                chars.next();
            }
            _ => stdvec_push(vec, read_value(chars, acc, reg, tbl)?),
        }
        c = *(chars.peek().ok_or(SlErrCode::ParseUnexpectedEnd)?);
    }
    chars.next();
    Ok(vec)
}

/// Reads an associative map from the input stream and creates the
/// corresponding Sail object
fn read_map(
    chars: &mut iter::Peekable<str::Bytes>,
    acc: &mut Vec<u8>,
    reg: *mut memmgt::Region,
    tbl: *mut SlHead,
) -> Result<*mut SlHead, SlErrCode> {
    let map = hashvec_make(reg, 16);
    let mut c = *(chars.peek().ok_or(SlErrCode::ParseUnexpectedEnd)?);
    while c != b'}' {
        match c {
            b';' => while chars.next().unwrap_or(b'\n') != b'\n' {},
            _ if c.is_ascii_whitespace() => {
                chars.next();
            }
            _ => hash_map_insert(
                reg,
                map,
                read_value(chars, acc, reg, tbl)?,
                read_value(chars, acc, reg, tbl)?,
            ),
        }
        c = *(chars.peek().ok_or(SlErrCode::ParseUnexpectedEnd)?);
    }
    chars.next();
    Ok(map)
}

/// Reads a basic symbol from the input stream and creates its Sail
/// object
fn read_symbol(
    chars: &mut iter::Peekable<str::Bytes>,
    acc: &mut Vec<u8>,
    reg: *mut memmgt::Region,
    tbl: *mut SlHead,
) -> Result<*mut SlHead, SlErrCode> {
    while {
        let peek = chars.peek().unwrap_or(&b' ');
        match peek {
            b')' | b']' | b'}' => false,
            _ if peek.is_ascii_whitespace() => false,
            _ => true,
        }
    } {
        let next = chars.next().unwrap();
        match next {
            b'!' | b'*' | b'+' | b'-' | b'/' | b'<' | b'=' | b'>' | b'?' | b'_' => acc.push(next),
            _ if next.is_ascii_alphanumeric() => acc.push(next),
            _ => {
                return Err(SlErrCode::ParseInvalidChar);
            }
        }
    }

    let sym = sym_init(
        reg,
        super::sym_tab_get_id(reg, tbl, unsafe {
            str::from_utf8_unchecked(acc.as_slice())
        }),
    );

    Ok(sym)
}

/// Reads a specialized symbol from the input stream and creates its
/// Sail object
fn read_spec_sym(
    chars: &mut iter::Peekable<str::Bytes>,
    acc: &mut Vec<u8>,
    reg: *mut memmgt::Region,
    tbl: *mut SlHead,
    mode: SymbolMode,
) -> Result<*mut SlHead, SlErrCode> {
    while {
        let peek = chars.peek().unwrap_or(&b' ');
        match peek {
            b')' | b']' | b'}' => false,
            _ if peek.is_ascii_whitespace() => false,
            _ => true,
        }
    } {
        let next = chars.next().unwrap();
        match next {
            b'-' | b'_' => acc.push(next),
            _ if next.is_ascii_alphanumeric() => acc.push(next),
            _ => {
                return Err(SlErrCode::ParseInvalidChar);
            }
        }
    }

    if acc.len() == 0 {
        return Err(SlErrCode::ParseUnexpectedEnd);
    }

    let sym = unsafe {
        sym_init(
            reg,
            super::modeize_sym(
                sym_tab_get_id(reg, tbl, str::from_utf8_unchecked(acc.as_slice())),
                mode,
            ),
        )
    };

    Ok(sym)
}

/// Reads a string from the input stream and creates its Sail object
fn read_string(
    chars: &mut iter::Peekable<str::Bytes>,
    acc: &mut Vec<u8>,
    reg: *mut memmgt::Region,
    tbl: *mut SlHead,
) -> Result<*mut SlHead, SlErrCode> {
    let mut next = *(chars.peek().ok_or(SlErrCode::ParseUnexpectedEnd)?);
    while next != b'"' {
        acc.push(chars.next().unwrap());
        next = *(chars.peek().ok_or(SlErrCode::ParseUnexpectedEnd)?);
    }

    chars.next();

    let string = string_init(
        reg,
        match str::from_utf8(&acc) {
            Ok(s) => s,
            _ => return Err(SlErrCode::ParseInvalidString),
        },
    );

    Ok(string)
}

/// Reads a number from the input stream and creates its Sail object
fn read_number(
    chars: &mut iter::Peekable<str::Bytes>,
    acc: &mut Vec<u8>,
    reg: *mut memmgt::Region,
    tbl: *mut SlHead,
) -> Result<*mut SlHead, SlErrCode> {
    while {
        let peek = chars.peek().unwrap_or(&b' ');
        match peek {
            b')' | b']' | b'}' => false,
            _ if peek.is_ascii_whitespace() => false,
            _ => true,
        }
    } {
        let next = chars.next().unwrap();
        match next {
            b'+' | b'-' | b'_' | b'.' => acc.push(next),
            _ if next.is_ascii_alphanumeric() => acc.push(next),
            _ => {
                return Err(SlErrCode::ParseInvalidChar);
            }
        }
    }
    process_num(unsafe { str::from_utf8_unchecked(acc) }, reg, tbl)
}

/// Reads a special item from the input stream and creates a Sail
/// object if appropriate
fn read_special(
    chars: &mut iter::Peekable<str::Bytes>,
    acc: &mut Vec<u8>,
    reg: *mut memmgt::Region,
    tbl: *mut SlHead,
) -> Result<*mut SlHead, SlErrCode> {
    while {
        let peek = chars.peek().unwrap_or(&b' ');
        match peek {
            b')' | b']' | b'}' => false,
            _ if peek.is_ascii_whitespace() => false,
            _ => true,
        }
    } {
        let next = chars.next().unwrap();
        match next {
            b'_' => acc.push(next),
            _ if next.is_ascii_alphanumeric() => acc.push(next),
            _ => {
                return Err(SlErrCode::ParseInvalidChar);
            }
        }
    }

    if acc.len() == 0 {
        return Err(SlErrCode::ParseUnexpectedEnd);
    }

    if acc[0].eq_ignore_ascii_case(&b't') && acc.len() == 1 {
        Ok(bool_init(reg, true))
    } else if acc[0].eq_ignore_ascii_case(&b'f') && acc.len() == 1 {
        Ok(bool_init(reg, false))
    } else {
        Err(SlErrCode::ParseBadSpecial)
    }
}

/// Parses a number and creates an object according to its textual
/// representation
fn process_num(
    slice: &str,
    reg: *mut memmgt::Region,
    tbl: *mut SlHead,
) -> Result<*mut SlHead, SlErrCode> {
    if let Ok(n) = slice.parse::<i64>() {
        Ok(i64_init(reg, n))
    } else if let Ok(n) = slice.parse::<f64>() {
        Ok(f64_init(reg, n))
    } else {
        Err(SlErrCode::ParseInvalidNum)
    }
}