Super-simple visitor doing something
This commit is contained in:
parent
0903277b69
commit
c3c515284d
@ -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<T> {
|
pub trait ExpressionKindVisitor<T> {
|
||||||
fn nat_literal(&mut self, n: u64) -> T;
|
fn nat_literal(&mut self, n: &u64) -> T;
|
||||||
|
fn string_literal(&mut self, s: Rc<String>) -> T;
|
||||||
|
fn binexp(&mut self, op: &BinOp, lhs: &Expression, rhs: &Expression) -> T;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn dispatch<T>(input: &mut ExpressionKind, visitor: &mut dyn ExpressionKindVisitor<T>) -> T {
|
pub fn dispatch<T>(input: &ExpressionKind, visitor: &mut dyn ExpressionKindVisitor<T>) -> T {
|
||||||
use ExpressionKind::*;
|
use ExpressionKind::*;
|
||||||
match input {
|
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!()
|
_ => panic!()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
struct NumberSummer;
|
||||||
|
|
||||||
|
impl ExpressionKindVisitor<u64> for NumberSummer {
|
||||||
|
fn nat_literal(&mut self, n: &u64) -> u64 {
|
||||||
|
n.clone()
|
||||||
|
}
|
||||||
|
fn string_literal(&mut self, s: Rc<String>) -> 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);
|
||||||
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user