mech-syntax 0.3.3

A toolchain for compiling textual syntax into Mech blocks.
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
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
// Parser
// ========

/// Sections:
///   1. Prelude
///   2. Parser combinators
///   3. Recovery functions
///   4. Public interface
///   5. Error reporting

// 1. Prelude
// ------------

use crate::*;
use crate::functions::function_define;

use mech_core::nodes::*;
use mech_core::nodes::{SectionElement, MechString, Table};

#[cfg(not(feature = "no-std"))] use core::fmt;
#[cfg(feature = "no-std")] use alloc::fmt;
#[cfg(feature = "no-std")] use alloc::string::String;
#[cfg(feature = "no-std")] use alloc::vec::Vec;
use nom::{
  IResult,
  branch::alt,
  sequence::{tuple as nom_tuple, preceded},
  combinator::{opt, eof, cut, peek},
  multi::{many1, many_till, many0, separated_list1, separated_list0},
  Err,
  Err::Failure
};

use std::collections::HashMap;
use colored::*;

//use crate::*;
use crate::{
  TextFormatter,
  ParseError,
  ParseString,
  ParseErrorDetail,
  graphemes,
  ParseResult,
};

// 2. Parser combinators
// -----------------------

/// Convert output of any parser into ParserNode::Null.
/// Useful for working with `alt` combinator and error recovery functions.
pub fn null<'a, F, O>(mut parser: F) ->
  impl FnMut(ParseString<'a>) -> ParseResult<()>
where
  F: FnMut(ParseString<'a>) -> ParseResult<O>
{
  move |input: ParseString| match parser(input) {
    Ok((remaining, _)) => Ok((remaining, ())),
    Err(Err::Error(e)) => Err(Err::Error(e)),
    Err(Err::Failure(e)) => Err(Err::Failure(e)),
    x => panic!("Err::Incomplete is not supported"),
  }
}

/// For parser p, run p and also output the range that p has matched
/// upon success.
pub fn range<'a, F, O>(mut parser: F) ->
  impl FnMut(ParseString<'a>) -> ParseResult<(O, SourceRange)>
where
  F: FnMut(ParseString<'a>) -> ParseResult<O>
{
  move |input: ParseString| {
    let start = input.loc();
    match parser(input) {
      Ok((remaining, o)) => {
        let rng = SourceRange { start, end: remaining.loc(), };
        Ok((remaining, (o, rng)))
      },
      Err(e) => Err(e),
    }
  }
}

#[macro_export]
macro_rules! label {
  ($parser:expr, $msg:expr) => {
    (label_without_recovery($parser, ParseErrorDetail {
      message: $msg, annotation_rngs: vec![]
    }))
  };

  ($parser:expr, $msg:expr, $($rngs:expr),+) => {
    (label_without_recovery($parser, ParseErrorDetail {
      message: $msg, annotation_rngs: vec![$($rngs),+]
    }))
  };
}

#[macro_export]
macro_rules! labelr {
  ($parser:expr, $recovery_fn:expr, $msg:expr) => {
    (label_with_recovery($parser, $recovery_fn, ParseErrorDetail {
      message: $msg, annotation_rngs: vec![]
    }))
  };

  ($parser:expr, $recovery_fn:expr, $msg:expr, $($rngs:expr),+) => {
    (label_with_recovery($parser, $recovery_fn, ParseErrorDetail {
      message: $msg, annotation_rngs: vec![$($rngs),+]
    }))
  };
}

/// Label without recovery function. Upgrade Err::Error to Err:Failure
/// and override its context information.
pub fn label_without_recovery<'a, F, O>(
  mut parser: F,
  error_detail: ParseErrorDetail,
) ->
  impl FnMut(ParseString<'a>) -> ParseResult<O>
where
  F: FnMut(ParseString<'a>) -> ParseResult<O>
{
  move |mut input: ParseString| {
    let start = input.loc();
    match parser(input) {
      Err(Err::Error(mut e)) => {
        e.cause_range = SourceRange { start, end: e.cause_range.end };
        e.error_detail = error_detail.clone();
        Err(Err::Failure(e))
      }
      x => x,
    }
  }
}

/// Label with recovery function. In addition to upgrading errors, the
/// error is logged and recovery function will be run as an attempt to
/// synchronize parser state.
pub fn label_with_recovery<'a, F, O>(
  mut parser: F,
  mut recovery_fn: fn(ParseString<'a>) -> ParseResult<O>,
  error_detail: ParseErrorDetail,
) ->
  impl FnMut(ParseString<'a>) -> ParseResult<O>
where
  F: FnMut(ParseString<'a>) -> ParseResult<O>
{
  move |mut input: ParseString| {
    let start = input.loc();
    match parser(input) {
      Err(Err::Error(mut e)) => {
        e.cause_range = SourceRange { start, end: e.cause_range.end };
        e.error_detail = error_detail.clone();
        e.log();
        recovery_fn(e.remaining_input)
      }
      Err(Err::Failure(mut e)) => {
        e.cause_range = SourceRange { start, end: e.cause_range.end };
        //e.error_detail = error_detail.clone();
        e.log();
        recovery_fn(e.remaining_input)
      },
      x => x,
    }
  }
}

/// For parser p, return the `!!p` peek parsing expression.
pub fn is<'a, F, O>(mut parser: F) ->
  impl FnMut(ParseString<'a>) -> ParseResult<O>
where
  F: FnMut(ParseString<'a>) -> ParseResult<O>
{
  move |input: ParseString| {
    let input_clone = input.clone();
    match parser(input_clone) {
      Ok((_, o)) => Ok((input, o)),
      _ => Err(Err::Error(ParseError::new(input, "Unexpected character"))),
    }
  }
}

/// For parser p, return the `!p` peek parsing expression.
pub fn is_not<'a, F, E>(mut parser: F) ->
  impl FnMut(ParseString<'a>) -> ParseResult<()>
where
  F: FnMut(ParseString<'a>) -> ParseResult<E>
{
  move |input: ParseString| {
    let input_clone = input.clone();
    match parser(input_clone) {
      Err(Err::Failure(_)) |
      Err(Err::Error(_)) => Ok((input, ())),
      _ => Err(Err::Error(ParseError::new(input, "Unexpected character")))
    }
  }
}

/// Return a terminal parsing expression that consumes `tag` from input.
pub fn tag(tag: &'static str) -> impl Fn(ParseString) -> ParseResult<String> {
  move |mut input: ParseString| {
    if input.is_empty() {
      return Err(nom::Err::Error(ParseError::new(input, "Unexpected eof")));
    }
    if let Some(matched) = input.consume_tag(tag) {
      Ok((input, matched))
    } else {
      Err(nom::Err::Error(ParseError::new(input, "Unexpected character")))
    }
  }
}

// 3. Recovery functions
// -----------------------

// skip_till_eol := (!new_line, any)* ;
pub fn skip_till_eol(input: ParseString) -> ParseResult<Token> {
  let (input, matched) = many0(nom_tuple((
    is_not(new_line),
    any_token,
  )))(input)?;
  let mut matched: Vec<Token> = matched.into_iter().map(|(_, t)| t).collect(); 
  let tkn = Token::merge_tokens(&mut matched).unwrap_or(Token::default()); 
  Ok((input, tkn))
}

// skip_past_eol := skip_till_eol, new_line ;
pub fn skip_past_eol(input: ParseString) -> ParseResult<Token> {
  let (input, matched) = skip_till_eol(input)?;
  let (input, nl) = new_line(input)?;
  let matched = Token::merge_tokens(&mut vec![matched, nl]).unwrap_or(Token::default());
  Ok((input, matched))
}

// skip-till-end-of-statement := *((!new-line, !";"), any) ;
pub fn skip_till_end_of_statement(input: ParseString) -> ParseResult<Token> {
  // If empty, return
  if input.is_empty() {
      return Ok((input, Token::default()));
  }

  // Consume until either newline or ;
  let (input, matched) = many0(nom_tuple((
      // is_not matches any char NOT in the set
      is_not(alt((
          new_line,
          semicolon,
          mika_section_close,
      ))),
      any_token,
  )))(input)?;

  let mut matched: Vec<Token> = matched.into_iter().map(|(_, t)| t).collect();
  let tkn = Token::merge_tokens(&mut matched).unwrap_or(Token::default());

  Ok((input, tkn))
}

// skip_till_section_element := skip_past_eol, (!section_element, skip_past_eol)* ;
pub fn skip_till_section_element(input: ParseString) -> ParseResult<Token> {
  if input.is_empty() {
    return Ok((input, Token::default()));
  }
  let (input, matched) = skip_past_eol(input)?;
  let (input, matched2) = many0(nom_tuple((
    is_not(section_element),
    skip_past_eol,
  )))(input)?;
  let mut matched: Vec<Token> = vec![matched];
  matched.extend(matched2.into_iter().map(|(_, t)| t));
  let tkn = Token::merge_tokens(&mut matched).unwrap_or(Token::default());
  Ok((input, tkn))
}

pub fn skip_till_paragraph_element(input: ParseString) -> ParseResult<Token> {
  // if it's empty, return
  if input.is_empty() {
    return Ok((input, Token::default()));
  }
  // Otherwise, consume tokens until we reach a paragraph element
  let (input, matched) = many0(nom_tuple((
    is_not(paragraph_element),
    any_token,
  )))(input)?;
  let mut matched: Vec<Token> = matched.into_iter().map(|(_, t)| t).collect(); 
  let tkn = Token::merge_tokens(&mut matched).unwrap_or(Token::default());
  Ok((input, tkn))
}

// skip_spaces := space* ;
pub fn skip_spaces(input: ParseString) -> ParseResult<()> {
  let (input, _) = many0(space)(input)?;
  Ok((input, ()))
}

// skip_nil := ;
pub fn skip_nil(input: ParseString) -> ParseResult<()> {
  Ok((input, ()))
}

// skip_empty_mech_directive := ;
pub fn skip_empty_mech_directive(input: ParseString) -> ParseResult<String> {
  Ok((input, String::from("mech:")))
}

// recovery function for Recoverable nodes with customizable skip function
pub fn recover<T: Recoverable, F>(input: ParseString, skip_fn: F) -> ParseResult<T>
where
  F: Fn(ParseString) -> ParseResult<Token>,
{
  let start = input.loc();
  let (input, matched) = skip_fn(input)?;
  let end = input.loc();
  Ok((input, T::error_placeholder(matched, SourceRange { start, end })))
}

// 4. Public interface
// ---------------------

// mech_code_alt := fsm_specification | fsm_implementation | function_define | statement | expression | comment ;
pub fn mech_code_alt(input: ParseString) -> ParseResult<MechCode> {
  let (input, _) = whitespace0(input)?;
  let parsers: Vec<(&str, Box<dyn Fn(ParseString) -> ParseResult<MechCode>>)> = vec![
    ("fsm_specification", Box::new(|i| fsm_specification(i).map(|(i, v)| (i, MechCode::FsmSpecification(v))))),
    ("fsm_implementation", Box::new(|i| fsm_implementation(i).map(|(i, v)| (i, MechCode::FsmImplementation(v))))),
    ("function_define", Box::new(|i| function_define(i).map(|(i, v)| (i, MechCode::FunctionDefine(v))))),
    ("statement",   Box::new(|i| statement(i).map(|(i, v)| (i, MechCode::Statement(v))))),
    ("expression",  Box::new(|i| expression(i).map(|(i, v)| (i, MechCode::Expression(v))))),
    ("comment",     Box::new(|i| comment(i).map(|(i, v)| (i, MechCode::Comment(v))))),
  ];
  match alt_best(input, &parsers) {
    Ok((input, code)) => {
      return Ok((input, code));
    }
    Err(e) => {
      return Err(e);
    }
  };

}

/// code-terminal := *space-tab, ?(?semicolon, *space-tab, comment), (new-line | ";" | eof), *whitespace ;
pub fn code_terminal(input: ParseString) -> ParseResult<Option<Comment>> {
  let (input, _) = many0(space_tab)(input)?;
  let (input, cmmnt) = opt(tuple((opt(semicolon), many0(space_tab), comment)))(input)?;
  let (input, _) = alt((null(new_line), null(semicolon), null(eof), null(peek(mika_section_close))))(input)?;
  let (input, _) = whitespace0(input)?;
  let cmmt = match cmmnt {
    Some((_, _, cmnt)) => Some(cmnt),
    None => None,
  };
  Ok((input, cmmt))
}

// mech-code-block := +(mech-code, code-terminal) ;
pub fn mech_code(input: ParseString) -> ParseResult<Vec<(MechCode,Option<Comment>)>> {
  let mut output = vec![];
  let mut new_input = input.clone();
  loop {

    if peek(not_mech_code)(new_input.clone()).is_ok() {
      if output.len() > 0 {
        return Ok((new_input, output));
      } else {
        let e = ParseError::new(new_input, "Unexpected character");
        return Err(Err::Error(e));
      }
    }

    let start = new_input.loc();
    let start_cursor = new_input.cursor;
    let (input, code) = match mech_code_alt(new_input.clone()) {
      Err(Err::Error(mut e)) => {
        // if the error is just "Unexpected character", we will just fail.
        if e.error_detail.message == "Unexpected character" {
          if output.len() > 0 {
            return Ok((new_input, output));
          } else {
            return Err(Err::Error(e));
          }
        } else {
          e.cause_range = SourceRange { start, end: e.cause_range.end };
          e.log();
          // skip till the end of the statement
          let (input, skipped) = skip_till_end_of_statement(e.remaining_input)?;
          // get tokens from start_cursor to input.cursor
          let skipped_input = input.slice(start_cursor, input.cursor);
          let skipped_token = Token {
            kind: TokenKind::Error,
            chars: skipped_input.chars().collect(),
            src_range: SourceRange { start, end: input.loc() },
          };
          let mech_error = MechCode::Error(skipped_token, e.cause_range);
          (input, mech_error)
        }
      }
      Err(Err::Failure(mut e)) => {
        // Check if this thing matches a section element:
        match subtitle(new_input.clone()) {
          Ok((_, _)) => {
            // if it does, and we have already parsed something, return what we have.
            if output.len() > 0 {
              return Ok((new_input, output));
            } else {
              return Err(Err::Failure(e));
            }
          }
          Err(_) => { /* continue with error recovery */ }
        }
        e.cause_range = SourceRange { start, end: e.cause_range.end };
        e.log();
        // skip till the end of the statement
        let (input, skipped) = skip_till_end_of_statement(e.remaining_input)?;
        // get tokens from start_cursor to input.cursor
        let skipped_input = input.slice(start_cursor, input.cursor);
        let skipped_token = Token {
          kind: TokenKind::Error,
          chars: skipped_input.chars().collect(),
          src_range: SourceRange { start, end: input.loc() },
        };
        let mech_error = MechCode::Error(skipped_token, e.cause_range);
        (input, mech_error)
      },
      Ok(x) => x,
      _ => unreachable!(),
    };
    let (input, cmmt) = match code_terminal(input) {
      Ok((input, cmmt)) => (input, cmmt),
      Err(e) => {
        // if we didn't parse a terminal, just return what we've got so far.
        if output.len() > 0 {
          return Ok((new_input, output));
        }
        // otherwise, return the error.
        return Err(e);
      }
    };
    output.push((code, cmmt));
    new_input = input;
    if new_input.is_empty() {
      break;
    }
  }
  Ok((new_input, output))
}

// program := ws0, ?title, body, ws0 ;
pub fn program(input: ParseString) -> ParseResult<Program> {
  let msg = "Expects program body";
  let (input, _) = whitespace0(input)?;
  let (input, title) = opt(title)(input)?;
  //let (input, body) = labelr!(body, skip_nil, msg)(input)?;
  let (input, body) = body(input)?;
  //println!("Parsed program body: {:#?}", body);
  let (input, _) = whitespace0(input)?;
  Ok((input, Program{title, body}))
}

// parse_mech := program | statement ;
pub fn parse_mech(input: ParseString) -> ParseResult<Program> {
  //let (input, mech) = alt((program, statement))(input)?;
  //Ok((input, ParserNode::Root { children: vec![mech] }))
  let (input, mech) = program(input)?;
  Ok((input, mech))
}

// 5. Error Reporting
// --------------------

/// Print formatted error message.
pub fn print_err_report(text: &str, report: &ParserErrorReport) {
  let msg = TextFormatter::new(text).format_error(report);
  println!("{}", msg);
}

pub fn parse_grammar(text: &str) -> MResult<Grammar> {
  // remove all whitespace from the input string
  let text_no_Ws = &text.replace(" ", "").replace("\n", "").replace("\r", "").replace("\t", "");
  let graphemes = graphemes::init_source(text_no_Ws);
  let mut result_node = None;
  let mut error_log: Vec<(SourceRange, ParseErrorDetail)> = vec![];

  // Do parse
  let remaining: ParseString = match grammar(ParseString::new(&graphemes)) {
    // Got a parse tree, however there may be errors
    Ok((mut remaining_input, parse_tree)) => {
      error_log.append(&mut remaining_input.error_log);
      result_node = Some(parse_tree);
      remaining_input
    },
    // Parsing failed and could not be recovered. No parse tree was created in this case
    Err(err) => {
      match err {
        Err::Error(mut e) | Err::Failure(mut e) => {
          error_log.append(&mut e.remaining_input.error_log);
          error_log.push((e.cause_range, e.error_detail));
          e.remaining_input
        },
        Err::Incomplete(_) => panic!("nom::Err::Incomplete is not supported!"),
      }
    },
  };
  // Check if all inputs were parsed
  if remaining.len() != 0 {
    let e = ParseError::new(remaining, "Inputs since here are not parsed");
    error_log.push((e.cause_range, e.error_detail));
  }

  // Construct result
  if error_log.is_empty() {
    Ok(result_node.unwrap())
  } else {
    let report: Vec<ParserErrorContext> = error_log.into_iter().map(|e| ParserErrorContext {
      cause_rng: e.0,
      err_message: String::from(e.1.message),
      annotation_rngs: e.1.annotation_rngs,
    }).collect();
    Err(MechError::new(
      ParserErrorReport(text.to_string(), report),
      None
    ))
  }
}


pub fn parse(text: &str) -> MResult<Program> {
  let graphemes = graphemes::init_source(text);
  let mut result_node = None;
  let mut error_log: Vec<(SourceRange, ParseErrorDetail)> = vec![];

  // Do parse
  let remaining: ParseString = match parse_mech(ParseString::new(&graphemes)) {
    // Got a parse tree, however there may be errors
    Ok((mut remaining_input, parse_tree)) => {
      error_log.append(&mut remaining_input.error_log);
      result_node = Some(parse_tree);
      remaining_input
    },
    // Parsing failed and could not be recovered. No parse tree was created in this case
    Err(err) => {
      match err {
        Err::Error(mut e) | Err::Failure(mut e) => {
          error_log.append(&mut e.remaining_input.error_log);
          error_log.push((e.cause_range, e.error_detail));
          e.remaining_input
        },
        Err::Incomplete(_) => panic!("nom::Err::Incomplete is not supported!"),
      }
    },
  };

  // Check if all inputs were parsed
  if remaining.len() != 0 {
    let e = ParseError::new(remaining, "Inputs since here are not parsed");
    error_log.push((e.cause_range, e.error_detail));
  }

  // Construct result
  if error_log.is_empty() {
    Ok(result_node.unwrap())
  } else {
    let report: Vec<ParserErrorContext> = error_log.into_iter().map(|e| ParserErrorContext {
      cause_rng: e.0,
      err_message: String::from(e.1.message),
      annotation_rngs: e.1.annotation_rngs,
    }).collect();
    Err(MechError::new(
      ParserErrorReport(text.to_string(), report),
      None
    ).with_compiler_loc())
  }
}