From c3c515284dc205bff2158157ea2303e07d0ce1dd Mon Sep 17 00:00:00 2001 From: greg Date: Mon, 29 Jul 2019 20:01:51 -0700 Subject: [PATCH] Super-simple visitor doing something --- schala-lang/language/src/visitor.rs | 43 ++++++++++++++++++++++++++--- 1 file changed, 39 insertions(+), 4 deletions(-) diff --git a/schala-lang/language/src/visitor.rs b/schala-lang/language/src/visitor.rs index a258186..73453ed 100644 --- a/schala-lang/language/src/visitor.rs +++ b/schala-lang/language/src/visitor.rs @@ -1,13 +1,48 @@ -use crate::ast::ExpressionKind; +use std::rc::Rc; + +use crate::builtin::{BinOp, PrefixOp}; +use crate::ast::{Expression, ExpressionKind}; pub trait ExpressionKindVisitor { - fn nat_literal(&mut self, n: u64) -> T; + fn nat_literal(&mut self, n: &u64) -> T; + fn string_literal(&mut self, s: Rc) -> T; + fn binexp(&mut self, op: &BinOp, lhs: &Expression, rhs: &Expression) -> T; } -pub fn dispatch(input: &mut ExpressionKind, visitor: &mut dyn ExpressionKindVisitor) -> T { +pub fn dispatch(input: &ExpressionKind, visitor: &mut dyn ExpressionKindVisitor) -> T { use ExpressionKind::*; match input { - NatLiteral(n) => visitor.nat_literal(*n), + NatLiteral(n) => visitor.nat_literal(n), + StringLiteral(s) => visitor.string_literal(s.clone()), + BinExp(op, box lhs, box rhs) => visitor.binexp(op, lhs.node(), rhs.node()), _ => panic!() } } + +struct NumberSummer; + +impl ExpressionKindVisitor for NumberSummer { + fn nat_literal(&mut self, n: &u64) -> u64 { + n.clone() + } + fn string_literal(&mut self, s: Rc) -> u64 { + 0 + } + fn binexp(&mut self, op: &BinOp, lhs: &Expression, rhs: &Expression) -> u64 { + let lhs = dispatch(&lhs.kind, self); + let rhs = dispatch(&rhs.kind, self); + lhs + rhs + } +} + +#[test] +fn yolo_swagg() { + use super::*; + + let mut t = NumberSummer; + + let x = ExpressionKind::NatLiteral(4); + + let result = dispatch(&x, &mut t); + assert_eq!(result, 4); +}