diff options
| author | Mel <einebeere@gmail.com> | 2021-10-18 20:37:57 +0200 |
|---|---|---|
| committer | Mel <einebeere@gmail.com> | 2021-10-18 20:37:57 +0200 |
| commit | 0f6f6068ebc33152f57658cf138df0622b44f6a2 (patch) | |
| tree | 6c67ae6b88fcea74d1ac7105ebf121c2658ffa72 /src/parse/ast.rs | |
| parent | 338bffe40ffea3f7cec94e8da8d96813b7f844ff (diff) | |
| download | rabbithole-0f6f6068ebc33152f57658cf138df0622b44f6a2.tar.zst rabbithole-0f6f6068ebc33152f57658cf138df0622b44f6a2.zip | |
Basic expression parsing
Diffstat (limited to 'src/parse/ast.rs')
| -rw-r--r-- | src/parse/ast.rs | 39 |
1 files changed, 39 insertions, 0 deletions
diff --git a/src/parse/ast.rs b/src/parse/ast.rs index 2f30eaf..0f7ea34 100644 --- a/src/parse/ast.rs +++ b/src/parse/ast.rs @@ -1,3 +1,5 @@ +use std::fmt::Display; + use crate::lex::token::Token; #[derive(Debug)] @@ -14,3 +16,40 @@ pub enum Expression { Group(Box<Expression>), Literal(Token), } + +impl Display for Expression { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + self.nested_fmt(f, 0) + } +} + +impl Expression { + fn nested_fmt(&self, f: &mut std::fmt::Formatter<'_>, depth: usize) -> std::fmt::Result { + let pad = " ".repeat(depth); + match self { + Expression::Binary { left, op, right } => { + writeln!(f, "{}Binary:", pad)?; + writeln!(f, "{}- Left:", pad)?; + left.nested_fmt(f, depth + 1)?; + writeln!(f, "{}- Operator: {:?}", pad, op.variant)?; + writeln!(f, "{}- Right:", pad)?; + right.nested_fmt(f, depth + 1)?; + } + Expression::Unary { op, right } => { + writeln!(f, "{}Unary:", pad)?; + writeln!(f, "{}- Operator: {:?}", pad, op.variant)?; + writeln!(f, "{}- Right:", pad)?; + right.nested_fmt(f, depth + 1)?; + } + Expression::Group(node) => { + writeln!(f, "{}Group:", pad)?; + node.nested_fmt(f, depth + 1)?; + } + Expression::Literal(token) => { + writeln!(f, "{}Literal: {:?}", pad, token.variant)?; + } + } + + Ok(()) + } +} |
