Function to parse expressions based on assosicavity and precedence
- Dominant language
- Zig
- Stars
- 609
- Forks
- 30
- PR merge metrics
- No merged PRs in 30d
Description
`mecha` should provide parsers that can parse infix binary expressions based on based on assosicavity and precedence. It is possible to write these out by hand (as can be seen in [example/math.zig](https://github.com/Hejsil/mecha/blob/master/example/math.zig)) but the pattern is so common, that a dedicate function can save quite a bit of code and make it a lot easier to implement.
I suggest an API along the lines of [this](https://docs.rs/combine-language/3.0.1/combine_language/fn.expression_parser.html). Translated into `mecha`, the function would look this this:
```zig
pub const Associativity = enum {
left,
right,
};
pub fn Operator(comptime T: type) type {
return struct {
value: T,
precedence: i32,
associativity: Associativity,
};
}
/// Construct a parser that parses infix binary expressions based on associativity and precedence.
/// The parser will go over the string, parsing any terminators (using the `term` parser) and operators
/// (using the `operator` parser). Once a left and right side of an operator has been determined, a
/// result will be constructed using the `result` function. The way results are constructed depends
/// on the associativity and precedence returned by the `operator` parser.
pub fn expressionParser(
/// Parser(T): Parses the terms of the expression
term: anytype,
/// Parser(Operator(O)): Parses the operators returns the operators precedence and associativity
operator: anytype,
/// fn(T, Operator(O), T) T: Constructs the results of parsing the expressions. "1 + 1" -> result(1, "+", 1) -> 2
result: *const fn(ParserResult(@TypeOf(term)), ParserResult(@TypeOf(operator)), ParserResult(@TypeOf(term))) ParserResult(@TypeOf(term)),
) Parser(ParserResult(@TypeOf(term)) {
...
}
```
Contributor guide
No contributing guide indexed for this repository
Assessment
This issue has not been assessed yet.