about summary refs log tree commit diff
path: root/src/parse/ast.rs
diff options
context:
space:
mode:
authorMel <einebeere@gmail.com>2021-10-18 20:37:57 +0200
committerMel <einebeere@gmail.com>2021-10-18 20:37:57 +0200
commit0f6f6068ebc33152f57658cf138df0622b44f6a2 (patch)
tree6c67ae6b88fcea74d1ac7105ebf121c2658ffa72 /src/parse/ast.rs
parent338bffe40ffea3f7cec94e8da8d96813b7f844ff (diff)
downloadrabbithole-0f6f6068ebc33152f57658cf138df0622b44f6a2.tar.zst
rabbithole-0f6f6068ebc33152f57658cf138df0622b44f6a2.zip
Basic expression parsing
Diffstat (limited to 'src/parse/ast.rs')
-rw-r--r--src/parse/ast.rs39
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(())
+    }
+}