Try associated type

This commit is contained in:
greg 2019-11-11 02:55:00 -08:00
parent 4b8f1c35b6
commit a7cad3b88e
2 changed files with 12 additions and 10 deletions

View File

@ -40,15 +40,16 @@ pub trait ASTVisitor: Sized {
fn pattern(&mut self, _pat: &Pattern) {} fn pattern(&mut self, _pat: &Pattern) {}
} }
pub trait ExpressionVisitor<T> {//TODO maybe this should be an associated type? pub trait ExpressionVisitor {//TODO maybe this should be an associated type?
fn type_anno(&mut self, _anno: &TypeIdentifier) -> T; type Output;
fn nat_literal(&mut self, _value: &u64) -> T; fn type_anno(&mut self, _anno: &TypeIdentifier) -> Self::Output;
fn string_literal(&mut self, _value: &Rc<String>) -> T; fn nat_literal(&mut self, _value: &u64) -> Self::Output;
fn binexp(&mut self, _op: &BinOp, _lhs_resul: T, _rhs_result: T) -> T; fn string_literal(&mut self, _value: &Rc<String>) -> Self::Output;
fn done(&mut self, kind: T, anno: Option<T>) -> T; fn binexp(&mut self, _op: &BinOp, _lhs_resul: Self::Output, _rhs_result: Self::Output) -> Self::Output;
fn done(&mut self, kind: Self::Output, anno: Option<Self::Output>) -> Self::Output;
} }
pub fn dispatch_expression_visitor<T>(input: &Expression, visitor: &mut dyn ExpressionVisitor<T>) -> Result<T, String> { pub fn dispatch_expression_visitor<T>(input: &Expression, visitor: &mut dyn ExpressionVisitor<Output=T>) -> Result<T, String> {
let output = match input.kind { let output = match input.kind {
ExpressionKind::NatLiteral(ref n) => visitor.nat_literal(n), ExpressionKind::NatLiteral(ref n) => visitor.nat_literal(n),

View File

@ -45,7 +45,8 @@ fn heh() {
struct ExprPrinter { struct ExprPrinter {
} }
impl ExpressionVisitor<String> for ExprPrinter { impl ExpressionVisitor for ExprPrinter {
type Output = String;
fn type_anno(&mut self, _anno: &TypeIdentifier) -> String { fn type_anno(&mut self, _anno: &TypeIdentifier) -> String {
"Any".to_string() "Any".to_string()
} }
@ -81,9 +82,9 @@ fn make_expr(input: &str) -> Expression {
#[test] #[test]
fn new_visitor() { fn new_visitor() {
let expr: Expression = make_expr("7+20"); let expr: Expression = make_expr("7+\"nueces\"");
let mut printer = ExprPrinter { }; let mut printer = ExprPrinter { };
let s = dispatch_expression_visitor(&expr, &mut printer).unwrap(); let s = dispatch_expression_visitor(&expr, &mut printer).unwrap();
assert_eq!(s, "7 + 20"); assert_eq!(s, r#"7 + "nueces""#);
} }