| 1 |
//! Main points of the `c_expression` example: |
| 2 |
//! |
| 3 |
//! 1. [`Expr`], representing the AST of C-style expressions |
| 4 |
//! 2. [`pratt_parser()`], the core parser. |
| 5 |
//! 3. The [`test`]s, which demonstrate the expected input/outputs. |
| 6 |
//! |
| 7 |
//! There is one [`parse_example()`] function in this file, but the |
| 8 |
//! associated test module for this example shows the other inputs/outputs. |
| 9 |
//! |
| 10 |
//! # Errata: |
| 11 |
//! - There is a helper parser, [`identifier()`] |
| 12 |
//! - Two print implementations: [`Expr::fmt_ast_with_indent()`] and [`Expr::fmt_delimited()`] |
| 13 |
//! - For operator precedence, `1` has a low binding power while `13` has a high binding power. |
| 14 |
//! |
| 15 |
//! ## Printing |
| 16 |
//! |
| 17 |
//! `fmt_delimited()` is essentially prefix-notation. |
| 18 |
//! |
| 19 |
//! A short visual about the differences in printing, for parsing `1 + 1`: |
| 20 |
//! |
| 21 |
//! `fmt_ast_with_indent()` = |
| 22 |
//! ~~~text |
| 23 |
//! ADD |
| 24 |
//! VAL 1 |
| 25 |
//! VAL 1 |
| 26 |
//! ~~~ |
| 27 |
//! |
| 28 |
//! `fmt_delimited()` = |
| 29 |
//! ~~~text |
| 30 |
//! (+ 1 1) |
| 31 |
//! ~~~ |
| 32 |
//! |
| 33 |
//! ## Precedences |
| 34 |
//! |
| 35 |
//! Values uses an *inverted form* of the [C language operator precedence](c-precedence). |
| 36 |
//! |
| 37 |
//! In our implementation, a precedence of `1` is a very low precedence compared |
| 38 |
//! to a value of `13`. |
| 39 |
//! |
| 40 |
//! In the linked C operator page, the table shows precedence in *descending precedence order*, |
| 41 |
//! so `1` is the highest precedence, while `13` is a low precedence. |
| 42 |
//! |
| 43 |
//! The precedence levels you have to choose for your grammar depend on the language's |
| 44 |
//! semantics. |
| 45 |
//! |
| 46 |
//! [c-precedence]: https://en.cppreference.com/w/c/language/operator_precedence.html |
| 47 |
//! |
| 48 |
//! ### Precedence Table |
| 49 |
//! |
| 50 |
//! An overview of the different operators for this C-style expression language. |
| 51 |
//! |
| 52 |
//! Note: this does not include the operands themselves, such as literals or |
| 53 |
//! parenthesized expressions like: `(x)` |
| 54 |
//! |
| 55 |
//! Legend: |
| 56 |
//! - Kind: one of Prefix, Postfix, or Infix |
| 57 |
//! - Example: input text example |
| 58 |
//! - Name: the [`Expr`] variant it corresponds to |
| 59 |
//! - Power: the binding power/precedence of the operator |
| 60 |
//! - Assoc: infix-only, represents the left/right associativity of an operator |
| 61 |
//! - Recursive: only "TRUE" if parsing the operand invokes the parser again |
| 62 |
//! |
| 63 |
//! | Kind | Example | Name | Power | Assoc | Recursive | |
| 64 |
//! |---------|------------|------------------|-------|---------|-----------| |
| 65 |
//! | Prefix | `++x` | PreIncr | 18 | | | |
| 66 |
//! | Prefix | `+x` | Positive (no-op) | 18 | | | |
| 67 |
//! | Prefix | `--x` | PreDecr | 18 | | | |
| 68 |
//! | Prefix | `-x` | Neg | 18 | | | |
| 69 |
//! | Prefix | `&x` | Addr | 18 | | | |
| 70 |
//! | Prefix | `*x` | Deref | 18 | | | |
| 71 |
//! | Prefix | `!x` | Not | 18 | | | |
| 72 |
//! | Prefix | `~x` | BitwiseNot | 18 | | | |
| 73 |
//! | Postfix | `x!` | Fac | 19 | | | |
| 74 |
//! | Postfix | `x?` | Ternary | 3 | | TRUE | |
| 75 |
//! | Postfix | `[x]` | Index | 20 | | TRUE | |
| 76 |
//! | Postfix | `(x)` | Function call | 20 | | TRUE | |
| 77 |
//! | Postfix | `x++` | PostIncr | 20 | | | |
| 78 |
//! | Postfix | `x--` | PostDecr | 20 | | | |
| 79 |
//! | Infix | `a ** b` | Pow | 28 | Right | | |
| 80 |
//! | Infix | `a * b` | Mul | 16 | Left | | |
| 81 |
//! | Infix | `a / b` | Div | 16 | Left | | |
| 82 |
//! | Infix | `a % b` | Rem | 16 | Left | | |
| 83 |
//! | Infix | `a + b` | Add | 14 | Left | | |
| 84 |
//! | Infix | `a -ne b` | NotEq | 10 | Neither | | |
| 85 |
//! | Infix | `a -eq b` | Eq | 10 | Neither | | |
| 86 |
//! | Infix | `a -gt b` | Greater | 12 | Neither | | |
| 87 |
//! | Infix | `a -ge b` | GreaterEq | 12 | Neither | | |
| 88 |
//! | Infix | `a -lt b` | Less | 12 | Neither | | |
| 89 |
//! | Infix | `a -le b` | LessEqual | 12 | Neither | | |
| 90 |
//! | Infix | `a->b` | ArrowOp | 20 | Left | | |
| 91 |
//! | Infix | `a - b` | Sub | 14 | Left | | |
| 92 |
//! | Infix | `a.b` | Dot | 20 | Left | | |
| 93 |
//! | Infix | `a && b` | And | 6 | Left | | |
| 94 |
//! | Infix | `a & b` | BitAnd | 12 | Left | | |
| 95 |
//! | Infix | `a ^ b` | BitXor | 8 | Left | | |
| 96 |
//! | Infix | `a == b` | Eq | 10 | Neither | | |
| 97 |
//! | Infix | `a = b` | Assign | 2 | Right | | |
| 98 |
//! | Infix | `a >= b` | GreaterEq | 12 | Neither | | |
| 99 |
//! | Infix | `a > b` | Greater | 12 | Neither | | |
| 100 |
//! | Infix | `a <= b` | LessEqual | 12 | Neither | | |
| 101 |
//! | Infix | `a < b` | Less | 12 | Neither | | |
| 102 |
//! | Infix | `a, b` | Comma | 0 | Left | | |
| 103 |
//! | Infix | `a != b` | NotEq | 10 | Neither | | |
| 104 |
//! | Infix | `a \|\| b` | Or | 4 | Left | | |
| 105 |
|
| 106 |
use winnow::ascii::{digit1, multispace0}; |
| 107 |
use winnow::combinator::{ |
| 108 |
alt, cut_err, delimited, expression, fail, not, opt, peek, separated_pair, trace, |
| 109 |
}; |
| 110 |
use winnow::combinator::{Infix, Postfix, Prefix}; |
| 111 |
use winnow::dispatch; |
| 112 |
use winnow::error::{ContextError, ErrMode}; |
| 113 |
use winnow::prelude::*; |
| 114 |
use winnow::token::{any, one_of, take, take_while}; |
| 115 |
|
| 116 |
#[test] |
| 117 |
fn parse_example() { |
| 118 |
// Check out the [`crate::parser::test`] in this example for more samples. |
| 119 |
let result = pratt_parser |
| 120 |
.parse("a*a + b - c") |
| 121 |
.map(|r| format!("{}", r)) |
| 122 |
.unwrap(); |
| 123 |
|
| 124 |
let expect = "\ |
| 125 |
SUB |
| 126 |
ADD |
| 127 |
MUL |
| 128 |
NAME a |
| 129 |
NAME a |
| 130 |
NAME b |
| 131 |
NAME c |
| 132 |
|
| 133 |
(- (+ (* a a) b) c)"; |
| 134 |
|
| 135 |
assert_eq!(result, expect); |
| 136 |
} |
| 137 |
|
| 138 |
// Abstract syntax tree for an expression |
| 139 |
pub(crate) enum Expr { |
| 140 |
Name(String), |
| 141 |
Value(i64), |
| 142 |
|
| 143 |
Assign(Box<Expr>, Box<Expr>), |
| 144 |
|
| 145 |
Addr(Box<Expr>), |
| 146 |
Deref(Box<Expr>), |
| 147 |
|
| 148 |
Dot(Box<Expr>, Box<Expr>), |
| 149 |
ArrowOp(Box<Expr>, Box<Expr>), |
| 150 |
Neg(Box<Expr>), |
| 151 |
Add(Box<Expr>, Box<Expr>), |
| 152 |
Sub(Box<Expr>, Box<Expr>), |
| 153 |
Mul(Box<Expr>, Box<Expr>), |
| 154 |
Div(Box<Expr>, Box<Expr>), |
| 155 |
Pow(Box<Expr>, Box<Expr>), |
| 156 |
Fac(Box<Expr>), |
| 157 |
|
| 158 |
PreIncr(Box<Expr>), |
| 159 |
PostIncr(Box<Expr>), |
| 160 |
PreDecr(Box<Expr>), |
| 161 |
PostDecr(Box<Expr>), |
| 162 |
|
| 163 |
And(Box<Expr>, Box<Expr>), |
| 164 |
Or(Box<Expr>, Box<Expr>), |
| 165 |
|
| 166 |
// `==` |
| 167 |
Eq(Box<Expr>, Box<Expr>), |
| 168 |
// `!=` |
| 169 |
NotEq(Box<Expr>, Box<Expr>), |
| 170 |
// `!` |
| 171 |
Not(Box<Expr>), |
| 172 |
Greater(Box<Expr>, Box<Expr>), |
| 173 |
GreaterEqual(Box<Expr>, Box<Expr>), |
| 174 |
Less(Box<Expr>, Box<Expr>), |
| 175 |
LessEqual(Box<Expr>, Box<Expr>), |
| 176 |
|
| 177 |
// A parenthesized expression. |
| 178 |
Paren(Box<Expr>), |
| 179 |
FunctionCall(Box<Expr>, Option<Box<Expr>>), |
| 180 |
Ternary(Box<Expr>, Box<Expr>, Box<Expr>), |
| 181 |
// foo[...] |
| 182 |
Index(Box<Expr>, Box<Expr>), |
| 183 |
// a, b |
| 184 |
Comma(Box<Expr>, Box<Expr>), |
| 185 |
|
| 186 |
// % |
| 187 |
Rem(Box<Expr>, Box<Expr>), |
| 188 |
BitXor(Box<Expr>, Box<Expr>), |
| 189 |
BitAnd(Box<Expr>, Box<Expr>), |
| 190 |
BitwiseNot(Box<Expr>), |
| 191 |
} |
| 192 |
|
| 193 |
/// Parser definition |
| 194 |
/// |
| 195 |
/// We define a helper function `parser()` and call it at the very end. |
| 196 |
/// |
| 197 |
/// `parser()` accepts a minimum `precedence_level` for the entire expression, |
| 198 |
/// and it returns a [`Parser`] that takes in a string and returns an [`Expr`] on |
| 199 |
/// success. |
| 200 |
pub(crate) fn pratt_parser(i: &mut &str) -> ModalResult<Expr> { |
| 201 |
fn parser<'i>(precedence: i64) -> impl Parser<&'i str, Expr, ErrMode<ContextError>> { |
| 202 |
move |i: &mut &str| { |
| 203 |
use Infix::{Left, Neither, Right}; |
| 204 |
expression( |
| 205 |
// parsing an operand, optionally surrounded by whitespace |
| 206 |
delimited( |
| 207 |
multispace0, |
| 208 |
dispatch! {peek(any); |
| 209 |
// Case one: Parenthesized expression |
| 210 |
'(' => delimited('(', parser(0).map(|e| Expr::Paren(Box::new(e))), cut_err(')')), |
| 211 |
_ => alt(( |
| 212 |
// Case two: A C-style identifier |
| 213 |
identifier.map(|s| Expr::Name(s.into())), |
| 214 |
// Case three: An integer |
| 215 |
digit1.parse_to::<i64>().map(Expr::Value) |
| 216 |
)), |
| 217 |
}, |
| 218 |
multispace0, |
| 219 |
) |
| 220 |
) |
| 221 |
.current_precedence_level(precedence) |
| 222 |
.prefix( |
| 223 |
// parsing prefix operators, optionally surrounded by whitespace |
| 224 |
// for example: `++1` |
| 225 |
// ||^ operand, called `a` below |
| 226 |
// ^^ prefix 'pre-increment' operator |
| 227 |
delimited( |
| 228 |
multispace0, |
| 229 |
dispatch! {any; |
| 230 |
'+' => alt(( |
| 231 |
// ++ |
| 232 |
'+'.value(Prefix(18, |_: &mut _, a| Ok(Expr::PreIncr(Box::new(a))))), |
| 233 |
Prefix(18, |_: &mut _, a| Ok(a) ) |
| 234 |
)), |
| 235 |
'-' => alt(( |
| 236 |
// -- |
| 237 |
'-'.value(Prefix(18, |_: &mut _, a| Ok(Expr::PreDecr(Box::new(a))))), |
| 238 |
Prefix(18, |_: &mut _, a| Ok(Expr::Neg(Box::new(a)))) |
| 239 |
)), |
| 240 |
'&' => Prefix(18, |_: &mut _, a| Ok(Expr::Addr(Box::new(a)))), |
| 241 |
'*' => Prefix(18, |_: &mut _, a| Ok(Expr::Deref(Box::new(a)))), |
| 242 |
'!' => Prefix(18, |_: &mut _, a| Ok(Expr::Not(Box::new(a)))), |
| 243 |
'~' => Prefix(18, |_: &mut _, a| Ok(Expr::BitwiseNot(Box::new(a)))), |
| 244 |
_ => fail |
| 245 |
}, |
| 246 |
multispace0, |
| 247 |
) |
| 248 |
) |
| 249 |
.postfix( |
| 250 |
// parsing postfix operators, optionally surrounded by whitespace |
| 251 |
// for example: `(1 == 1) ? 100 : 0` |
| 252 |
// |||||||| | \\\\\\\\___ remainder of the input, called `i` below |
| 253 |
// |||||||| ^ postfix ternary operator |
| 254 |
// ^^^^^^^^ operand, called `cond` below |
| 255 |
delimited( |
| 256 |
multispace0, |
| 257 |
alt(( |
| 258 |
dispatch! {any; |
| 259 |
'!' => not('=').value(Postfix(19, |_: &mut _, a| Ok(Expr::Fac(Box::new(a))))), |
| 260 |
'?' => Postfix(3, |i: &mut &str, cond| { |
| 261 |
let (left, right) = cut_err(separated_pair(parser(0), delimited(multispace0, ':', multispace0), parser(3))).parse_next(i)?; |
| 262 |
Ok(Expr::Ternary(Box::new(cond), Box::new(left), Box::new(right))) |
| 263 |
}), |
| 264 |
'[' => Postfix(20, |i: &mut &str, a| { |
| 265 |
let index = delimited(multispace0, parser(0), (multispace0, cut_err(']'), multispace0)).parse_next(i)?; |
| 266 |
Ok(Expr::Index(Box::new(a), Box::new(index))) |
| 267 |
}), |
| 268 |
'(' => Postfix(20, |i: &mut &str, a| { |
| 269 |
let args = delimited(multispace0, opt(parser(0)), (multispace0, cut_err(')'), multispace0)).parse_next(i)?; |
| 270 |
Ok(Expr::FunctionCall(Box::new(a), args.map(Box::new))) |
| 271 |
}), |
| 272 |
_ => fail, |
| 273 |
}, |
| 274 |
dispatch! {take(2usize); |
| 275 |
"++" => Postfix(20, |_: &mut _, a| Ok(Expr::PostIncr(Box::new(a)))), |
| 276 |
"--" => Postfix(20, |_: &mut _, a| Ok(Expr::PostDecr(Box::new(a)))), |
| 277 |
_ => fail, |
| 278 |
}, |
| 279 |
)), |
| 280 |
multispace0, |
| 281 |
), |
| 282 |
) |
| 283 |
.infix( |
| 284 |
// parsing infix operators |
| 285 |
// |
| 286 |
// we do not need to deal with whitespace here, it would be redundant |
| 287 |
// since the operands already ignore whitespace |
| 288 |
// |
| 289 |
// an example infix operator: `123 + 456` |
| 290 |
// operand, called `a` ^^^ | ^^^ operand, called `b` below |
| 291 |
// | |
| 292 |
// ^ infix addition operator |
| 293 |
alt(( |
| 294 |
dispatch! {any; |
| 295 |
'*' => alt(( |
| 296 |
// ** |
| 297 |
"*".value(Right(28, |_: &mut _, a, b| Ok(Expr::Pow(Box::new(a), Box::new(b))))), |
| 298 |
Left(16, |_: &mut _, a, b| Ok(Expr::Mul(Box::new(a), Box::new(b)))), |
| 299 |
)), |
| 300 |
'/' => Left(16, |_: &mut _, a, b| Ok(Expr::Div(Box::new(a), Box::new(b)))), |
| 301 |
'%' => Left(16, |_: &mut _, a, b| Ok(Expr::Rem(Box::new(a), Box::new(b)))), |
| 302 |
|
| 303 |
'+' => Left(14, |_: &mut _, a, b| Ok(Expr::Add(Box::new(a), Box::new(b)))), |
| 304 |
'-' => alt(( |
| 305 |
dispatch!{take(2usize); |
| 306 |
"ne" => Neither(10, |_: &mut _, a, b| Ok(Expr::NotEq(Box::new(a), Box::new(b)))), |
| 307 |
"eq" => Neither(10, |_: &mut _, a, b| Ok(Expr::Eq(Box::new(a), Box::new(b)))), |
| 308 |
"gt" => Neither(12, |_: &mut _, a, b| Ok(Expr::Greater(Box::new(a), Box::new(b)))), |
| 309 |
"ge" => Neither(12, |_: &mut _, a, b| Ok(Expr::GreaterEqual(Box::new(a), Box::new(b)))), |
| 310 |
"lt" => Neither(12, |_: &mut _, a, b| Ok(Expr::Less(Box::new(a), Box::new(b)))), |
| 311 |
"le" => Neither(12, |_: &mut _, a, b| Ok(Expr::LessEqual(Box::new(a), Box::new(b)))), |
| 312 |
_ => fail |
| 313 |
}, |
| 314 |
'>'.value(Left(20, |_: &mut _, a, b| Ok(Expr::ArrowOp(Box::new(a), Box::new(b))))), |
| 315 |
Left(14, |_: &mut _, a, b| Ok(Expr::Sub(Box::new(a), Box::new(b)))) |
| 316 |
)), |
| 317 |
'.' => Left(20, |_: &mut _, a, b| Ok(Expr::Dot(Box::new(a), Box::new(b)))), |
| 318 |
'&' => alt(( |
| 319 |
// && |
| 320 |
"&".value(Left(6, |_: &mut _, a, b| Ok(Expr::And(Box::new(a), Box::new(b))))), |
| 321 |
|
| 322 |
Left(12, |_: &mut _, a, b| Ok(Expr::BitAnd(Box::new(a), Box::new(b)))), |
| 323 |
)), |
| 324 |
'^' => Left(8, |_: &mut _, a, b| Ok(Expr::BitXor(Box::new(a), Box::new(b)))), |
| 325 |
'=' => alt(( |
| 326 |
// == |
| 327 |
"=".value(Neither(10, |_: &mut _, a, b| Ok(Expr::Eq(Box::new(a), Box::new(b))))), |
| 328 |
Right(2, |_: &mut _, a, b| Ok(Expr::Assign(Box::new(a), Box::new(b)))) |
| 329 |
)), |
| 330 |
|
| 331 |
'>' => alt(( |
| 332 |
// >= |
| 333 |
"=".value(Neither(12, |_: &mut _, a, b| Ok(Expr::GreaterEqual(Box::new(a), Box::new(b))))), |
| 334 |
Neither(12, |_: &mut _, a, b| Ok(Expr::Greater(Box::new(a), Box::new(b)))) |
| 335 |
)), |
| 336 |
'<' => alt(( |
| 337 |
// <= |
| 338 |
"=".value(Neither(12, |_: &mut _, a, b| Ok(Expr::LessEqual(Box::new(a), Box::new(b))))), |
| 339 |
Neither(12, |_: &mut _, a, b| Ok(Expr::Less(Box::new(a), Box::new(b)))) |
| 340 |
)), |
| 341 |
',' => Left(0, |_: &mut _, a, b| Ok(Expr::Comma(Box::new(a), Box::new(b)))), |
| 342 |
_ => fail |
| 343 |
}, |
| 344 |
dispatch! {take(2usize); |
| 345 |
"!=" => Neither(10, |_: &mut _, a, b| Ok(Expr::NotEq(Box::new(a), Box::new(b)))), |
| 346 |
"||" => Left(4, |_: &mut _, a, b| Ok(Expr::Or(Box::new(a), Box::new(b)))), |
| 347 |
_ => fail |
| 348 |
}, |
| 349 |
)), |
| 350 |
) |
| 351 |
.parse_next(i) |
| 352 |
} |
| 353 |
} |
| 354 |
|
| 355 |
parser(0).parse_next(i) |
| 356 |
} |
| 357 |
|
| 358 |
// Helper parsers |
| 359 |
|
| 360 |
fn identifier<'i>(i: &mut &'i str) -> ModalResult<&'i str> { |
| 361 |
trace( |
| 362 |
"identifier", |
| 363 |
( |
| 364 |
one_of(|c: char| c.is_alpha() || c == '_'), |
| 365 |
take_while(0.., |c: char| c.is_alphanum() || c == '_'), |
| 366 |
), |
| 367 |
) |
| 368 |
.take() |
| 369 |
.parse_next(i) |
| 370 |
} |
| 371 |
|
| 372 |
// Formatted print implementations |
| 373 |
impl Expr { |
| 374 |
fn fmt_ast_with_indent( |
| 375 |
&self, |
| 376 |
indent: u32, |
| 377 |
f: &mut core::fmt::Formatter<'_>, |
| 378 |
) -> core::fmt::Result { |
| 379 |
for _ in 0..indent { |
| 380 |
write!(f, " ")?; |
| 381 |
} |
| 382 |
macro_rules! binary_fmt { |
| 383 |
($a:ident, $b:ident, $name:literal) => {{ |
| 384 |
writeln!(f, $name)?; |
| 385 |
$a.fmt_ast_with_indent(indent + 1, f)?; |
| 386 |
$b.fmt_ast_with_indent(indent + 1, f) |
| 387 |
}}; |
| 388 |
} |
| 389 |
macro_rules! unary_fmt { |
| 390 |
($a:ident, $name:literal) => {{ |
| 391 |
writeln!(f, $name)?; |
| 392 |
$a.fmt_ast_with_indent(indent + 1, f) |
| 393 |
}}; |
| 394 |
} |
| 395 |
match self { |
| 396 |
Self::Name(name) => writeln!(f, "NAME {name}"), |
| 397 |
Self::Value(value) => writeln!(f, "VAL {value}"), |
| 398 |
Self::Addr(a) => unary_fmt!(a, "ADDR"), |
| 399 |
Self::Deref(a) => unary_fmt!(a, "DEREF"), |
| 400 |
Self::Neg(a) => unary_fmt!(a, "NEG"), |
| 401 |
Self::Fac(a) => unary_fmt!(a, "FAC"), |
| 402 |
Self::PreIncr(a) => unary_fmt!(a, "PRE_INCR"), |
| 403 |
Self::PostIncr(a) => unary_fmt!(a, "POST_INCR"), |
| 404 |
Self::PreDecr(a) => unary_fmt!(a, "PRE_DECR"), |
| 405 |
Self::PostDecr(a) => unary_fmt!(a, "POST_DECR"), |
| 406 |
Self::Not(a) => unary_fmt!(a, "NOT"), |
| 407 |
Self::BitwiseNot(a) => unary_fmt!(a, "BIT_NOT"), |
| 408 |
Self::Paren(a) => unary_fmt!(a, "PAREN"), |
| 409 |
Self::Assign(a, b) => binary_fmt!(a, b, "ASSIGN"), |
| 410 |
Self::ArrowOp(a, b) => binary_fmt!(a, b, "ARROW"), |
| 411 |
Self::Dot(a, b) => binary_fmt!(a, b, "ARROW"), |
| 412 |
Self::FunctionCall(a, b) => { |
| 413 |
writeln!(f, "CALL")?; |
| 414 |
a.fmt_ast_with_indent(indent + 1, f)?; |
| 415 |
if let Some(b) = b { |
| 416 |
b.fmt_ast_with_indent(indent + 1, f)?; |
| 417 |
} |
| 418 |
Ok(()) |
| 419 |
} |
| 420 |
Self::Add(a, b) => binary_fmt!(a, b, "ADD"), |
| 421 |
Self::Sub(a, b) => binary_fmt!(a, b, "SUB"), |
| 422 |
Self::Mul(a, b) => binary_fmt!(a, b, "MUL"), |
| 423 |
Self::Div(a, b) => binary_fmt!(a, b, "DIV"), |
| 424 |
Self::Pow(a, b) => binary_fmt!(a, b, "POW"), |
| 425 |
Self::And(a, b) => binary_fmt!(a, b, "AND"), |
| 426 |
Self::Or(a, b) => binary_fmt!(a, b, "OR"), |
| 427 |
Self::Eq(a, b) => binary_fmt!(a, b, "EQ"), |
| 428 |
Self::NotEq(a, b) => binary_fmt!(a, b, "NEQ"), |
| 429 |
Self::Greater(a, b) => binary_fmt!(a, b, "GREATER"), |
| 430 |
Self::GreaterEqual(a, b) => binary_fmt!(a, b, "GTEQ"), |
| 431 |
Self::Less(a, b) => binary_fmt!(a, b, "LESS"), |
| 432 |
Self::LessEqual(a, b) => binary_fmt!(a, b, "LESSEQ"), |
| 433 |
Self::BitXor(a, b) => binary_fmt!(a, b, "BIT_XOR"), |
| 434 |
Self::Rem(a, b) => binary_fmt!(a, b, "REM"), |
| 435 |
Self::BitAnd(a, b) => binary_fmt!(a, b, "BIT_AND"), |
| 436 |
Self::Index(a, b) => binary_fmt!(a, b, "INDEX"), |
| 437 |
Self::Comma(a, b) => binary_fmt!(a, b, "COMMA"), |
| 438 |
Self::Ternary(cond, a, b) => { |
| 439 |
writeln!(f, "TERNARY")?; |
| 440 |
cond.fmt_ast_with_indent(indent + 1, f)?; |
| 441 |
a.fmt_ast_with_indent(indent + 2, f)?; |
| 442 |
b.fmt_ast_with_indent(indent + 2, f) |
| 443 |
} |
| 444 |
} |
| 445 |
} |
| 446 |
fn fmt_delimited(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { |
| 447 |
match self { |
| 448 |
Self::Name(name) => return write!(f, "{name}"), |
| 449 |
Self::Value(value) => return write!(f, "{value}"), |
| 450 |
Self::Paren(a) => return a.fmt_delimited(f), |
| 451 |
_ => (), |
| 452 |
} |
| 453 |
macro_rules! unary { |
| 454 |
($op:literal, $a:ident) => {{ |
| 455 |
write!(f, $op)?; |
| 456 |
$a.fmt_delimited(f)?; |
| 457 |
}}; |
| 458 |
} |
| 459 |
macro_rules! binary { |
| 460 |
($op:literal, $a:ident, $b:ident) => {{ |
| 461 |
write!(f, "{} ", $op)?; |
| 462 |
$a.fmt_delimited(f)?; |
| 463 |
write!(f, " ")?; |
| 464 |
$b.fmt_delimited(f)?; |
| 465 |
}}; |
| 466 |
} |
| 467 |
write!(f, "(")?; |
| 468 |
match self { |
| 469 |
Self::Assign(a, b) => binary!("=", a, b), |
| 470 |
Self::FunctionCall(a, b) => { |
| 471 |
write!(f, "call ")?; |
| 472 |
a.fmt_delimited(f)?; |
| 473 |
if let Some(b) = b { |
| 474 |
write!(f, " ")?; |
| 475 |
b.fmt_delimited(f)?; |
| 476 |
} |
| 477 |
} |
| 478 |
Self::ArrowOp(a, b) => binary!("->", a, b), |
| 479 |
Self::Dot(a, b) => binary!(".", a, b), |
| 480 |
Self::Addr(a) => unary!("&", a), |
| 481 |
Self::Deref(a) => unary!("*", a), |
| 482 |
Self::Neg(a) => unary!("-", a), |
| 483 |
Self::Fac(a) => unary!("!", a), |
| 484 |
Self::Not(a) => unary!("!", a), |
| 485 |
Self::BitwiseNot(a) => unary!("~", a), |
| 486 |
Self::PreIncr(a) => unary!("pre++", a), |
| 487 |
Self::PostIncr(a) => unary!("post++", a), |
| 488 |
Self::PreDecr(a) => unary!("pre--", a), |
| 489 |
Self::PostDecr(a) => unary!("post--", a), |
| 490 |
Self::Add(a, b) => binary!("+", a, b), |
| 491 |
Self::Sub(a, b) => binary!("-", a, b), |
| 492 |
Self::Mul(a, b) => binary!("*", a, b), |
| 493 |
Self::Div(a, b) => binary!("/", a, b), |
| 494 |
Self::Pow(a, b) => binary!("**", a, b), |
| 495 |
Self::And(a, b) => binary!("&&", a, b), |
| 496 |
Self::Or(a, b) => binary!("||", a, b), |
| 497 |
Self::Eq(a, b) => binary!("==", a, b), |
| 498 |
Self::NotEq(a, b) => binary!("!=", a, b), |
| 499 |
Self::Greater(a, b) => binary!(">", a, b), |
| 500 |
Self::GreaterEqual(a, b) => binary!(">=", a, b), |
| 501 |
Self::Less(a, b) => binary!("<", a, b), |
| 502 |
Self::LessEqual(a, b) => binary!("<=", a, b), |
| 503 |
Self::BitXor(a, b) => binary!("^", a, b), |
| 504 |
Self::Rem(a, b) => binary!("%", a, b), |
| 505 |
Self::BitAnd(a, b) => binary!("&", a, b), |
| 506 |
Self::Index(a, b) => binary!("[]", a, b), |
| 507 |
Self::Comma(a, b) => binary!(",", a, b), |
| 508 |
Self::Ternary(cond, a, b) => { |
| 509 |
write!(f, "? ")?; |
| 510 |
cond.fmt_delimited(f)?; |
| 511 |
write!(f, " ")?; |
| 512 |
a.fmt_delimited(f)?; |
| 513 |
write!(f, " ")?; |
| 514 |
b.fmt_delimited(f)?; |
| 515 |
} |
| 516 |
_ => unreachable!(), |
| 517 |
} |
| 518 |
|
| 519 |
write!(f, ")") |
| 520 |
} |
| 521 |
} |
| 522 |
|
| 523 |
impl core::fmt::Display for Expr { |
| 524 |
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { |
| 525 |
self.fmt_ast_with_indent(0, f)?; |
| 526 |
writeln!(f)?; |
| 527 |
self.fmt_delimited(f) |
| 528 |
} |
| 529 |
} |