6 个版本 (破坏性更新)
| 新功能 0.6.0 | 2024 年 8 月 21 日 |
|---|---|
| 0.5.0 | 2024 年 8 月 21 日 |
| 0.4.0 | 2024 年 8 月 20 日 |
| 0.3.0 | 2024 年 8 月 18 日 |
| 0.1.0 | 2024 年 8 月 18 日 |
248 在 解析工具
每月下载 743 次
在 2 crate 中使用
395KB
7.5K SLoC
RustyLR
yacc 风格的 LR(1) 和 LALR(1) 确定性有限自动机 (DFA) 生成器,从上下文无关语法 (CFG) 生成。
RustyLR 提供了 过程宏 和 构建脚本工具 来生成 LR(1) 和 LALR(1) 解析器。生成的解析器将是纯 Rust 代码,DFA 的计算将在编译时完成。可以编写 Rust 代码来执行减少操作,错误信息是 可读和详细的。对于大型和复杂的语法,建议使用 构建脚本。
features 在 Cargo.toml
build: 启用构建脚本工具。fxhash: 在解析器表中,将std::collections::HashMap替换为FxHashMap(来自rustc-hash)。
示例
// this define `EParser` struct
// where `E` is the start symbol
lr1! {
%userdata i32; // userdata type
%tokentype char; // token type
%start E; // start symbol
%eof '\0'; // eof token
// token definition
%token zero '0';
%token one '1';
%token two '2';
%token three '3';
%token four '4';
%token five '5';
%token six '6';
%token seven '7';
%token eight '8';
%token nine '9';
%token plus '+';
%token star '*';
%token lparen '(';
%token rparen ')';
%token space ' ';
// conflict resolving
%left [plus star]; // reduce first for token 'plus', 'star'
// context-free grammars
Digit(char): [zero-nine]; // character set '0' to '9'
Number(i32) // type assigned to production rule `Number`
: space* Digit+ space* // regex pattern
{ Digit.into_iter().collect::<String>().parse().unwrap() };
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this will be the value of `Number`
// reduce action written in Rust code
A(f32): A plus a2=A {
*data += 1; // access userdata by `data`
println!( "{:?} {:?} {:?}", A, plus, a2 );
A + a2
}
| M
;
M(f32): M star m2=M { M * m2 }
| P
;
P(f32): Number { Number as f32 }
| space* lparen E rparen space* { E }
;
E(f32) : A ;
}
let parser = EParser::new(); // generate `EParser`
let mut context = parser.begin(); // create context
let mut userdata: i32 = 0; // define userdata
let input_sequence = "1 + 2 * ( 3 + 4 )";
// start feeding tokens
for token in input_sequence.chars() {
match parser.feed(&mut context, token, &mut userdata) {
// ^^^^^ ^^^^^^^^^^^^ userdata passed here as `&mut i32`
// feed token
Ok(_) => {}
Err(e) => {
match e {
EParseError::InvalidTerminal(invalid_terminal) => {
...
}
EParseError::ReduceAction(error_from_reduce_action) => {
...
}
}
println!("{}", e);
// println!( "{}", e.long_message( &parser, &context ) );
return;
}
}
}
parser.feed(&mut context, '\0', &mut userdata).unwrap(); // feed `eof` token
let res = context.accept(); // get the value of start symbol
println!("{}", res);
println!("userdata: {}", userdata);
可读的错误信息(带有 codespan)

- 此错误信息由构建脚本工具生成,而不是过程宏。
特性
- 纯 Rust 实现
- 可读的错误信息,包括语法构建和解析
- 从 CFG 在编译时构建 DFA
- 可自定义的减少操作
- 解决歧义语法的冲突
- 部分支持正则表达式模式
- 用于与
build.rs集成的工具
内容
过程宏
以下提供的过程宏
lr1!: 生成 LR(1) 解析器lalr1!: 生成 LALR(1) 解析器
这些宏将生成结构体
Parser: 包含DFA表和产生式规则ParseError: 对Error的类型别名,由feed函数返回Context: 包含当前状态和数据栈enum NonTerminals: 非终结符符号列表Rule: 产生式规则的类型别名State: DFA状态的类型别名
以上所有结构体都以前缀 <StartSymbol> 开头。在大多数情况下,您需要的是 Parser 和 ParseError 结构体,而其他结构体用于内部使用。
与 build.rs 集成
此构建脚本工具将提供比过程宏更详细、格式化的错误消息。如果您正在编写一个庞大、复杂的语法,建议使用构建脚本而不是过程宏。生成的代码将包含与过程宏相同的结构和函数。在您的实际源代码中,您可以 include! 生成文件。
与过程宏不同,程序在输入文件中搜索 %%,而不是 lr1!、lalr1! 宏。在 %% 之前的所有内容将原样复制到输出文件中。并且必须跟在有 %% 的上下文无关文法之后。
// parser.rs
use some_crate::some_module::SomeStruct;
enum SomeTypeDef {
A,
B,
C,
}
%% // <-- input file splitted here
%tokentype u8;
%start E;
%eof b'\0';
%token a b'a';
%token lparen b'(';
%token rparen b')';
E: lparen E rparen
| P
;
P: a;
必须在构建脚本中启用 build 功能才能使用。
[build-dependencies]
rusty_lr = { version = "...", features = ["build"] }
// build.rs
use rusty_lr::build;
fn main() {
println!("cargo::rerun-if-changed=src/parser.rs");
let output = format!("{}/parser.rs", std::env::var("OUT_DIR").unwrap());
build::Builder::new()
.file("src/parser.rs") // path to the input file
// .lalr() // to generate LALR(1) parser
.build(&output); // path to the output file
}
在您的源代码中包含生成的文件。
include!(concat!(env!("OUT_DIR"), "/parser.rs"));
开始解析
Parser 结构体有以下函数
new(): 创建新的解析器begin(&self): 创建新的上下文feed(&self, &mut Context, TerminalType, &mut UserData) -> Result<(), ParseError>: 将令牌喂给解析器
注意,如果未定义 %userdata,则省略参数 &mut UserData。您只需调用 new() 来生成解析器,并调用 begin() 来创建上下文。然后,您可以使用 feed() 函数逐个输入序列。一旦输入序列被输入(包括 eof 标记),如果没有错误,您可以通过调用 context.accept() 获取起始符号的值。
let parser = Parser::new();
let context = parser.begin();
for token in input_sequence {
match parser.feed(&context, token) {
Ok(_) => {}
Err(e) => { // e: ParseError
println!("{}", e);
return;
}
}
}
let start_symbol_value = context.accept();
错误处理
feed() 函数返回两种错误类型
InvalidTerminal(InvalidTerminalError):当输入无效终端符号时ReduceAction(ReduceActionError):当归约动作返回Err(Error)时
对于 ReduceActionError,可以通过 %err 指令定义错误类型。如果未定义,将使用 DefaultReduceActionError。
在打印错误消息时,有两种方法获取错误消息
e.long_message( &parser, &context ):以详细格式获取错误消息作为Stringe as Display:通过Display特性简要打印短消息。
long_message 函数需要解析器和上下文的引用。它将生成当前状态尝试解析的内容和期望的终端符号的详细错误消息。
long_message 的示例
Invalid Terminal: *. Expected one of: , (, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
>>> In:
M -> M * • M
>>> Backtrace:
M -> M • * M
>>> Backtrace:
A -> A + • A
>>> Backtrace:
A -> A • + A
语法
要开始编写上下文无关文法,首先需要定义必要的指令。这是过程宏的语法。
lr1! {
// %directives
// %directives
// ...
// %directives
// NonTerminalSymbol(RuleType): ProductionRules
// NonTerminalSymbol(RuleType): ProductionRules
// ...
}
lr1! 宏将生成具有 LR(1) DFA 表的解析器结构体。如果您想生成 LALR(1) 解析器,请使用 lalr1! 宏。宏中的每一行都必须遵循以下语法。
引导,展开引导是理解语法和生成代码的好例子。这是用 RustyLR 编写的 RustyLR 语法解析器。
快速参考
- 生成规则
- 正则表达式模式
- 规则类型
- 归约动作
- 在归约动作中访问标记数据
- 感叹号
! %tokentype%token%开始%eof%userdata%left,%right%err,%error%derive%derive
生成规则
每个生成规则都有基本形式
NonTerminalName
: Pattern1 Pattern2 ... PatternN { ReduceAction }
| Pattern1 Pattern2 ... PatternN { ReduceAction }
...
;
每个 Pattern 都遵循以下语法
name: 语法中定义的非终结符或终结符name。[term1 term_start-term_last],[^term1 term_start-term_last]: 终结符集。eof将自动从终结符集中移除。P*:P的零次或多次重复。P+:P的一次或多次重复。P?:P的零次或一次重复。(P1 P2 P3): 模式的分组。P / term,P / [term1 term_start-term_last],P / [^term1 term_start-term_last]: 预查;紧跟给定终结符集中的任意一个的P。预查不会被消费。
注意
当使用范围模式 [first-last] 时,范围是通过 %token 指令的顺序构建的,而不是通过令牌的实际值。如果您按以下顺序定义令牌
%token one '1';
%token two '2';
...
%token zero '0';
%token nine '9';
范围 [zero-nine] 将是 ['0', '9'],而不是 ['0'-'9']。
RuleType (可选)
可以为每个非终结符分配一个值。在 reduce action 中,您可以访问每个模式持有的值,并可以为当前的非终结符分配新值。请参阅下面的 ReduceAction 和 在 ReduceAction 中访问令牌数据 部分。解析结束时,起始符号的值将是解析的结果。默认情况下,终结符持有由 feed() 函数传递的 %tokentype 的值。
struct MyType<T> {
...
}
E(MyType<i32>) : ... Patterns ... { <This will be new value of E> } ;
ReduceAction (可选)
Reduce action 可以用 Rust 代码编写。它在规则匹配和减少时执行。
-
如果为当前非终结符定义了
RuleType,则ReduceAction本身必须是RuleType的值(即语句结尾没有分号)。 -
如果
RuleType未定义,则可以省略ReduceAction。- 产生式规则中只有一个令牌持有值。
-
Result<(),Error>可以从ReduceAction返回。- 返回的
Error将传递给feed()函数的调用者。 ErrorType可以通过%err或%error指令定义。请参阅 错误类型 部分。
- 返回的
NoRuleType: ... ;
RuleTypeI32(i32): ... { 0 } ;
// RuleTypeI32 will be chosen
E(i32): NoRuleType NoRuleType RuleTypeI32 NoRuleType;
// set Err variant type to String
%err String;
%token div '/';
E(i32): A div a2=A {
if a2 == 0 {
return Err("Division by zero".to_string());
}
A / a2
};
A(i32): ... ;
在归约动作中访问标记数据
预定义变量 可以在 ReduceAction 中使用。
data: 传递给feed()函数的用户数据。
要访问每个标记的数据,可以直接使用标记的名称作为变量。
- 对于非终结符号,变量的类型是
RuleType。 - 对于终结符号,变量的类型是
%tokentype。 - 如果定义了多个同名的变量,则使用最前面的变量。
- 您可以通过使用
=运算符来重命名变量。
E(i32) : A plus a2=A {
println!("Value of A: {:?}", A);
println!("Value of plus: {:?}", plus);
println!("Value of a2: {:?}", a2);
A + a2 // new value of E
};
对于某些正则表达式模式,变量的类型将按以下方式修改
P*:Vec<P>P+:Vec<P>P?:Option<P>
您仍然可以通过使用模式的基名来访问 Vec 或 Option。
E(i32) : A* {
println!( "Value of A: {:?}", A ); // Vec<A>
};
对于终结符集合 [term1 term_start-term_end],[^term1 term_start-term_end],没有预定义的变量名。您必须明确定义变量名。
E: digit=[zero-nine] {
println!( "Value of digit: {:?}", digit ); // %tokentype
};
对于组 (P1 P2 P3)
- 如果没有任何模式持有值,则组本身不会持有任何值。
- 如果只有一个模式持有值,则组将持有该模式的值。变量名将与模式相同。(例如,如果
P1持有值,而其他不持有,则(P1 P2 P3)将持有P1的值,并且可以通过名称P1访问) - 如果有多个模式持有值,则组将持有值的
Tuple。组没有默认变量名,您必须通过=运算符显式定义变量名。
NoRuleType: ... ;
I(i32): ... ;
// I will be chosen
A: (NoRuleType I NoRuleType) {
println!( "Value of I: {:?}", I ); // can access by 'I'
I
};
// ( i32, i32 )
B: i2=( I NoRuleType I ) {
println!( "Value of I: {:?}", i2 ); // must explicitly define the variable name
};
感叹号 !
可以在标记后直接使用感叹号 ! 来忽略标记的值。该标记将被视为不持有任何值。
A(i32) : ... ;
// A in the middle will be chosen, since other A's are ignored
E(i32) : A! A A!;
标记类型 (必须定义)
%tokentype <RustType> ;
定义终端符号的类型。 <RustType> 必须在调用宏的地方可访问。
enum MyTokenType<Generic> {
Digit,
Ident,
...
VariantWithGeneric<Generic>
}
lr! {
...
%tokentype MyTokenType<i32>;
}
令牌定义 (必须定义)
%token name <RustExpr> ;
将终端符号 name 映射到实际值 <RustExpr>。 <RustExpr> 必须在调用宏的地方可访问。
%tokentype u8;
%token zero b'0';
%token one b'1';
...
// 'zero' and 'one' will be replaced by b'0' and b'1' respectively
E: zero one;
起始符号 (必须定义)
%start NonTerminalName ;
将语法的起始符号设置为 NonTerminalName。
%start E;
// this internally generate augmented rule <Augmented> -> E eof
E: ... ;
Eof 符号 (必须定义)
%eof <RustExpr> ;
定义 eof 终端符号。 <RustExpr> 必须在调用宏的地方可访问。'eof' 终端符号将自动添加到语法中。
%eof b'\0';
// you can access eof terminal symbol by 'eof' in the grammar
// without %token eof ...;
用户数据类型 (可选)
%userdata <RustType> ;
定义传递给 feed() 函数的用户数据类型。
struct MyUserData { ... }
...
%userdata MyUserData;
...
fn main() {
...
let mut userdata = MyUserData { ... };
parser.feed( ..., token, &mut userdata); // <-- userdata feed here
}
归约类型 (可选)
// reduce first
%left term1 ;
%left [term1 term_start-term_last] ;
// shift first
%right term1 ;
%right [term1 term_start-term_last] ;
设置终端符号的移位/归约优先级。 %left 可以缩写为 %reduce 或 %l,而 %right 可以缩写为 %shift 或 %r。
// define tokens
%token plus '+';
%token hat '^';
// reduce first for token 'plus'
%left plus;
// shift first for token 'hat'
%right hat;
错误类型 (可选)
%err <RustType> ;
%error <RustType> ;
定义从 ReduceAction 返回的 Result<(), Err> 返回的 Err 变量的类型。如果没有定义,将使用 DefaultReduceActionError。
enum MyErrorType<T> {
ErrVar1,
ErrVar2,
ErrVar3(T),
}
...
%err MyErrorType<GenericType> ;
...
match parser.feed( ... ) {
Ok(_) => {}
Err(err) => {
match err {
ParseError::ReduceAction( err ) => {
// do something with err
}
_ => {}
}
}
}
推导 (可选)
指定生成 Context 结构的 derive 属性。默认情况下,生成的 Context 不实现任何特质。但在某些情况下,您可能希望推导出特质,如 Clone、Debug 或 Serialize、Deserialize 的 serde。
在这种情况下,用户必须确保 Context 的每个成员都实现该特质。目前,Context 正在保留堆栈数据,这是状态堆栈的 Vec<usize> 和语法中每个 RuleType 的 Vec<T>。
%derive Clone, Debug, serde::Serialize ;
// here, #[derive(Clone,Debug)] will be added to the generated `Context` struct
%derive Clone, Debug;
...
let mut context = parser.begin();
// do something with context...
println!( "{:?}", context ); // debug-print context
let cloned_context = context.clone(); // clone context, you can re-feed the input sequence using cloned context
依赖关系
~0.5–7.5MB
~42K SLoC