1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! The main parser interface
14 use codemap::{Span, CodeMap, FileMap};
15 use diagnostic::{SpanHandler, mk_span_handler, default_handler, Auto};
16 use parse::attr::ParserAttr;
17 use parse::parser::Parser;
20 use std::cell::{Cell, RefCell};
36 /// Info about a parsing session.
37 pub struct ParseSess {
38 pub span_diagnostic: SpanHandler, // better be the same as the one in the reader!
39 /// Used to determine and report recursive mod inclusions
40 included_mod_stack: RefCell<Vec<Path>>,
41 pub node_id: Cell<ast::NodeId>,
44 pub fn new_parse_sess() -> ParseSess {
46 span_diagnostic: mk_span_handler(default_handler(Auto, None), CodeMap::new()),
47 included_mod_stack: RefCell::new(Vec::new()),
48 node_id: Cell::new(1),
52 pub fn new_parse_sess_special_handler(sh: SpanHandler) -> ParseSess {
55 included_mod_stack: RefCell::new(Vec::new()),
56 node_id: Cell::new(1),
61 pub fn next_node_id(&self) -> ast::NodeId {
62 self.reserve_node_ids(1)
64 pub fn reserve_node_ids(&self, count: ast::NodeId) -> ast::NodeId {
65 let v = self.node_id.get();
67 match v.checked_add(count) {
68 Some(next) => { self.node_id.set(next); }
69 None => panic!("Input too large, ran out of node ids!")
76 // a bunch of utility functions of the form parse_<thing>_from_<source>
77 // where <thing> includes crate, expr, item, stmt, tts, and one that
78 // uses a HOF to parse anything, and <source> includes file and
81 pub fn parse_crate_from_file(
83 cfg: ast::CrateConfig,
86 new_parser_from_file(sess, cfg, input).parse_crate_mod()
87 // why is there no p.abort_if_errors here?
90 pub fn parse_crate_attrs_from_file(
92 cfg: ast::CrateConfig,
94 ) -> Vec<ast::Attribute> {
95 let mut parser = new_parser_from_file(sess, cfg, input);
96 let (inner, _) = parser.parse_inner_attrs_and_next();
100 pub fn parse_crate_from_source_str(name: String,
102 cfg: ast::CrateConfig,
105 let mut p = new_parser_from_source_str(sess,
109 maybe_aborted(p.parse_crate_mod(),p)
112 pub fn parse_crate_attrs_from_source_str(name: String,
114 cfg: ast::CrateConfig,
116 -> Vec<ast::Attribute> {
117 let mut p = new_parser_from_source_str(sess,
121 let (inner, _) = maybe_aborted(p.parse_inner_attrs_and_next(),p);
125 pub fn parse_expr_from_source_str(name: String,
127 cfg: ast::CrateConfig,
130 let mut p = new_parser_from_source_str(sess, cfg, name, source);
131 maybe_aborted(p.parse_expr(), p)
134 pub fn parse_item_from_source_str(name: String,
136 cfg: ast::CrateConfig,
138 -> Option<P<ast::Item>> {
139 let mut p = new_parser_from_source_str(sess, cfg, name, source);
140 maybe_aborted(p.parse_item_with_outer_attributes(),p)
143 pub fn parse_meta_from_source_str(name: String,
145 cfg: ast::CrateConfig,
147 -> P<ast::MetaItem> {
148 let mut p = new_parser_from_source_str(sess, cfg, name, source);
149 maybe_aborted(p.parse_meta_item(),p)
152 pub fn parse_stmt_from_source_str(name: String,
154 cfg: ast::CrateConfig,
155 attrs: Vec<ast::Attribute> ,
158 let mut p = new_parser_from_source_str(
164 maybe_aborted(p.parse_stmt(attrs),p)
167 // Note: keep in sync with `with_hygiene::parse_tts_from_source_str`
168 // until #16472 is resolved.
169 pub fn parse_tts_from_source_str(name: String,
171 cfg: ast::CrateConfig,
173 -> Vec<ast::TokenTree> {
174 let mut p = new_parser_from_source_str(
181 // right now this is re-creating the token trees from ... token trees.
182 maybe_aborted(p.parse_all_token_trees(),p)
185 // Note: keep in sync with `with_hygiene::new_parser_from_source_str`
186 // until #16472 is resolved.
187 // Create a new parser from a source string
188 pub fn new_parser_from_source_str<'a>(sess: &'a ParseSess,
189 cfg: ast::CrateConfig,
193 filemap_to_parser(sess, string_to_filemap(sess, source, name), cfg)
196 /// Create a new parser, handling errors as appropriate
197 /// if the file doesn't exist
198 pub fn new_parser_from_file<'a>(sess: &'a ParseSess,
199 cfg: ast::CrateConfig,
200 path: &Path) -> Parser<'a> {
201 filemap_to_parser(sess, file_to_filemap(sess, path, None), cfg)
204 /// Given a session, a crate config, a path, and a span, add
205 /// the file at the given path to the codemap, and return a parser.
206 /// On an error, use the given span as the source of the problem.
207 pub fn new_sub_parser_from_file<'a>(sess: &'a ParseSess,
208 cfg: ast::CrateConfig,
210 owns_directory: bool,
211 module_name: Option<String>,
212 sp: Span) -> Parser<'a> {
213 let mut p = filemap_to_parser(sess, file_to_filemap(sess, path, Some(sp)), cfg);
214 p.owns_directory = owns_directory;
215 p.root_module_name = module_name;
219 // Note: keep this in sync with `with_hygiene::filemap_to_parser` until
220 // #16472 is resolved.
221 /// Given a filemap and config, return a parser
222 pub fn filemap_to_parser<'a>(sess: &'a ParseSess,
223 filemap: Rc<FileMap>,
224 cfg: ast::CrateConfig) -> Parser<'a> {
225 tts_to_parser(sess, filemap_to_tts(sess, filemap), cfg)
228 // must preserve old name for now, because quote! from the *existing*
229 // compiler expands into it
230 pub fn new_parser_from_tts<'a>(sess: &'a ParseSess,
231 cfg: ast::CrateConfig,
232 tts: Vec<ast::TokenTree>) -> Parser<'a> {
233 tts_to_parser(sess, tts, cfg)
239 /// Given a session and a path and an optional span (for error reporting),
240 /// add the path to the session's codemap and return the new filemap.
241 pub fn file_to_filemap(sess: &ParseSess, path: &Path, spanopt: Option<Span>)
243 let err = |&: msg: &str| {
245 Some(sp) => sess.span_diagnostic.span_fatal(sp, msg),
246 None => sess.span_diagnostic.handler().fatal(msg),
249 let bytes = match File::open(path).read_to_end() {
252 err(format!("couldn't read {}: {}",
258 match str::from_utf8(bytes[]).ok() {
260 return string_to_filemap(sess, s.to_string(),
261 path.as_str().unwrap().to_string())
264 err(format!("{} is not UTF-8 encoded", path.display())[])
270 /// Given a session and a string, add the string to
271 /// the session's codemap and return the new filemap
272 pub fn string_to_filemap(sess: &ParseSess, source: String, path: String)
274 sess.span_diagnostic.cm.new_filemap(path, source)
277 // Note: keep this in sync with `with_hygiene::filemap_to_tts` (apart
278 // from the StringReader constructor), until #16472 is resolved.
279 /// Given a filemap, produce a sequence of token-trees
280 pub fn filemap_to_tts(sess: &ParseSess, filemap: Rc<FileMap>)
281 -> Vec<ast::TokenTree> {
282 // it appears to me that the cfg doesn't matter here... indeed,
283 // parsing tt's probably shouldn't require a parser at all.
284 let cfg = Vec::new();
285 let srdr = lexer::StringReader::new(&sess.span_diagnostic, filemap);
286 let mut p1 = Parser::new(sess, cfg, box srdr);
287 p1.parse_all_token_trees()
290 /// Given tts and cfg, produce a parser
291 pub fn tts_to_parser<'a>(sess: &'a ParseSess,
292 tts: Vec<ast::TokenTree>,
293 cfg: ast::CrateConfig) -> Parser<'a> {
294 let trdr = lexer::new_tt_reader(&sess.span_diagnostic, None, tts);
295 Parser::new(sess, cfg, box trdr)
298 // FIXME (Issue #16472): The `with_hygiene` mod should go away after
299 // ToToken impls are revised to go directly to token-trees.
300 pub mod with_hygiene {
302 use codemap::FileMap;
303 use parse::parser::Parser;
305 use super::ParseSess;
306 use super::{maybe_aborted, string_to_filemap, tts_to_parser};
308 // Note: keep this in sync with `super::parse_tts_from_source_str` until
309 // #16472 is resolved.
310 pub fn parse_tts_from_source_str(name: String,
312 cfg: ast::CrateConfig,
313 sess: &ParseSess) -> Vec<ast::TokenTree> {
314 let mut p = new_parser_from_source_str(
321 // right now this is re-creating the token trees from ... token trees.
322 maybe_aborted(p.parse_all_token_trees(),p)
325 // Note: keep this in sync with `super::new_parser_from_source_str` until
326 // #16472 is resolved.
327 // Create a new parser from a source string
328 fn new_parser_from_source_str<'a>(sess: &'a ParseSess,
329 cfg: ast::CrateConfig,
331 source: String) -> Parser<'a> {
332 filemap_to_parser(sess, string_to_filemap(sess, source, name), cfg)
335 // Note: keep this in sync with `super::filemap_to_parserr` until
336 // #16472 is resolved.
337 /// Given a filemap and config, return a parser
338 fn filemap_to_parser<'a>(sess: &'a ParseSess,
339 filemap: Rc<FileMap>,
340 cfg: ast::CrateConfig) -> Parser<'a> {
341 tts_to_parser(sess, filemap_to_tts(sess, filemap), cfg)
344 // Note: keep this in sync with `super::filemap_to_tts` until
345 // #16472 is resolved.
346 /// Given a filemap, produce a sequence of token-trees
347 fn filemap_to_tts(sess: &ParseSess, filemap: Rc<FileMap>)
348 -> Vec<ast::TokenTree> {
349 // it appears to me that the cfg doesn't matter here... indeed,
350 // parsing tt's probably shouldn't require a parser at all.
351 use super::lexer::make_reader_with_embedded_idents as make_reader;
352 let cfg = Vec::new();
353 let srdr = make_reader(&sess.span_diagnostic, filemap);
354 let mut p1 = Parser::new(sess, cfg, box srdr);
355 p1.parse_all_token_trees()
359 /// Abort if necessary
360 pub fn maybe_aborted<T>(result: T, mut p: Parser) -> T {
365 /// Parse a string representing a character literal into its final form.
366 /// Rather than just accepting/rejecting a given literal, unescapes it as
367 /// well. Can take any slice prefixed by a character escape. Returns the
368 /// character and the number of characters consumed.
369 pub fn char_lit(lit: &str) -> (char, int) {
370 use std::{num, char};
372 let mut chars = lit.chars();
373 let c = match (chars.next(), chars.next()) {
374 (Some(c), None) if c != '\\' => return (c, 1),
375 (Some('\\'), Some(c)) => match c {
385 _ => panic!("lexer accepted invalid char escape `{}`", lit)
389 Some(x) => return (x, 2),
393 let msg = format!("lexer should have rejected a bad character escape {}", lit);
396 fn esc(len: uint, lit: &str) -> Option<(char, int)> {
397 num::from_str_radix(lit[2..len], 16)
398 .and_then(char::from_u32)
399 .map(|x| (x, len as int))
402 let unicode_escape = |&: | -> Option<(char, int)>
403 if lit.as_bytes()[2] == b'{' {
404 let idx = lit.find('}').expect(msg2);
405 let subslice = lit[3..idx];
406 num::from_str_radix(subslice, 16)
407 .and_then(char::from_u32)
408 .map(|x| (x, subslice.chars().count() as int + 4))
414 return match lit.as_bytes()[1] as char {
415 'x' | 'X' => esc(4, lit),
416 'u' => unicode_escape(),
422 /// Parse a string representing a string literal into its final form. Does
424 pub fn str_lit(lit: &str) -> String {
425 debug!("parse_str_lit: given {}", lit.escape_default());
426 let mut res = String::with_capacity(lit.len());
428 // FIXME #8372: This could be a for-loop if it didn't borrow the iterator
429 let error = |&: i| format!("lexer should have rejected {} at {}", lit, i);
431 /// Eat everything up to a non-whitespace
432 fn eat<'a>(it: &mut iter::Peekable<(uint, char), str::CharIndices<'a>>) {
434 match it.peek().map(|x| x.1) {
435 Some(' ') | Some('\n') | Some('\r') | Some('\t') => {
443 let mut chars = lit.char_indices().peekable();
449 let ch = chars.peek().unwrap_or_else(|| {
450 panic!("{}", error(i).as_slice())
455 } else if ch == '\r' {
457 let ch = chars.peek().unwrap_or_else(|| {
458 panic!("{}", error(i).as_slice())
462 panic!("lexer accepted bare CR");
466 // otherwise, a normal escape
467 let (c, n) = char_lit(lit[i..]);
468 for _ in range(0, n - 1) { // we don't need to move past the first \
475 let ch = chars.peek().unwrap_or_else(|| {
476 panic!("{}", error(i).as_slice())
480 panic!("lexer accepted bare CR");
492 res.shrink_to_fit(); // probably not going to do anything, unless there was an escape.
493 debug!("parse_str_lit: returning {}", res);
497 /// Parse a string representing a raw string literal into its final form. The
498 /// only operation this does is convert embedded CRLF into a single LF.
499 pub fn raw_str_lit(lit: &str) -> String {
500 debug!("raw_str_lit: given {}", lit.escape_default());
501 let mut res = String::with_capacity(lit.len());
503 // FIXME #8372: This could be a for-loop if it didn't borrow the iterator
504 let mut chars = lit.chars().peekable();
509 if *chars.peek().unwrap() != '\n' {
510 panic!("lexer accepted bare CR");
526 // check if `s` looks like i32 or u1234 etc.
527 fn looks_like_width_suffix(first_chars: &[char], s: &str) -> bool {
529 first_chars.contains(&s.char_at(0)) &&
530 s[1..].chars().all(|c| '0' <= c && c <= '9')
533 fn filtered_float_lit(data: token::InternedString, suffix: Option<&str>,
534 sd: &SpanHandler, sp: Span) -> ast::Lit_ {
535 debug!("filtered_float_lit: {}, {}", data, suffix);
537 Some("f32") => ast::LitFloat(data, ast::TyF32),
538 Some("f64") => ast::LitFloat(data, ast::TyF64),
540 if suf.len() >= 2 && looks_like_width_suffix(&['f'], suf) {
541 // if it looks like a width, lets try to be helpful.
542 sd.span_err(sp, &*format!("illegal width `{}` for float literal, \
543 valid widths are 32 and 64", suf[1..]));
545 sd.span_err(sp, &*format!("illegal suffix `{}` for float literal, \
546 valid suffixes are `f32` and `f64`", suf));
549 ast::LitFloatUnsuffixed(data)
551 None => ast::LitFloatUnsuffixed(data)
554 pub fn float_lit(s: &str, suffix: Option<&str>, sd: &SpanHandler, sp: Span) -> ast::Lit_ {
555 debug!("float_lit: {}, {}", s, suffix);
556 // FIXME #2252: bounds checking float literals is defered until trans
557 let s = s.chars().filter(|&c| c != '_').collect::<String>();
558 let data = token::intern_and_get_ident(&*s);
559 filtered_float_lit(data, suffix, sd, sp)
562 /// Parse a string representing a byte literal into its final form. Similar to `char_lit`
563 pub fn byte_lit(lit: &str) -> (u8, uint) {
564 let err = |&: i| format!("lexer accepted invalid byte literal {} step {}", lit, i);
567 (lit.as_bytes()[0], 1)
569 assert!(lit.as_bytes()[0] == b'\\', err(0i));
570 let b = match lit.as_bytes()[1] {
579 match ::std::num::from_str_radix::<u64>(lit[2..4], 16) {
586 None => panic!(err(3))
594 pub fn binary_lit(lit: &str) -> Rc<Vec<u8>> {
595 let mut res = Vec::with_capacity(lit.len());
597 // FIXME #8372: This could be a for-loop if it didn't borrow the iterator
598 let error = |&: i| format!("lexer should have rejected {} at {}", lit, i);
600 /// Eat everything up to a non-whitespace
601 fn eat<'a, I: Iterator<Item=(uint, u8)>>(it: &mut iter::Peekable<(uint, u8), I>) {
603 match it.peek().map(|x| x.1) {
604 Some(b' ') | Some(b'\n') | Some(b'\r') | Some(b'\t') => {
612 // binary literals *must* be ASCII, but the escapes don't have to be
613 let mut chars = lit.bytes().enumerate().peekable();
616 Some((i, b'\\')) => {
618 match chars.peek().expect(em.as_slice()).1 {
619 b'\n' => eat(&mut chars),
622 if chars.peek().expect(em.as_slice()).1 != b'\n' {
623 panic!("lexer accepted bare CR");
628 // otherwise, a normal escape
629 let (c, n) = byte_lit(lit[i..]);
630 // we don't need to move past the first \
631 for _ in range(0, n - 1) {
638 Some((i, b'\r')) => {
640 if chars.peek().expect(em.as_slice()).1 != b'\n' {
641 panic!("lexer accepted bare CR");
646 Some((_, c)) => res.push(c),
654 pub fn integer_lit(s: &str, suffix: Option<&str>, sd: &SpanHandler, sp: Span) -> ast::Lit_ {
655 // s can only be ascii, byte indexing is fine
657 let s2 = s.chars().filter(|&c| c != '_').collect::<String>();
660 debug!("integer_lit: {}, {}", s, suffix);
664 let mut ty = ast::UnsuffixedIntLit(ast::Plus);
666 if s.char_at(0) == '0' && s.len() > 1 {
675 // 1f64 and 2f32 etc. are valid float literals.
677 Some(suf) if looks_like_width_suffix(&['f'], suf) => {
679 16u => sd.span_err(sp, "hexadecimal float literal is not supported"),
680 8u => sd.span_err(sp, "octal float literal is not supported"),
681 2u => sd.span_err(sp, "binary float literal is not supported"),
684 let ident = token::intern_and_get_ident(&*s);
685 return filtered_float_lit(ident, suffix, sd, sp)
694 if let Some(suf) = suffix {
695 if suf.is_empty() { sd.span_bug(sp, "found empty literal suffix in Some")}
697 "i" => ast::SignedIntLit(ast::TyI, ast::Plus),
698 "i8" => ast::SignedIntLit(ast::TyI8, ast::Plus),
699 "i16" => ast::SignedIntLit(ast::TyI16, ast::Plus),
700 "i32" => ast::SignedIntLit(ast::TyI32, ast::Plus),
701 "i64" => ast::SignedIntLit(ast::TyI64, ast::Plus),
702 "u" => ast::UnsignedIntLit(ast::TyU),
703 "u8" => ast::UnsignedIntLit(ast::TyU8),
704 "u16" => ast::UnsignedIntLit(ast::TyU16),
705 "u32" => ast::UnsignedIntLit(ast::TyU32),
706 "u64" => ast::UnsignedIntLit(ast::TyU64),
708 // i<digits> and u<digits> look like widths, so lets
709 // give an error message along those lines
710 if looks_like_width_suffix(&['i', 'u'], suf) {
711 sd.span_err(sp, &*format!("illegal width `{}` for integer literal; \
712 valid widths are 8, 16, 32 and 64",
715 sd.span_err(sp, &*format!("illegal suffix `{}` for numeric literal", suf));
723 debug!("integer_lit: the type is {}, base {}, the new string is {}, the original \
724 string was {}, the original suffix was {}", ty, base, s, orig, suffix);
726 let res: u64 = match ::std::num::from_str_radix(s, base) {
728 None => { sd.span_err(sp, "int literal is too large"); 0 }
732 let sign = ast::Sign::new(res);
734 ast::SignedIntLit(t, _) => ast::LitInt(res, ast::SignedIntLit(t, sign)),
735 ast::UnsuffixedIntLit(_) => ast::LitInt(res, ast::UnsuffixedIntLit(sign)),
736 us@ast::UnsignedIntLit(_) => ast::LitInt(res, us)
744 use codemap::{Span, BytePos, Pos, Spanned, NO_EXPANSION};
745 use owned_slice::OwnedSlice;
748 use attr::{first_attr_value_str_by_name, AttrMetaMethods};
749 use parse::parser::Parser;
750 use parse::token::{str_to_ident};
751 use print::pprust::view_item_to_string;
753 use util::parser_testing::{string_to_tts, string_to_parser};
754 use util::parser_testing::{string_to_expr, string_to_item};
755 use util::parser_testing::{string_to_stmt, string_to_view_item};
757 // produce a codemap::span
758 fn sp(a: u32, b: u32) -> Span {
759 Span {lo: BytePos(a), hi: BytePos(b), expn_id: NO_EXPANSION}
762 #[test] fn path_exprs_1() {
763 assert!(string_to_expr("a".to_string()) ==
765 id: ast::DUMMY_NODE_ID,
766 node: ast::ExprPath(ast::Path {
771 identifier: str_to_ident("a"),
772 parameters: ast::PathParameters::none(),
780 #[test] fn path_exprs_2 () {
781 assert!(string_to_expr("::a::b".to_string()) ==
783 id: ast::DUMMY_NODE_ID,
784 node: ast::ExprPath(ast::Path {
789 identifier: str_to_ident("a"),
790 parameters: ast::PathParameters::none(),
793 identifier: str_to_ident("b"),
794 parameters: ast::PathParameters::none(),
803 #[test] fn bad_path_expr_1() {
804 string_to_expr("::abc::def::return".to_string());
807 // check the token-tree-ization of macros
809 fn string_to_tts_macro () {
810 let tts = string_to_tts("macro_rules! zip (($a)=>($a))".to_string());
811 let tts: &[ast::TokenTree] = tts[];
813 [ast::TtToken(_, token::Ident(name_macro_rules, token::Plain)),
814 ast::TtToken(_, token::Not),
815 ast::TtToken(_, token::Ident(name_zip, token::Plain)),
816 ast::TtDelimited(_, ref macro_delimed)]
817 if name_macro_rules.as_str() == "macro_rules"
818 && name_zip.as_str() == "zip" => {
819 match macro_delimed.tts[] {
820 [ast::TtDelimited(_, ref first_delimed),
821 ast::TtToken(_, token::FatArrow),
822 ast::TtDelimited(_, ref second_delimed)]
823 if macro_delimed.delim == token::Paren => {
824 match first_delimed.tts[] {
825 [ast::TtToken(_, token::Dollar),
826 ast::TtToken(_, token::Ident(name, token::Plain))]
827 if first_delimed.delim == token::Paren
828 && name.as_str() == "a" => {},
829 _ => panic!("value 3: {}", **first_delimed),
831 match second_delimed.tts[] {
832 [ast::TtToken(_, token::Dollar),
833 ast::TtToken(_, token::Ident(name, token::Plain))]
834 if second_delimed.delim == token::Paren
835 && name.as_str() == "a" => {},
836 _ => panic!("value 4: {}", **second_delimed),
839 _ => panic!("value 2: {}", **macro_delimed),
842 _ => panic!("value: {}",tts),
847 fn string_to_tts_1 () {
848 let tts = string_to_tts("fn a (b : int) { b; }".to_string());
849 assert_eq!(json::encode(&tts),
852 \"variant\":\"TtToken\",\
856 \"variant\":\"Ident\",\
865 \"variant\":\"TtToken\",\
869 \"variant\":\"Ident\",\
878 \"variant\":\"TtDelimited\",\
882 \"delim\":\"Paren\",\
886 \"variant\":\"TtToken\",\
890 \"variant\":\"Ident\",\
899 \"variant\":\"TtToken\",\
906 \"variant\":\"TtToken\",\
910 \"variant\":\"Ident\",\
924 \"variant\":\"TtDelimited\",\
928 \"delim\":\"Brace\",\
932 \"variant\":\"TtToken\",\
936 \"variant\":\"Ident\",\
945 \"variant\":\"TtToken\",\
960 #[test] fn ret_expr() {
961 assert!(string_to_expr("return d".to_string()) ==
963 id: ast::DUMMY_NODE_ID,
964 node:ast::ExprRet(Some(P(ast::Expr{
965 id: ast::DUMMY_NODE_ID,
966 node:ast::ExprPath(ast::Path{
971 identifier: str_to_ident("d"),
972 parameters: ast::PathParameters::none(),
982 #[test] fn parse_stmt_1 () {
983 assert!(string_to_stmt("b;".to_string()) ==
985 node: ast::StmtExpr(P(ast::Expr {
986 id: ast::DUMMY_NODE_ID,
987 node: ast::ExprPath(ast::Path {
992 identifier: str_to_ident("b"),
993 parameters: ast::PathParameters::none(),
1003 fn parser_done(p: Parser){
1004 assert_eq!(p.token.clone(), token::Eof);
1007 #[test] fn parse_ident_pat () {
1008 let sess = new_parse_sess();
1009 let mut parser = string_to_parser(&sess, "b".to_string());
1010 assert!(parser.parse_pat()
1012 id: ast::DUMMY_NODE_ID,
1013 node: ast::PatIdent(ast::BindByValue(ast::MutImmutable),
1014 Spanned{ span:sp(0, 1),
1015 node: str_to_ident("b")
1019 parser_done(parser);
1022 // check the contents of the tt manually:
1023 #[test] fn parse_fundecl () {
1024 // this test depends on the intern order of "fn" and "int"
1025 assert!(string_to_item("fn a (b : int) { b; }".to_string()) ==
1027 P(ast::Item{ident:str_to_ident("a"),
1029 id: ast::DUMMY_NODE_ID,
1030 node: ast::ItemFn(P(ast::FnDecl {
1031 inputs: vec!(ast::Arg{
1032 ty: P(ast::Ty{id: ast::DUMMY_NODE_ID,
1033 node: ast::TyPath(ast::Path{
1039 str_to_ident("int"),
1040 parameters: ast::PathParameters::none(),
1043 }, ast::DUMMY_NODE_ID),
1047 id: ast::DUMMY_NODE_ID,
1048 node: ast::PatIdent(
1049 ast::BindByValue(ast::MutImmutable),
1052 node: str_to_ident("b")},
1057 id: ast::DUMMY_NODE_ID
1059 output: ast::Return(P(ast::Ty{id: ast::DUMMY_NODE_ID,
1060 node: ast::TyTup(vec![]),
1061 span:sp(15,15)})), // not sure
1064 ast::Unsafety::Normal,
1066 ast::Generics{ // no idea on either of these:
1067 lifetimes: Vec::new(),
1068 ty_params: OwnedSlice::empty(),
1069 where_clause: ast::WhereClause {
1070 id: ast::DUMMY_NODE_ID,
1071 predicates: Vec::new(),
1075 view_items: Vec::new(),
1076 stmts: vec!(P(Spanned{
1077 node: ast::StmtSemi(P(ast::Expr{
1078 id: ast::DUMMY_NODE_ID,
1079 node: ast::ExprPath(
1089 ast::PathParameters::none(),
1094 ast::DUMMY_NODE_ID),
1097 id: ast::DUMMY_NODE_ID,
1098 rules: ast::DefaultBlock, // no idea
1101 vis: ast::Inherited,
1105 #[test] fn parse_use() {
1106 let use_s = "use foo::bar::baz;";
1107 let vitem = string_to_view_item(use_s.to_string());
1108 let vitem_s = view_item_to_string(&vitem);
1109 assert_eq!(vitem_s[], use_s);
1111 let use_s = "use foo::bar as baz;";
1112 let vitem = string_to_view_item(use_s.to_string());
1113 let vitem_s = view_item_to_string(&vitem);
1114 assert_eq!(vitem_s[], use_s);
1117 #[test] fn parse_extern_crate() {
1118 let ex_s = "extern crate foo;";
1119 let vitem = string_to_view_item(ex_s.to_string());
1120 let vitem_s = view_item_to_string(&vitem);
1121 assert_eq!(vitem_s[], ex_s);
1123 let ex_s = "extern crate \"foo\" as bar;";
1124 let vitem = string_to_view_item(ex_s.to_string());
1125 let vitem_s = view_item_to_string(&vitem);
1126 assert_eq!(vitem_s[], ex_s);
1129 fn get_spans_of_pat_idents(src: &str) -> Vec<Span> {
1130 let item = string_to_item(src.to_string()).unwrap();
1132 struct PatIdentVisitor {
1135 impl<'v> ::visit::Visitor<'v> for PatIdentVisitor {
1136 fn visit_pat(&mut self, p: &'v ast::Pat) {
1138 ast::PatIdent(_ , ref spannedident, _) => {
1139 self.spans.push(spannedident.span.clone());
1142 ::visit::walk_pat(self, p);
1147 let mut v = PatIdentVisitor { spans: Vec::new() };
1148 ::visit::walk_item(&mut v, &*item);
1152 #[test] fn span_of_self_arg_pat_idents_are_correct() {
1154 let srcs = ["impl z { fn a (&self, &myarg: int) {} }",
1155 "impl z { fn a (&mut self, &myarg: int) {} }",
1156 "impl z { fn a (&'a self, &myarg: int) {} }",
1157 "impl z { fn a (self, &myarg: int) {} }",
1158 "impl z { fn a (self: Foo, &myarg: int) {} }",
1161 for &src in srcs.iter() {
1162 let spans = get_spans_of_pat_idents(src);
1163 let Span{lo:lo,hi:hi,..} = spans[0];
1164 assert!("self" == src[lo.to_uint()..hi.to_uint()],
1165 "\"{}\" != \"self\". src=\"{}\"",
1166 src[lo.to_uint()..hi.to_uint()], src)
1170 #[test] fn parse_exprs () {
1171 // just make sure that they parse....
1172 string_to_expr("3 + 4".to_string());
1173 string_to_expr("a::z.froob(b,&(987+3))".to_string());
1176 #[test] fn attrs_fix_bug () {
1177 string_to_item("pub fn mk_file_writer(path: &Path, flags: &[FileFlag])
1178 -> Result<Box<Writer>, String> {
1181 (O_WRONLY | libc::consts::os::extra::O_BINARY) as c_int
1185 fn wb() -> c_int { O_WRONLY as c_int }
1187 let mut fflags: c_int = wb();
1191 #[test] fn crlf_doc_comments() {
1192 let sess = new_parse_sess();
1194 let name = "<source>".to_string();
1195 let source = "/// doc comment\r\nfn foo() {}".to_string();
1196 let item = parse_item_from_source_str(name.clone(), source, Vec::new(), &sess).unwrap();
1197 let doc = first_attr_value_str_by_name(item.attrs.as_slice(), "doc").unwrap();
1198 assert_eq!(doc.get(), "/// doc comment");
1200 let source = "/// doc comment\r\n/// line 2\r\nfn foo() {}".to_string();
1201 let item = parse_item_from_source_str(name.clone(), source, Vec::new(), &sess).unwrap();
1202 let docs = item.attrs.iter().filter(|a| a.name().get() == "doc")
1203 .map(|a| a.value_str().unwrap().get().to_string()).collect::<Vec<_>>();
1204 let b: &[_] = &["/// doc comment".to_string(), "/// line 2".to_string()];
1205 assert_eq!(docs[], b);
1207 let source = "/** doc comment\r\n * with CRLF */\r\nfn foo() {}".to_string();
1208 let item = parse_item_from_source_str(name, source, Vec::new(), &sess).unwrap();
1209 let doc = first_attr_value_str_by_name(item.attrs.as_slice(), "doc").unwrap();
1210 assert_eq!(doc.get(), "/** doc comment\n * with CRLF */");