Created
April 24, 2015 02:14
-
-
Save cmf028/6ed4e57e4e66f08703c7 to your computer and use it in GitHub Desktop.
Trait object incorrect method selection bug
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
trait VisitorBase<T> { | |
fn visit(&mut self, node: &T); | |
} | |
trait Visitor : VisitorBase<Num> + VisitorBase<Add> {} | |
impl<T> Visitor for T where T: VisitorBase<Num> + VisitorBase<Add> {} | |
trait Node { | |
fn accept(&self, visitor: &mut Visitor ); | |
} | |
struct Add { | |
lhs: Box<Node>, | |
rhs: Box<Node> | |
} | |
impl Node for Add { | |
fn accept(&self, visitor: &mut Visitor) { | |
println!("accept Add"); | |
visitor.visit(self); | |
} | |
} | |
struct Num { | |
val: i32 | |
} | |
impl Node for Num { | |
fn accept(&self, visitor: &mut Visitor) { | |
println!("accept Num"); | |
visitor.visit(self); | |
} | |
} | |
struct EvalVisitor { | |
result: i32 | |
} | |
impl EvalVisitor { | |
fn new() -> EvalVisitor { | |
EvalVisitor{result:0} | |
} | |
} | |
impl VisitorBase<Add> for EvalVisitor { | |
fn visit(&mut self, node: &Add) { | |
println!("visit Add"); | |
node.lhs.accept(self); | |
let temp = self.result; | |
node.rhs.accept(self); | |
println!("lhs: {} rhs: {}", temp, self.result); | |
self.result = temp + self.result; | |
} | |
} | |
impl VisitorBase<Num> for EvalVisitor { | |
fn visit(&mut self, node: &Num) { | |
println!("visit Num"); | |
println!("val {}", node.val); | |
self.result = node.val; | |
} | |
} | |
fn main() { | |
let top = Num{val:5}; | |
let mut visitor = EvalVisitor::new(); | |
top.accept(&mut visitor); | |
let res = visitor.result; | |
println!("value: {}", res); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment