rustantlrantlr4

Rust reuse moved struct instance


I am working on a grammar in AntLR and Rust and I need to implement an ErrorListener that collects syntax errors that I need to use later. If I use a custom listener that has an inner RefCell to a vector of failed token types when I pass it to the parser.add_error_listener I lose the ownership and I cannot extract errors anymore (parser.add_error_listener takes a Box and not a reference to the listener).

    let listener = MyErrorListener::new();
    parser.add_error_listener(Box::new(listener));
    let res = parser.query();
    lestener.errors() // here I get error from the compiler since I already moved listener above

How do I overcome this issue? Is there a way to reuse the listener instance once I passed it to the add_error_listener function? Of course, I cannot clone the listener when passing it to the parser. (Note that add_error_listener is part of the AntLR rust lib)


Solution

  • After working on the suggestion from @PitaJ, I came up with this solution:

        let errors = Rc::new(RefCell::new(vec![]));
        let listener = MyErrorListener::new(&errors.clone()); // MyListener has a property errors: Rc<RefCell<Vec<isize>>>
        parser.add_error_listener(Box::new(listener));
        let res = parser.query();
        errors.as_ref().clone().into_inner().clone() // here I can access to the inner object and return it
    
    

    Hope this can help someone else.