Advertisement
zbx1425

Untitled

Jan 19th, 2023
1,592
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.43 KB | None | 0 0
  1. pub struct AntlrAst {
  2.   content_ptr: *mut str,
  3.   pub ctx_root: std::rc::Rc<super::grammar::bvemapparser::RootContext<'static>>
  4. }
  5.  
  6. impl AntlrAst {
  7.  
  8.  pub fn load(path: String, content: String) -> Result<AntlrAst, Box<dyn Error>> {
  9.    // Create a forgotten copy of content on the heap
  10.    let content_ptr = Box::leak(content.into_boxed_str());
  11.    // Use the pointer to create a reference with static lifetime
  12.    let input_stream = InputStream::new(unsafe { Box::leak(Box::from_raw(content_ptr)) });
  13.  
  14.    let error_vec = SyntaxErrorVec::new(path.as_str());
  15.    let mut lexer = BveMapLexer::new(input_stream);
  16.    lexer.remove_error_listeners();
  17.    lexer.add_error_listener(Box::new(SyntaxErrorVecListener::new(&error_vec)));
  18.    let token_stream = CommonTokenStream::new(lexer);
  19.    if error_vec.has_error() {
  20.      return Err(error_vec.to_string().into());
  21.    }
  22.  
  23.    let mut parser = BveMapParser::new(token_stream);
  24.    parser.remove_error_listeners();
  25.    parser.add_error_listener(Box::new(SyntaxErrorVecListener::new(&error_vec)));
  26.    let ctx_root = parser.root()?;
  27.    if error_vec.has_error() {
  28.      return Err(error_vec.to_string().into());
  29.    }
  30.  
  31.    // TODO: Is there memory leaks?
  32.    Ok(AntlrAst {
  33.      content_ptr,
  34.      ctx_root
  35.    })
  36.  }
  37. }
  38.  
  39. impl Drop for AntlrAst {
  40.  
  41.  fn drop(&mut self) {
  42.    unsafe {
  43.      // Manually free the content
  44.      drop(Box::from_raw(self.content_ptr));
  45.    }
  46.  }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement