kamo 0.9.2

A library to assist in the creation of an interpreter or compiler and its associated runtime.
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
//! # Type parser for binary encoded types
//!
//! This module provides functions to parse a binary encoded type into a
//! [`Type`]. The binary encoding is a compact representation of a type that can
//! be used to serialize and deserialize types.
//!
//! The binary encoding is a sequence of bytes that represents a type. The
//! encoding is a simple grammar that can be parsed into a type. The grammar is
//! defined as follows:
//!
//! ```text
//! type     = (filled | option | code::VOID | code::NIL) eof
//! filled   = code::ANY | union | specific
//! specific = code::TYPE | code::BOOL | code::CHAR | code::INT
//!          | code::FLOAT | code::SYMBOL | code::BINARY
//!          | array | pair | lambda
//! array    = code::ARRAY filled-or-option fixed
//! pair     = code::PAIR filled-or-option filled-or-option
//! lambda   = code::LAMBDA params variadic return
//! params   = (filled-or-option)*
//! variadic = (code::VARIADIC filled-or-option)?
//! return   = code::RETURN (code::VOID | filled-or-option)
//! option   = code::OPTION filled
//! union    = code::UNION specific specific+ code::END
//! fixed    = (fixed0 | fixed1 | fixed2 | fixed3 | fixed4)?
//! fixed0   = code::FIXED0..=code::FIXED0_MAX
//! fixed1   = code::FIXED1..=code::FIXED1_MAX byte
//! fixed2   = code::FIXED2..=code::FIXED2_MAX byte byte
//! fixed3   = code::FIXED3..=code::FIXED3_MAX byte byte byte
//! fixed4   = code::FIXED4..=code::FIXED4_MAX byte byte byte byte
//! byte     = 0x00..=0xFF
//! ```

use crate::types::Type;

use super::{code, TypeCodeError};

/// Parse a type code stream into a type.
///
/// This function is called by the [`Type::new()`].
///
/// # Errors
///
/// If the type code stream is empty or is malformed, an error is returned.
///
/// # Grammar
///
/// ```text
/// type = (filled | option | code::VOID | code::NIL) eof
/// ```
pub fn parse(src: &[u8]) -> Result<Type, TypeCodeError> {
    let first = src.first().copied();
    let (ty, rest) = match first {
        Some(code::OPTION) => parse_option(src, 0)?,
        Some(code::VOID) => (Type::void(), &src[1..]),
        Some(code::NIL) => (Type::nil(), &src[1..]),
        Some(_) => parse_filled(src, 0)?,
        None => return Err(TypeCodeError::Empty),
    };

    if rest.is_empty() {
        Ok(ty)
    } else {
        Err(TypeCodeError::ExpectedEof(src.len() - rest.len()))
    }
}

/// Parse a type code stream into a specific type.
///
/// # Errors
///
/// If the type code stream is empty or is not a specific type, an error is
/// returned.
///
/// # Grammar
///
/// ```text
/// specific = code::TYPE | code::BOOL | code::CHAR | code::INT
///          | code::FLOAT | code::SYMBOL | code::BINARY
///          | array | pair | lambda
/// ```
pub fn parse_specific(src: &[u8], offset: usize) -> Result<(Type, &[u8]), TypeCodeError> {
    src.first()
        .copied()
        .ok_or(TypeCodeError::ExpectedSpecificTypeEof(offset))
        .and_then(|code| match code {
            code::TYPE => Ok((Type::typedef(), &src[1..])),
            code::BOOL => Ok((Type::boolean(), &src[1..])),
            code::CHAR => Ok((Type::character(), &src[1..])),
            code::INT => Ok((Type::integer(), &src[1..])),
            code::FLOAT => Ok((Type::float(), &src[1..])),
            code::SYMBOL => Ok((Type::symbol(), &src[1..])),
            code::BINARY => Ok((Type::binary(), &src[1..])),
            code::ARRAY => parse_array(src, offset),
            code::PAIR => parse_pair(src, offset),
            code::LAMBDA => parse_lambda(src, offset),
            _ => Err(TypeCodeError::ExpectedSpecificType(offset)),
        })
}

/// Parse a type code stream into a filled type.
///
/// # Errors
///
/// If the type code stream is empty or is not a filled type, an error is
/// returned.
///
/// # Grammar
///
/// ```text
/// filled = code::ANY | union | specific
/// ```
pub fn parse_filled(src: &[u8], offset: usize) -> Result<(Type, &[u8]), TypeCodeError> {
    src.first()
        .copied()
        .ok_or(TypeCodeError::ExpectedFilledTypeEof(offset))
        .and_then(|code| match code {
            code::ANY => Ok((Type::any(), &src[1..])),
            code::TYPE => Ok((Type::typedef(), &src[1..])),
            code::BOOL => Ok((Type::boolean(), &src[1..])),
            code::CHAR => Ok((Type::character(), &src[1..])),
            code::INT => Ok((Type::integer(), &src[1..])),
            code::FLOAT => Ok((Type::float(), &src[1..])),
            code::SYMBOL => Ok((Type::symbol(), &src[1..])),
            code::BINARY => Ok((Type::binary(), &src[1..])),
            code::ARRAY => parse_array(src, offset),
            code::PAIR => parse_pair(src, offset),
            code::LAMBDA => parse_lambda(src, offset),
            code::UNION => parse_union(src, offset),
            _ => Err(TypeCodeError::ExpectedFilledType(offset)),
        })
}

/// Parse a type code stream into a filled type or an option type.
///
/// # Errors
///
/// If the type code stream is empty or is not a filled or option type, an error
/// is returned.
///
/// # Grammar
///
/// ```text
/// filled-or-option = filled | option
/// ```
pub fn parse_filled_or_option(src: &[u8], offset: usize) -> Result<(Type, &[u8]), TypeCodeError> {
    let first = src
        .first()
        .copied()
        .ok_or(TypeCodeError::ExpectedTypeOrOption(offset))?;

    match first {
        code::OPTION => parse_option(src, offset),
        _ => parse_filled(src, offset),
    }
}

#[inline]
fn expect_array(src: &[u8], offset: usize) -> Result<(&[u8], usize), TypeCodeError> {
    src.first()
        .copied()
        .ok_or(TypeCodeError::ExpectedArrayEof(offset))
        .and_then(|c| match c {
            code::ARRAY => Ok((&src[1..], offset + 1)),
            _ => Err(TypeCodeError::ExpectedArray(offset)),
        })
}

/// Parse a type code stream into an array type.
///
/// # Errors
///
/// If the type code stream is empty or is not an array type, an error is
/// returned.
///
/// # Panics
///
/// This function will panic if the array type cannot be created from the
/// emitted type code. This should never happen as the type code is generated
/// from a valid type.
///
/// # Grammar
///
/// ```text
/// array = code::ARRAY filled-or-option fixed
/// ```
pub fn parse_array(input: &[u8], offset: usize) -> Result<(Type, &[u8]), TypeCodeError> {
    let (cursor, offset) = expect_array(input, offset)?;
    let (elem, cursor) = parse_filled_or_option(cursor, offset)?;
    let (size, src) = parse_fixed(cursor, offset + (input.len() - cursor.len()))?;

    Ok((Type::array(elem, size).expect("array type"), src))
}

#[inline]
fn expect_pair(src: &[u8], offset: usize) -> Result<(&[u8], usize), TypeCodeError> {
    src.first()
        .copied()
        .ok_or(TypeCodeError::ExpectedPairEof(offset))
        .and_then(|c| match c {
            code::PAIR => Ok((&src[1..], offset + 1)),
            _ => Err(TypeCodeError::ExpectedPair(offset)),
        })
}

/// Parse a type code stream into a pair type.
///
/// # Errors
///
/// If the type code stream is empty or is not a pair type, an error is
/// returned.
///
/// # Panics
///
/// This function will panic if the pair type cannot be created from the emitted
/// type code. This should never happen as the type code is generated from a
/// valid type.
///
/// # Grammar
///
/// ```text
/// pair = code::PAIR filled-or-option filled-or-option
/// ```
#[allow(clippy::similar_names)]
pub fn parse_pair(input: &[u8], offset: usize) -> Result<(Type, &[u8]), TypeCodeError> {
    let (cursor, offset) = expect_pair(input, offset)?;
    let (car, cursor) = parse_filled_or_option(cursor, offset)?;
    let (cdr, cursor) = parse_filled_or_option(cursor, offset + (input.len() - cursor.len()))?;

    Ok((Type::pair(car, cdr).expect("pair taype"), cursor))
}

#[inline]
fn expect_lambda(input: &[u8], offset: usize) -> Result<(&[u8], usize), TypeCodeError> {
    input
        .first()
        .copied()
        .ok_or(TypeCodeError::ExpectedLambdaEof(offset))
        .and_then(|c| match c {
            code::LAMBDA => Ok((&input[1..], offset + 1)),
            _ => Err(TypeCodeError::ExpectedLambda(offset)),
        })
}

/// Parse a type code stream into a lambda type.
///
/// # Errors
///
/// If the type code stream is empty or is not a lambda type, an error is
/// returned.
///
/// # Panics
///
/// This function will panic if the lambda type cannot be created from the
/// emitted type code. This should never happen as the type code is generated
/// from a valid type.
///
/// # Grammar
///
/// ```text
/// lambda = code::LAMBDA params variadic return
/// ```
pub fn parse_lambda(src: &[u8], offset: usize) -> Result<(Type, &[u8]), TypeCodeError> {
    let (src, offset) = expect_lambda(src, offset)?;
    let (params, cursor) = parse_params(src, offset)?;
    let (variadic, cursor) = parse_variadic(cursor, offset + (src.len() - cursor.len()))?;
    let (ret, cursor) = parse_return(cursor, offset + (src.len() - cursor.len()))?;

    Ok((
        Type::lambda(params, variadic, ret).expect("lambda type"),
        cursor,
    ))
}

/// Parse a type code stream into a sequence of parameters, which may filled or
/// option types. The sequence may be of zero length. Parses until no more
/// parameters can be found.
///
/// # Errors
///
/// If the type code stream is malformed, an error is returned.
///
/// # Grammar
///
/// ```text
/// params = (filled-or-option)*
/// ```
pub fn parse_params(src: &[u8], offset: usize) -> Result<(Vec<Type>, &[u8]), TypeCodeError> {
    let mut params = Vec::new();
    let mut offset = offset;
    let mut cursor = src;

    while let Ok((arg, rest)) = parse_filled_or_option(cursor, offset) {
        params.push(arg);
        offset += cursor.len() - rest.len();
        cursor = rest;
    }

    Ok((params, cursor))
}

/// Parse a type code stream into an optional variadic type.
///
/// # Errors
///
/// If the type code stream is malformed, an error is returned.
///
/// # Grammar
///
/// ```text
/// variadic = (code::VARIADIC filled-or-option)?
/// ```
pub fn parse_variadic(src: &[u8], offset: usize) -> Result<(Option<Type>, &[u8]), TypeCodeError> {
    if src.first().copied() == Some(code::VARIADIC) {
        let offset = offset + 1;
        let (arg, src) = parse_filled_or_option(&src[1..], offset)?;

        Ok((Some(arg), src))
    } else {
        Ok((None, src))
    }
}

#[inline]
fn expect_return(src: &[u8], offset: usize) -> Result<(&[u8], usize), TypeCodeError> {
    src.first()
        .copied()
        .filter(|&c| c == code::RETURN)
        .map(|_| (&src[1..], offset + 1))
        .ok_or(TypeCodeError::ExpectedReturn(offset))
}

/// Parse a type code stream into a return type.
///
/// # Errors
///
/// If the type code stream does not start with a return code, is empty or is
/// malformed, an error is returned.
///
/// # Grammar
///
/// ```text
/// return = code::RETURN (code::VOID | filled-or-option)
/// ```
pub fn parse_return(src: &[u8], offset: usize) -> Result<(Type, &[u8]), TypeCodeError> {
    let (src, offset) = expect_return(src, offset)?;
    let (ty, rest) = match src.first().copied() {
        Some(code::OPTION) => parse_option(src, offset)?,
        Some(code::VOID) => (Type::void(), &src[1..]),
        Some(_) => parse_filled(src, offset)?,
        None => return Err(TypeCodeError::ExpectedReturnType(offset)),
    };

    Ok((ty, rest))
}

#[inline]
fn expect_option(src: &[u8], offset: usize) -> Result<(&[u8], usize), TypeCodeError> {
    src.first()
        .copied()
        .filter(|&c| c == code::OPTION)
        .map(|_| (&src[1..], offset + 1))
        .ok_or(TypeCodeError::ExpectedOption(offset))
}

/// Parse a type code stream into an option type.
///
/// # Errors
///
/// If the type code stream is empty, does not start with an option code or is
/// malformed, an error is returned.
///
/// # Panics
///
/// This function will panic if the option type cannot be created from the
/// emitted type code. This should never happen as the type code is generated
/// from a valid type.
///
/// # Grammar
///
/// ```text
/// option = code::OPTION filled
/// ```
pub fn parse_option(src: &[u8], offset: usize) -> Result<(Type, &[u8]), TypeCodeError> {
    let (src, offset) = expect_option(src, offset)?;
    let (ty, rest) = match src.first().copied() {
        Some(code::OPTION) => return Err(TypeCodeError::ExpectedFilledType(offset)),
        Some(_) => parse_filled(src, offset)?,
        None => return Err(TypeCodeError::ExpectedOptionType(offset)),
    };

    Ok((Type::option(ty).expect("option type"), rest))
}

#[inline]
fn expect_union(src: &[u8], offset: usize) -> Result<(&[u8], usize), TypeCodeError> {
    src.first()
        .copied()
        .filter(|&c| c == code::UNION)
        .map(|_| (&src[1..], offset + 1))
        .ok_or(TypeCodeError::ExpectedUnion(offset))
}

fn expect_union_end(src: &[u8], offset: usize) -> Result<(&[u8], usize), TypeCodeError> {
    src.first()
        .copied()
        .filter(|&c| c == code::END)
        .map(|_| (&src[1..], offset + 1))
        .ok_or(TypeCodeError::ExpectedMemberOrEnd(offset))
}

/// Parse a type code stream into a union type.
///
/// # Errors
///
/// If the type code stream is empty, does not start with a union code or is
/// malformed, an error is returned.
///
/// # Panics
///
/// This function will panic if the union type cannot be created from the
/// emitted type code. This should never happen as the type code is generated
/// from a valid type.
///
/// # Grammar
///
/// ```text
/// union = code::UNION specific specific+ code::END
/// ```
pub fn parse_union(src: &[u8], offset: usize) -> Result<(Type, &[u8]), TypeCodeError> {
    let mut members = Vec::new();
    let (cursor, offset) = expect_union(src, offset)?;
    let (ty1, cursor) = parse_specific(cursor, offset)?;
    let offset = src.len() - cursor.len();
    let (ty2, mut cursor) = parse_specific(cursor, offset)?;
    let mut offset = src.len() - cursor.len();

    members.push(ty1);
    members.push(ty2);
    while let Ok((ty, rest)) = parse_specific(cursor, offset) {
        members.push(ty);
        offset += cursor.len() - rest.len();
        cursor = rest;
    }

    let (cursor, _) = expect_union_end(cursor, offset)?;

    Ok((Type::union(members).expect("union type"), cursor))
}

/// Parse a type code stream into an optional fixed length value.
///
/// # Errors
///
/// If the type code stream is empty or is malformed, an error is returned.
///
/// # Grammar
///
/// ```text
/// fixed  = (fixed0 | fixed1 | fixed2 | fixed3 | fixed4)?
/// fixed0 = code::FIXED0..=code::FIXED0_MAX
/// fixed1 = code::FIXED1..=code::FIXED1_MAX byte
/// fixed2 = code::FIXED2..=code::FIXED2_MAX byte byte
/// fixed3 = code::FIXED3..=code::FIXED3_MAX byte byte byte
/// fixed4 = code::FIXED4..=code::FIXED4_MAX byte byte byte byte
/// byte   = 0x00..=0xFF
/// ```
pub fn parse_fixed(src: &[u8], offset: usize) -> Result<(Option<usize>, &[u8]), TypeCodeError> {
    let (fixed, len) = match src.first().copied() {
        Some(val @ code::FIXED0..=code::FIXED0_MAX) => ((val - code::FIXED0) as usize, 1),
        Some(val @ code::FIXED1..=code::FIXED1_MAX) => {
            let mut fixed = ((val - code::FIXED1) as usize) << 8;

            if src.len() < 2 {
                return Err(TypeCodeError::ExpectedFixedByte(offset));
            }
            fixed |= src[1] as usize;
            (fixed, 2)
        }
        Some(val @ code::FIXED2..=code::FIXED2_MAX) => {
            let mut fixed = ((val - code::FIXED2) as usize) << 16;

            if src.len() < 3 {
                return Err(TypeCodeError::ExpectedFixedBytes(offset, 2));
            }
            fixed |= (src[1] as usize) << 8;
            fixed |= src[2] as usize;
            (fixed, 3)
        }
        Some(val @ code::FIXED3..=code::FIXED3_MAX) => {
            let mut fixed = ((val - code::FIXED3) as usize) << 24;

            if src.len() < 4 {
                return Err(TypeCodeError::ExpectedFixedBytes(offset, 3));
            }
            fixed |= (src[1] as usize) << 16;
            fixed |= (src[2] as usize) << 8;
            fixed |= src[3] as usize;
            (fixed, 4)
        }
        Some(val @ code::FIXED4..=code::FIXED4_MAX) => {
            let mut fixed = ((val - code::FIXED4) as usize) << 32;

            if src.len() < 5 {
                return Err(TypeCodeError::ExpectedFixedBytes(offset, 4));
            }
            fixed |= (src[1] as usize) << 24;
            fixed |= (src[2] as usize) << 16;
            fixed |= (src[3] as usize) << 8;
            fixed |= src[4] as usize;
            (fixed, 5)
        }
        Some(_) | None => return Ok((None, src)),
    };
    Ok((Some(fixed), &src[len..]))
}