Move more uses of `panictry!` out of libsyntax

[breaking-change] for syntax extensions
This commit is contained in:
Jonas Schievink 2016-02-13 18:05:16 +01:00
parent 0bf6394801
commit 3a872782d3
12 changed files with 107 additions and 119 deletions

View File

@ -48,12 +48,10 @@ use std::fs;
use std::io::{self, Write}; use std::io::{self, Write};
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use syntax::ast::{self, NodeIdAssigner}; use syntax::ast::{self, NodeIdAssigner};
use syntax::attr; use syntax::attr::{self, AttrMetaMethods};
use syntax::attr::AttrMetaMethods;
use syntax::diagnostics; use syntax::diagnostics;
use syntax::fold::Folder; use syntax::fold::Folder;
use syntax::parse; use syntax::parse::{self, PResult, token};
use syntax::parse::token;
use syntax::util::node_count::NodeCounter; use syntax::util::node_count::NodeCounter;
use syntax::visit; use syntax::visit;
use syntax; use syntax;
@ -86,7 +84,7 @@ pub fn compile_input(sess: &Session,
// possible to keep the peak memory usage low // possible to keep the peak memory usage low
let (outputs, trans) = { let (outputs, trans) = {
let (outputs, expanded_crate, id) = { let (outputs, expanded_crate, id) = {
let krate = phase_1_parse_input(sess, cfg, input); let krate = panictry!(phase_1_parse_input(sess, cfg, input));
controller_entry_point!(after_parse, controller_entry_point!(after_parse,
sess, sess,
@ -415,17 +413,20 @@ impl<'a, 'ast, 'tcx> CompileState<'a, 'ast, 'tcx> {
} }
} }
pub fn phase_1_parse_input(sess: &Session, cfg: ast::CrateConfig, input: &Input) -> ast::Crate { pub fn phase_1_parse_input<'a>(sess: &'a Session,
cfg: ast::CrateConfig,
input: &Input)
-> PResult<'a, ast::Crate> {
// These may be left in an incoherent state after a previous compile. // These may be left in an incoherent state after a previous compile.
// `clear_tables` and `get_ident_interner().clear()` can be used to free // `clear_tables` and `get_ident_interner().clear()` can be used to free
// memory, but they do not restore the initial state. // memory, but they do not restore the initial state.
syntax::ext::mtwt::reset_tables(); syntax::ext::mtwt::reset_tables();
token::reset_ident_interner(); token::reset_ident_interner();
let krate = time(sess.time_passes(), "parsing", || { let krate = try!(time(sess.time_passes(), "parsing", || {
match *input { match *input {
Input::File(ref file) => { Input::File(ref file) => {
parse::parse_crate_from_file(&(*file), cfg.clone(), &sess.parse_sess) parse::parse_crate_from_file(file, cfg.clone(), &sess.parse_sess)
} }
Input::Str(ref src) => { Input::Str(ref src) => {
parse::parse_crate_from_source_str(anon_src().to_string(), parse::parse_crate_from_source_str(anon_src().to_string(),
@ -434,7 +435,7 @@ pub fn phase_1_parse_input(sess: &Session, cfg: ast::CrateConfig, input: &Input)
&sess.parse_sess) &sess.parse_sess)
} }
} }
}); }));
if sess.opts.debugging_opts.ast_json_noexpand { if sess.opts.debugging_opts.ast_json_noexpand {
println!("{}", json::as_json(&krate)); println!("{}", json::as_json(&krate));
@ -449,7 +450,7 @@ pub fn phase_1_parse_input(sess: &Session, cfg: ast::CrateConfig, input: &Input)
syntax::show_span::run(sess.diagnostic(), s, &krate); syntax::show_span::run(sess.diagnostic(), s, &krate);
} }
krate Ok(krate)
} }
fn count_nodes(krate: &ast::Crate) -> usize { fn count_nodes(krate: &ast::Crate) -> usize {

View File

@ -88,7 +88,7 @@ use std::thread;
use rustc::session::early_error; use rustc::session::early_error;
use syntax::ast; use syntax::ast;
use syntax::parse; use syntax::parse::{self, PResult};
use syntax::errors; use syntax::errors;
use syntax::errors::emitter::Emitter; use syntax::errors::emitter::Emitter;
use syntax::diagnostics; use syntax::diagnostics;
@ -529,7 +529,7 @@ impl RustcDefaultCalls {
return Compilation::Continue; return Compilation::Continue;
} }
let attrs = input.map(|input| parse_crate_attrs(sess, input)); let attrs = input.map(|input| panictry!(parse_crate_attrs(sess, input)));
for req in &sess.opts.prints { for req in &sess.opts.prints {
match *req { match *req {
PrintRequest::TargetList => { PrintRequest::TargetList => {
@ -920,8 +920,8 @@ pub fn handle_options(mut args: Vec<String>) -> Option<getopts::Matches> {
Some(matches) Some(matches)
} }
fn parse_crate_attrs(sess: &Session, input: &Input) -> Vec<ast::Attribute> { fn parse_crate_attrs<'a>(sess: &'a Session, input: &Input) -> PResult<'a, Vec<ast::Attribute>> {
let result = match *input { match *input {
Input::File(ref ifile) => { Input::File(ref ifile) => {
parse::parse_crate_attrs_from_file(ifile, Vec::new(), &sess.parse_sess) parse::parse_crate_attrs_from_file(ifile, Vec::new(), &sess.parse_sess)
} }
@ -931,8 +931,7 @@ fn parse_crate_attrs(sess: &Session, input: &Input) -> Vec<ast::Attribute> {
Vec::new(), Vec::new(),
&sess.parse_sess) &sess.parse_sess)
} }
}; }
result.into_iter().collect()
} }
/// Run a procedure which will detect panics in the compiler and print nicer /// Run a procedure which will detect panics in the compiler and print nicer

View File

@ -686,7 +686,7 @@ pub fn pretty_print_input(sess: Session,
ppm: PpMode, ppm: PpMode,
opt_uii: Option<UserIdentifiedItem>, opt_uii: Option<UserIdentifiedItem>,
ofile: Option<PathBuf>) { ofile: Option<PathBuf>) {
let krate = driver::phase_1_parse_input(&sess, cfg, input); let krate = panictry!(driver::phase_1_parse_input(&sess, cfg, input));
let krate = if let PpmSource(PpmEveryBodyLoops) = ppm { let krate = if let PpmSource(PpmEveryBodyLoops) = ppm {
let mut fold = ReplaceBodyWithLoop::new(); let mut fold = ReplaceBodyWithLoop::new();

View File

@ -114,7 +114,7 @@ fn test_env<F>(source_string: &str,
rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess)); rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
let krate_config = Vec::new(); let krate_config = Vec::new();
let input = config::Input::Str(source_string.to_string()); let input = config::Input::Str(source_string.to_string());
let krate = driver::phase_1_parse_input(&sess, krate_config, &input); let krate = driver::phase_1_parse_input(&sess, krate_config, &input).unwrap();
let krate = driver::phase_2_configure_and_expand(&sess, &cstore, krate, "test", None) let krate = driver::phase_2_configure_and_expand(&sess, &cstore, krate, "test", None)
.expect("phase 2 aborted"); .expect("phase 2 aborted");

View File

@ -133,7 +133,7 @@ pub fn run_core(search_paths: SearchPaths, cfgs: Vec<String>, externs: Externs,
let mut cfg = config::build_configuration(&sess); let mut cfg = config::build_configuration(&sess);
target_features::add_configuration(&mut cfg, &sess); target_features::add_configuration(&mut cfg, &sess);
let krate = driver::phase_1_parse_input(&sess, cfg, &input); let krate = panictry!(driver::phase_1_parse_input(&sess, cfg, &input));
let name = link::find_crate_name(Some(&sess), &krate.attrs, let name = link::find_crate_name(Some(&sess), &krate.attrs,
&input); &input);

View File

@ -43,7 +43,7 @@ extern crate rustc_back;
extern crate rustc_front; extern crate rustc_front;
extern crate rustc_metadata; extern crate rustc_metadata;
extern crate serialize; extern crate serialize;
extern crate syntax; #[macro_use] extern crate syntax;
extern crate test as testing; extern crate test as testing;
extern crate rustc_unicode; extern crate rustc_unicode;
#[macro_use] extern crate log; #[macro_use] extern crate log;

View File

@ -91,7 +91,7 @@ pub fn run(input: &str,
let mut cfg = config::build_configuration(&sess); let mut cfg = config::build_configuration(&sess);
cfg.extend(config::parse_cfgspecs(cfgs.clone())); cfg.extend(config::parse_cfgspecs(cfgs.clone()));
let krate = driver::phase_1_parse_input(&sess, cfg, &input); let krate = panictry!(driver::phase_1_parse_input(&sess, cfg, &input));
let krate = driver::phase_2_configure_and_expand(&sess, &cstore, krate, let krate = driver::phase_2_configure_and_expand(&sess, &cstore, krate,
"rustdoc-test", None) "rustdoc-test", None)
.expect("phase_2_configure_and_expand aborted in rustdoc!"); .expect("phase_2_configure_and_expand aborted in rustdoc!");

View File

@ -1476,7 +1476,7 @@ mod tests {
let crate_ast = parse::parse_crate_from_source_str( let crate_ast = parse::parse_crate_from_source_str(
"<test>".to_string(), "<test>".to_string(),
src, src,
Vec::new(), &sess); Vec::new(), &sess).unwrap();
// should fail: // should fail:
let mut gated_cfgs = vec![]; let mut gated_cfgs = vec![];
let ecx = ExtCtxt::new(&sess, vec![], test_ecfg(), &mut gated_cfgs); let ecx = ExtCtxt::new(&sess, vec![], test_ecfg(), &mut gated_cfgs);
@ -1492,7 +1492,7 @@ mod tests {
let crate_ast = parse::parse_crate_from_source_str( let crate_ast = parse::parse_crate_from_source_str(
"<test>".to_string(), "<test>".to_string(),
src, src,
Vec::new(), &sess); Vec::new(), &sess).unwrap();
let mut gated_cfgs = vec![]; let mut gated_cfgs = vec![];
let ecx = ExtCtxt::new(&sess, vec![], test_ecfg(), &mut gated_cfgs); let ecx = ExtCtxt::new(&sess, vec![], test_ecfg(), &mut gated_cfgs);
expand_crate(ecx, vec![], vec![], crate_ast); expand_crate(ecx, vec![], vec![], crate_ast);
@ -1506,7 +1506,7 @@ mod tests {
let crate_ast = parse::parse_crate_from_source_str( let crate_ast = parse::parse_crate_from_source_str(
"<test>".to_string(), "<test>".to_string(),
src, src,
Vec::new(), &sess); Vec::new(), &sess).unwrap();
let mut gated_cfgs = vec![]; let mut gated_cfgs = vec![];
let ecx = ExtCtxt::new(&sess, vec![], test_ecfg(), &mut gated_cfgs); let ecx = ExtCtxt::new(&sess, vec![], test_ecfg(), &mut gated_cfgs);
expand_crate(ecx, vec![], vec![], crate_ast); expand_crate(ecx, vec![], vec![], crate_ast);

View File

@ -319,34 +319,36 @@ pub mod rt {
} }
impl<'a> ExtParseUtils for ExtCtxt<'a> { impl<'a> ExtParseUtils for ExtCtxt<'a> {
fn parse_item(&self, s: String) -> P<ast::Item> { fn parse_item(&self, s: String) -> P<ast::Item> {
parse::parse_item_from_source_str( panictry!(parse::parse_item_from_source_str(
"<quote expansion>".to_string(), "<quote expansion>".to_string(),
s, s,
self.cfg(), self.cfg(),
self.parse_sess()).expect("parse error") self.parse_sess())).expect("parse error")
} }
fn parse_stmt(&self, s: String) -> ast::Stmt { fn parse_stmt(&self, s: String) -> ast::Stmt {
parse::parse_stmt_from_source_str("<quote expansion>".to_string(), panictry!(parse::parse_stmt_from_source_str(
"<quote expansion>".to_string(),
s, s,
self.cfg(), self.cfg(),
self.parse_sess()).expect("parse error") self.parse_sess())).expect("parse error")
} }
fn parse_expr(&self, s: String) -> P<ast::Expr> { fn parse_expr(&self, s: String) -> P<ast::Expr> {
parse::parse_expr_from_source_str("<quote expansion>".to_string(), panictry!(parse::parse_expr_from_source_str(
"<quote expansion>".to_string(),
s, s,
self.cfg(), self.cfg(),
self.parse_sess()) self.parse_sess()))
} }
fn parse_tts(&self, s: String) -> Vec<TokenTree> { fn parse_tts(&self, s: String) -> Vec<TokenTree> {
parse::parse_tts_from_source_str("<quote expansion>".to_string(), panictry!(parse::parse_tts_from_source_str(
"<quote expansion>".to_string(),
s, s,
self.cfg(), self.cfg(),
self.parse_sess()) self.parse_sess()))
} }
} }
} }

View File

@ -71,95 +71,93 @@ impl ParseSess {
// uses a HOF to parse anything, and <source> includes file and // uses a HOF to parse anything, and <source> includes file and
// source_str. // source_str.
pub fn parse_crate_from_file( pub fn parse_crate_from_file<'a>(input: &Path,
input: &Path,
cfg: ast::CrateConfig, cfg: ast::CrateConfig,
sess: &ParseSess sess: &'a ParseSess)
) -> ast::Crate { -> PResult<'a, ast::Crate> {
let mut parser = new_parser_from_file(sess, cfg, input); let mut parser = new_parser_from_file(sess, cfg, input);
abort_if_errors(parser.parse_crate_mod(), &parser) parser.parse_crate_mod()
} }
pub fn parse_crate_attrs_from_file( pub fn parse_crate_attrs_from_file<'a>(input: &Path,
input: &Path,
cfg: ast::CrateConfig, cfg: ast::CrateConfig,
sess: &ParseSess sess: &'a ParseSess)
) -> Vec<ast::Attribute> { -> PResult<'a, Vec<ast::Attribute>> {
let mut parser = new_parser_from_file(sess, cfg, input); let mut parser = new_parser_from_file(sess, cfg, input);
abort_if_errors(parser.parse_inner_attributes(), &parser) parser.parse_inner_attributes()
} }
pub fn parse_crate_from_source_str(name: String, pub fn parse_crate_from_source_str<'a>(name: String,
source: String, source: String,
cfg: ast::CrateConfig, cfg: ast::CrateConfig,
sess: &ParseSess) sess: &'a ParseSess)
-> ast::Crate { -> PResult<'a, ast::Crate> {
let mut p = new_parser_from_source_str(sess, let mut p = new_parser_from_source_str(sess,
cfg, cfg,
name, name,
source); source);
panictry!(p.parse_crate_mod()) p.parse_crate_mod()
} }
pub fn parse_crate_attrs_from_source_str(name: String, pub fn parse_crate_attrs_from_source_str<'a>(name: String,
source: String, source: String,
cfg: ast::CrateConfig, cfg: ast::CrateConfig,
sess: &ParseSess) sess: &'a ParseSess)
-> Vec<ast::Attribute> { -> PResult<'a, Vec<ast::Attribute>> {
let mut p = new_parser_from_source_str(sess, let mut p = new_parser_from_source_str(sess,
cfg, cfg,
name, name,
source); source);
panictry!(p.parse_inner_attributes()) p.parse_inner_attributes()
} }
pub fn parse_expr_from_source_str(name: String, pub fn parse_expr_from_source_str<'a>(name: String,
source: String, source: String,
cfg: ast::CrateConfig, cfg: ast::CrateConfig,
sess: &ParseSess) sess: &'a ParseSess)
-> P<ast::Expr> { -> PResult<'a, P<ast::Expr>> {
let mut p = new_parser_from_source_str(sess, cfg, name, source); let mut p = new_parser_from_source_str(sess, cfg, name, source);
panictry!(p.parse_expr()) p.parse_expr()
} }
pub fn parse_item_from_source_str(name: String, pub fn parse_item_from_source_str<'a>(name: String,
source: String, source: String,
cfg: ast::CrateConfig, cfg: ast::CrateConfig,
sess: &ParseSess) sess: &'a ParseSess)
-> Option<P<ast::Item>> { -> PResult<'a, Option<P<ast::Item>>> {
let mut p = new_parser_from_source_str(sess, cfg, name, source); let mut p = new_parser_from_source_str(sess, cfg, name, source);
panictry!(p.parse_item()) p.parse_item()
} }
pub fn parse_meta_from_source_str(name: String, pub fn parse_meta_from_source_str<'a>(name: String,
source: String, source: String,
cfg: ast::CrateConfig, cfg: ast::CrateConfig,
sess: &ParseSess) sess: &'a ParseSess)
-> P<ast::MetaItem> { -> PResult<'a, P<ast::MetaItem>> {
let mut p = new_parser_from_source_str(sess, cfg, name, source); let mut p = new_parser_from_source_str(sess, cfg, name, source);
panictry!(p.parse_meta_item()) p.parse_meta_item()
} }
pub fn parse_stmt_from_source_str(name: String, pub fn parse_stmt_from_source_str<'a>(name: String,
source: String, source: String,
cfg: ast::CrateConfig, cfg: ast::CrateConfig,
sess: &ParseSess) sess: &'a ParseSess)
-> Option<ast::Stmt> { -> PResult<'a, Option<ast::Stmt>> {
let mut p = new_parser_from_source_str( let mut p = new_parser_from_source_str(
sess, sess,
cfg, cfg,
name, name,
source source
); );
panictry!(p.parse_stmt()) p.parse_stmt()
} }
// Warning: This parses with quote_depth > 0, which is not the default. // Warning: This parses with quote_depth > 0, which is not the default.
pub fn parse_tts_from_source_str(name: String, pub fn parse_tts_from_source_str<'a>(name: String,
source: String, source: String,
cfg: ast::CrateConfig, cfg: ast::CrateConfig,
sess: &ParseSess) sess: &'a ParseSess)
-> Vec<ast::TokenTree> { -> PResult<'a, Vec<ast::TokenTree>> {
let mut p = new_parser_from_source_str( let mut p = new_parser_from_source_str(
sess, sess,
cfg, cfg,
@ -168,7 +166,7 @@ pub fn parse_tts_from_source_str(name: String,
); );
p.quote_depth += 1; p.quote_depth += 1;
// right now this is re-creating the token trees from ... token trees. // right now this is re-creating the token trees from ... token trees.
panictry!(p.parse_all_token_trees()) p.parse_all_token_trees()
} }
// Create a new parser from a source string // Create a new parser from a source string
@ -265,20 +263,6 @@ pub fn tts_to_parser<'a>(sess: &'a ParseSess,
p p
} }
fn abort_if_errors<'a, T>(result: PResult<'a, T>, p: &Parser) -> T {
match result {
Ok(c) => {
c
}
Err(mut e) => {
e.emit();
p.abort_if_errors();
unreachable!();
}
}
}
/// Parse a string representing a character literal into its final form. /// Parse a string representing a character literal into its final form.
/// Rather than just accepting/rejecting a given literal, unescapes it as /// Rather than just accepting/rejecting a given literal, unescapes it as
/// well. Can take any slice prefixed by a character escape. Returns the /// well. Can take any slice prefixed by a character escape. Returns the
@ -1078,19 +1062,21 @@ mod tests {
let name = "<source>".to_string(); let name = "<source>".to_string();
let source = "/// doc comment\r\nfn foo() {}".to_string(); let source = "/// doc comment\r\nfn foo() {}".to_string();
let item = parse_item_from_source_str(name.clone(), source, Vec::new(), &sess).unwrap(); let item = parse_item_from_source_str(name.clone(), source, Vec::new(), &sess)
.unwrap().unwrap();
let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap(); let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap();
assert_eq!(&doc[..], "/// doc comment"); assert_eq!(&doc[..], "/// doc comment");
let source = "/// doc comment\r\n/// line 2\r\nfn foo() {}".to_string(); let source = "/// doc comment\r\n/// line 2\r\nfn foo() {}".to_string();
let item = parse_item_from_source_str(name.clone(), source, Vec::new(), &sess).unwrap(); let item = parse_item_from_source_str(name.clone(), source, Vec::new(), &sess)
.unwrap().unwrap();
let docs = item.attrs.iter().filter(|a| &*a.name() == "doc") let docs = item.attrs.iter().filter(|a| &*a.name() == "doc")
.map(|a| a.value_str().unwrap().to_string()).collect::<Vec<_>>(); .map(|a| a.value_str().unwrap().to_string()).collect::<Vec<_>>();
let b: &[_] = &["/// doc comment".to_string(), "/// line 2".to_string()]; let b: &[_] = &["/// doc comment".to_string(), "/// line 2".to_string()];
assert_eq!(&docs[..], b); assert_eq!(&docs[..], b);
let source = "/** doc comment\r\n * with CRLF */\r\nfn foo() {}".to_string(); let source = "/** doc comment\r\n * with CRLF */\r\nfn foo() {}".to_string();
let item = parse_item_from_source_str(name, source, Vec::new(), &sess).unwrap(); let item = parse_item_from_source_str(name, source, Vec::new(), &sess).unwrap().unwrap();
let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap(); let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap();
assert_eq!(&doc[..], "/** doc comment\n * with CRLF */"); assert_eq!(&doc[..], "/** doc comment\n * with CRLF */");
} }
@ -1099,7 +1085,7 @@ mod tests {
fn ttdelim_span() { fn ttdelim_span() {
let sess = ParseSess::new(); let sess = ParseSess::new();
let expr = parse::parse_expr_from_source_str("foo".to_string(), let expr = parse::parse_expr_from_source_str("foo".to_string(),
"foo!( fn main() { body } )".to_string(), vec![], &sess); "foo!( fn main() { body } )".to_string(), vec![], &sess).unwrap();
let tts = match expr.node { let tts = match expr.node {
ast::ExprKind::Mac(ref mac) => mac.node.tts.clone(), ast::ExprKind::Mac(ref mac) => mac.node.tts.clone(),

View File

@ -18,7 +18,7 @@ extern crate rustc_front;
extern crate rustc_lint; extern crate rustc_lint;
extern crate rustc_metadata; extern crate rustc_metadata;
extern crate rustc_resolve; extern crate rustc_resolve;
extern crate syntax; #[macro_use] extern crate syntax;
use std::ffi::{CStr, CString}; use std::ffi::{CStr, CString};
use std::mem::transmute; use std::mem::transmute;
@ -230,7 +230,7 @@ fn compile_program(input: &str, sysroot: PathBuf)
let id = "input".to_string(); let id = "input".to_string();
let krate = driver::phase_1_parse_input(&sess, cfg, &input); let krate = panictry!(driver::phase_1_parse_input(&sess, cfg, &input));
let krate = driver::phase_2_configure_and_expand(&sess, &cstore, krate, &id, None) let krate = driver::phase_2_configure_and_expand(&sess, &cstore, krate, &id, None)
.expect("phase_2 returned `None`"); .expect("phase_2 returned `None`");