parse.rs 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. extern crate rustc_ast;
  2. extern crate rustc_expand;
  3. extern crate rustc_parse as parse;
  4. extern crate rustc_session;
  5. extern crate rustc_span;
  6. use rustc_ast::ast;
  7. use rustc_ast::ptr::P;
  8. use rustc_session::parse::ParseSess;
  9. use rustc_span::source_map::FilePathMapping;
  10. use rustc_span::FileName;
  11. use std::panic;
  12. pub fn librustc_expr(input: &str) -> Option<P<ast::Expr>> {
  13. match panic::catch_unwind(|| {
  14. let sess = ParseSess::new(FilePathMapping::empty());
  15. let e = parse::new_parser_from_source_str(
  16. &sess,
  17. FileName::Custom("test_precedence".to_string()),
  18. input.to_string(),
  19. )
  20. .parse_expr();
  21. match e {
  22. Ok(expr) => Some(expr),
  23. Err(mut diagnostic) => {
  24. diagnostic.emit();
  25. None
  26. }
  27. }
  28. }) {
  29. Ok(Some(e)) => Some(e),
  30. Ok(None) => None,
  31. Err(_) => {
  32. errorf!("librustc panicked\n");
  33. None
  34. }
  35. }
  36. }
  37. pub fn syn_expr(input: &str) -> Option<syn::Expr> {
  38. match syn::parse_str(input) {
  39. Ok(e) => Some(e),
  40. Err(msg) => {
  41. errorf!("syn failed to parse\n{:?}\n", msg);
  42. None
  43. }
  44. }
  45. }