peginator/
peg_parser.rs

1// Copyright (C) 2022, Alex Badics
2// This file is part of peginator
3// Licensed under the MIT license. See LICENSE file in the project root for details.
4
5use super::{IndentedTracer, NoopTracer, ParseError, ParseTracer};
6
7/// The main trait for interfacing with peginator. Implemented by `@export`-ed rules.
8pub trait PegParser: Sized {
9    /// Parse a string into the AST.
10    fn parse(s: &str) -> Result<Self, ParseError>;
11
12    /// Parse a string into the AST, print a colored trace of the parse process.
13    ///
14    /// The printing happens with regular `eprintln!()`.
15    fn parse_with_trace(s: &str) -> Result<Self, ParseError>;
16}
17
18impl<T: PegParserAdvanced<()>> PegParser for T {
19    fn parse(s: &str) -> Result<Self, ParseError> {
20        Self::parse_advanced::<NoopTracer>(s, &ParseSettings::default(), ())
21    }
22    fn parse_with_trace(s: &str) -> Result<Self, ParseError> {
23        Self::parse_advanced::<IndentedTracer>(s, &ParseSettings::default(), ())
24    }
25}
26
27/// The trait that is actually implemented by the generated code.
28/// Should only be used in very specific cases, and [`PegParser`] should be
29/// used in all normal cases.
30pub trait PegParserAdvanced<TUD>: Sized {
31    /// Internal function that is actually generated by the grammar compiler, used by the more
32    /// friendly functions.
33    fn parse_advanced<TT: ParseTracer>(
34        s: &str,
35        settings: &ParseSettings,
36        user_context: TUD,
37    ) -> Result<Self, ParseError>;
38}
39
40/// Parse settings (for future compatibility)
41#[derive(Debug, Default)]
42#[non_exhaustive]
43pub struct ParseSettings {}