From 0f6f6068ebc33152f57658cf138df0622b44f6a2 Mon Sep 17 00:00:00 2001 From: Mel Date: Mon, 18 Oct 2021 20:37:57 +0200 Subject: Basic expression parsing --- src/parse/ast.rs | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) (limited to 'src/parse/ast.rs') 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), 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(()) + } +} -- cgit 1.4.1