]> git.proxmox.com Git - rustc.git/blob - src/libsyntax/parse/mod.rs
f1a3b523cfd93cef737bd75d0311c04f3c538ca8
[rustc.git] / src / libsyntax / parse / mod.rs
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.
4 //
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.
10
11 //! The main parser interface
12
13 use ast::{self, CrateConfig};
14 use codemap::CodeMap;
15 use syntax_pos::{self, Span, FileMap};
16 use errors::{Handler, ColorConfig, DiagnosticBuilder};
17 use feature_gate::UnstableFeatures;
18 use parse::parser::Parser;
19 use ptr::P;
20 use str::char_at;
21 use symbol::Symbol;
22 use tokenstream;
23
24 use std::cell::RefCell;
25 use std::collections::HashSet;
26 use std::iter;
27 use std::path::{Path, PathBuf};
28 use std::rc::Rc;
29 use std::str;
30
31 use rustc_i128::u128;
32
33 pub type PResult<'a, T> = Result<T, DiagnosticBuilder<'a>>;
34
35 #[macro_use]
36 pub mod parser;
37
38 pub mod lexer;
39 pub mod token;
40 pub mod attr;
41
42 pub mod common;
43 pub mod classify;
44 pub mod obsolete;
45
46 /// Info about a parsing session.
47 pub struct ParseSess {
48 pub span_diagnostic: Handler,
49 pub unstable_features: UnstableFeatures,
50 pub config: CrateConfig,
51 /// Used to determine and report recursive mod inclusions
52 included_mod_stack: RefCell<Vec<PathBuf>>,
53 code_map: Rc<CodeMap>,
54 }
55
56 impl ParseSess {
57 pub fn new() -> Self {
58 let cm = Rc::new(CodeMap::new());
59 let handler = Handler::with_tty_emitter(ColorConfig::Auto,
60 true,
61 false,
62 Some(cm.clone()));
63 ParseSess::with_span_handler(handler, cm)
64 }
65
66 pub fn with_span_handler(handler: Handler, code_map: Rc<CodeMap>) -> ParseSess {
67 ParseSess {
68 span_diagnostic: handler,
69 unstable_features: UnstableFeatures::from_environment(),
70 config: HashSet::new(),
71 included_mod_stack: RefCell::new(vec![]),
72 code_map: code_map
73 }
74 }
75
76 pub fn codemap(&self) -> &CodeMap {
77 &self.code_map
78 }
79 }
80
81 #[derive(Clone)]
82 pub struct Directory {
83 pub path: PathBuf,
84 pub ownership: DirectoryOwnership,
85 }
86
87 #[derive(Copy, Clone)]
88 pub enum DirectoryOwnership {
89 Owned,
90 UnownedViaBlock,
91 UnownedViaMod(bool /* legacy warnings? */),
92 }
93
94 // a bunch of utility functions of the form parse_<thing>_from_<source>
95 // where <thing> includes crate, expr, item, stmt, tts, and one that
96 // uses a HOF to parse anything, and <source> includes file and
97 // source_str.
98
99 pub fn parse_crate_from_file<'a>(input: &Path, sess: &'a ParseSess) -> PResult<'a, ast::Crate> {
100 let mut parser = new_parser_from_file(sess, input);
101 parser.parse_crate_mod()
102 }
103
104 pub fn parse_crate_attrs_from_file<'a>(input: &Path, sess: &'a ParseSess)
105 -> PResult<'a, Vec<ast::Attribute>> {
106 let mut parser = new_parser_from_file(sess, input);
107 parser.parse_inner_attributes()
108 }
109
110 pub fn parse_crate_from_source_str<'a>(name: String, source: String, sess: &'a ParseSess)
111 -> PResult<'a, ast::Crate> {
112 new_parser_from_source_str(sess, name, source).parse_crate_mod()
113 }
114
115 pub fn parse_crate_attrs_from_source_str<'a>(name: String, source: String, sess: &'a ParseSess)
116 -> PResult<'a, Vec<ast::Attribute>> {
117 new_parser_from_source_str(sess, name, source).parse_inner_attributes()
118 }
119
120 pub fn parse_expr_from_source_str<'a>(name: String, source: String, sess: &'a ParseSess)
121 -> PResult<'a, P<ast::Expr>> {
122 new_parser_from_source_str(sess, name, source).parse_expr()
123 }
124
125 /// Parses an item.
126 ///
127 /// Returns `Ok(Some(item))` when successful, `Ok(None)` when no item was found, and`Err`
128 /// when a syntax error occurred.
129 pub fn parse_item_from_source_str<'a>(name: String, source: String, sess: &'a ParseSess)
130 -> PResult<'a, Option<P<ast::Item>>> {
131 new_parser_from_source_str(sess, name, source).parse_item()
132 }
133
134 pub fn parse_meta_from_source_str<'a>(name: String, source: String, sess: &'a ParseSess)
135 -> PResult<'a, ast::MetaItem> {
136 new_parser_from_source_str(sess, name, source).parse_meta_item()
137 }
138
139 pub fn parse_stmt_from_source_str<'a>(name: String, source: String, sess: &'a ParseSess)
140 -> PResult<'a, Option<ast::Stmt>> {
141 new_parser_from_source_str(sess, name, source).parse_stmt()
142 }
143
144 // Warning: This parses with quote_depth > 0, which is not the default.
145 pub fn parse_tts_from_source_str<'a>(name: String, source: String, sess: &'a ParseSess)
146 -> PResult<'a, Vec<tokenstream::TokenTree>> {
147 let mut p = new_parser_from_source_str(sess, name, source);
148 p.quote_depth += 1;
149 // right now this is re-creating the token trees from ... token trees.
150 p.parse_all_token_trees()
151 }
152
153 // Create a new parser from a source string
154 pub fn new_parser_from_source_str<'a>(sess: &'a ParseSess, name: String, source: String)
155 -> Parser<'a> {
156 filemap_to_parser(sess, sess.codemap().new_filemap(name, None, source))
157 }
158
159 /// Create a new parser, handling errors as appropriate
160 /// if the file doesn't exist
161 pub fn new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path) -> Parser<'a> {
162 filemap_to_parser(sess, file_to_filemap(sess, path, None))
163 }
164
165 /// Given a session, a crate config, a path, and a span, add
166 /// the file at the given path to the codemap, and return a parser.
167 /// On an error, use the given span as the source of the problem.
168 pub fn new_sub_parser_from_file<'a>(sess: &'a ParseSess,
169 path: &Path,
170 directory_ownership: DirectoryOwnership,
171 module_name: Option<String>,
172 sp: Span) -> Parser<'a> {
173 let mut p = filemap_to_parser(sess, file_to_filemap(sess, path, Some(sp)));
174 p.directory.ownership = directory_ownership;
175 p.root_module_name = module_name;
176 p
177 }
178
179 /// Given a filemap and config, return a parser
180 pub fn filemap_to_parser<'a>(sess: &'a ParseSess, filemap: Rc<FileMap>, ) -> Parser<'a> {
181 let end_pos = filemap.end_pos;
182 let mut parser = tts_to_parser(sess, filemap_to_tts(sess, filemap));
183
184 if parser.token == token::Eof && parser.span == syntax_pos::DUMMY_SP {
185 parser.span = syntax_pos::mk_sp(end_pos, end_pos);
186 }
187
188 parser
189 }
190
191 // must preserve old name for now, because quote! from the *existing*
192 // compiler expands into it
193 pub fn new_parser_from_tts<'a>(sess: &'a ParseSess, tts: Vec<tokenstream::TokenTree>)
194 -> Parser<'a> {
195 tts_to_parser(sess, tts)
196 }
197
198 pub fn new_parser_from_ts<'a>(sess: &'a ParseSess, ts: tokenstream::TokenStream) -> Parser<'a> {
199 tts_to_parser(sess, ts.trees().cloned().collect())
200 }
201
202
203 // base abstractions
204
205 /// Given a session and a path and an optional span (for error reporting),
206 /// add the path to the session's codemap and return the new filemap.
207 fn file_to_filemap(sess: &ParseSess, path: &Path, spanopt: Option<Span>)
208 -> Rc<FileMap> {
209 match sess.codemap().load_file(path) {
210 Ok(filemap) => filemap,
211 Err(e) => {
212 let msg = format!("couldn't read {:?}: {}", path.display(), e);
213 match spanopt {
214 Some(sp) => panic!(sess.span_diagnostic.span_fatal(sp, &msg)),
215 None => panic!(sess.span_diagnostic.fatal(&msg))
216 }
217 }
218 }
219 }
220
221 /// Given a filemap, produce a sequence of token-trees
222 pub fn filemap_to_tts(sess: &ParseSess, filemap: Rc<FileMap>) -> Vec<tokenstream::TokenTree> {
223 let mut srdr = lexer::StringReader::new(sess, filemap);
224 srdr.real_token();
225 panictry!(srdr.parse_all_token_trees())
226 }
227
228 /// Given tts and the ParseSess, produce a parser
229 pub fn tts_to_parser<'a>(sess: &'a ParseSess, tts: Vec<tokenstream::TokenTree>) -> Parser<'a> {
230 let mut p = Parser::new(sess, tts, None, false);
231 p.check_unknown_macro_variable();
232 p
233 }
234
235 /// Parse a string representing a character literal into its final form.
236 /// Rather than just accepting/rejecting a given literal, unescapes it as
237 /// well. Can take any slice prefixed by a character escape. Returns the
238 /// character and the number of characters consumed.
239 pub fn char_lit(lit: &str) -> (char, isize) {
240 use std::char;
241
242 // Handle non-escaped chars first.
243 if lit.as_bytes()[0] != b'\\' {
244 // If the first byte isn't '\\' it might part of a multi-byte char, so
245 // get the char with chars().
246 let c = lit.chars().next().unwrap();
247 return (c, 1);
248 }
249
250 // Handle escaped chars.
251 match lit.as_bytes()[1] as char {
252 '"' => ('"', 2),
253 'n' => ('\n', 2),
254 'r' => ('\r', 2),
255 't' => ('\t', 2),
256 '\\' => ('\\', 2),
257 '\'' => ('\'', 2),
258 '0' => ('\0', 2),
259 'x' => {
260 let v = u32::from_str_radix(&lit[2..4], 16).unwrap();
261 let c = char::from_u32(v).unwrap();
262 (c, 4)
263 }
264 'u' => {
265 assert!(lit.as_bytes()[2] == b'{');
266 let idx = lit.find('}').unwrap();
267 let v = u32::from_str_radix(&lit[3..idx], 16).unwrap();
268 let c = char::from_u32(v).unwrap();
269 (c, (idx + 1) as isize)
270 }
271 _ => panic!("lexer should have rejected a bad character escape {}", lit)
272 }
273 }
274
275 /// Parse a string representing a string literal into its final form. Does
276 /// unescaping.
277 pub fn str_lit(lit: &str) -> String {
278 debug!("parse_str_lit: given {}", lit.escape_default());
279 let mut res = String::with_capacity(lit.len());
280
281 // FIXME #8372: This could be a for-loop if it didn't borrow the iterator
282 let error = |i| format!("lexer should have rejected {} at {}", lit, i);
283
284 /// Eat everything up to a non-whitespace
285 fn eat<'a>(it: &mut iter::Peekable<str::CharIndices<'a>>) {
286 loop {
287 match it.peek().map(|x| x.1) {
288 Some(' ') | Some('\n') | Some('\r') | Some('\t') => {
289 it.next();
290 },
291 _ => { break; }
292 }
293 }
294 }
295
296 let mut chars = lit.char_indices().peekable();
297 loop {
298 match chars.next() {
299 Some((i, c)) => {
300 match c {
301 '\\' => {
302 let ch = chars.peek().unwrap_or_else(|| {
303 panic!("{}", error(i))
304 }).1;
305
306 if ch == '\n' {
307 eat(&mut chars);
308 } else if ch == '\r' {
309 chars.next();
310 let ch = chars.peek().unwrap_or_else(|| {
311 panic!("{}", error(i))
312 }).1;
313
314 if ch != '\n' {
315 panic!("lexer accepted bare CR");
316 }
317 eat(&mut chars);
318 } else {
319 // otherwise, a normal escape
320 let (c, n) = char_lit(&lit[i..]);
321 for _ in 0..n - 1 { // we don't need to move past the first \
322 chars.next();
323 }
324 res.push(c);
325 }
326 },
327 '\r' => {
328 let ch = chars.peek().unwrap_or_else(|| {
329 panic!("{}", error(i))
330 }).1;
331
332 if ch != '\n' {
333 panic!("lexer accepted bare CR");
334 }
335 chars.next();
336 res.push('\n');
337 }
338 c => res.push(c),
339 }
340 },
341 None => break
342 }
343 }
344
345 res.shrink_to_fit(); // probably not going to do anything, unless there was an escape.
346 debug!("parse_str_lit: returning {}", res);
347 res
348 }
349
350 /// Parse a string representing a raw string literal into its final form. The
351 /// only operation this does is convert embedded CRLF into a single LF.
352 pub fn raw_str_lit(lit: &str) -> String {
353 debug!("raw_str_lit: given {}", lit.escape_default());
354 let mut res = String::with_capacity(lit.len());
355
356 // FIXME #8372: This could be a for-loop if it didn't borrow the iterator
357 let mut chars = lit.chars().peekable();
358 loop {
359 match chars.next() {
360 Some(c) => {
361 if c == '\r' {
362 if *chars.peek().unwrap() != '\n' {
363 panic!("lexer accepted bare CR");
364 }
365 chars.next();
366 res.push('\n');
367 } else {
368 res.push(c);
369 }
370 },
371 None => break
372 }
373 }
374
375 res.shrink_to_fit();
376 res
377 }
378
379 // check if `s` looks like i32 or u1234 etc.
380 fn looks_like_width_suffix(first_chars: &[char], s: &str) -> bool {
381 s.len() > 1 &&
382 first_chars.contains(&char_at(s, 0)) &&
383 s[1..].chars().all(|c| '0' <= c && c <= '9')
384 }
385
386 fn filtered_float_lit(data: Symbol, suffix: Option<Symbol>, sd: &Handler, sp: Span)
387 -> ast::LitKind {
388 debug!("filtered_float_lit: {}, {:?}", data, suffix);
389 let suffix = match suffix {
390 Some(suffix) => suffix,
391 None => return ast::LitKind::FloatUnsuffixed(data),
392 };
393
394 match &*suffix.as_str() {
395 "f32" => ast::LitKind::Float(data, ast::FloatTy::F32),
396 "f64" => ast::LitKind::Float(data, ast::FloatTy::F64),
397 suf => {
398 if suf.len() >= 2 && looks_like_width_suffix(&['f'], suf) {
399 // if it looks like a width, lets try to be helpful.
400 sd.struct_span_err(sp, &format!("invalid width `{}` for float literal", &suf[1..]))
401 .help("valid widths are 32 and 64")
402 .emit();
403 } else {
404 sd.struct_span_err(sp, &format!("invalid suffix `{}` for float literal", suf))
405 .help("valid suffixes are `f32` and `f64`")
406 .emit();
407 }
408
409 ast::LitKind::FloatUnsuffixed(data)
410 }
411 }
412 }
413 pub fn float_lit(s: &str, suffix: Option<Symbol>, sd: &Handler, sp: Span) -> ast::LitKind {
414 debug!("float_lit: {:?}, {:?}", s, suffix);
415 // FIXME #2252: bounds checking float literals is deferred until trans
416 let s = s.chars().filter(|&c| c != '_').collect::<String>();
417 filtered_float_lit(Symbol::intern(&s), suffix, sd, sp)
418 }
419
420 /// Parse a string representing a byte literal into its final form. Similar to `char_lit`
421 pub fn byte_lit(lit: &str) -> (u8, usize) {
422 let err = |i| format!("lexer accepted invalid byte literal {} step {}", lit, i);
423
424 if lit.len() == 1 {
425 (lit.as_bytes()[0], 1)
426 } else {
427 assert!(lit.as_bytes()[0] == b'\\', err(0));
428 let b = match lit.as_bytes()[1] {
429 b'"' => b'"',
430 b'n' => b'\n',
431 b'r' => b'\r',
432 b't' => b'\t',
433 b'\\' => b'\\',
434 b'\'' => b'\'',
435 b'0' => b'\0',
436 _ => {
437 match u64::from_str_radix(&lit[2..4], 16).ok() {
438 Some(c) =>
439 if c > 0xFF {
440 panic!(err(2))
441 } else {
442 return (c as u8, 4)
443 },
444 None => panic!(err(3))
445 }
446 }
447 };
448 return (b, 2);
449 }
450 }
451
452 pub fn byte_str_lit(lit: &str) -> Rc<Vec<u8>> {
453 let mut res = Vec::with_capacity(lit.len());
454
455 // FIXME #8372: This could be a for-loop if it didn't borrow the iterator
456 let error = |i| format!("lexer should have rejected {} at {}", lit, i);
457
458 /// Eat everything up to a non-whitespace
459 fn eat<'a, I: Iterator<Item=(usize, u8)>>(it: &mut iter::Peekable<I>) {
460 loop {
461 match it.peek().map(|x| x.1) {
462 Some(b' ') | Some(b'\n') | Some(b'\r') | Some(b'\t') => {
463 it.next();
464 },
465 _ => { break; }
466 }
467 }
468 }
469
470 // byte string literals *must* be ASCII, but the escapes don't have to be
471 let mut chars = lit.bytes().enumerate().peekable();
472 loop {
473 match chars.next() {
474 Some((i, b'\\')) => {
475 let em = error(i);
476 match chars.peek().expect(&em).1 {
477 b'\n' => eat(&mut chars),
478 b'\r' => {
479 chars.next();
480 if chars.peek().expect(&em).1 != b'\n' {
481 panic!("lexer accepted bare CR");
482 }
483 eat(&mut chars);
484 }
485 _ => {
486 // otherwise, a normal escape
487 let (c, n) = byte_lit(&lit[i..]);
488 // we don't need to move past the first \
489 for _ in 0..n - 1 {
490 chars.next();
491 }
492 res.push(c);
493 }
494 }
495 },
496 Some((i, b'\r')) => {
497 let em = error(i);
498 if chars.peek().expect(&em).1 != b'\n' {
499 panic!("lexer accepted bare CR");
500 }
501 chars.next();
502 res.push(b'\n');
503 }
504 Some((_, c)) => res.push(c),
505 None => break,
506 }
507 }
508
509 Rc::new(res)
510 }
511
512 pub fn integer_lit(s: &str, suffix: Option<Symbol>, sd: &Handler, sp: Span) -> ast::LitKind {
513 // s can only be ascii, byte indexing is fine
514
515 let s2 = s.chars().filter(|&c| c != '_').collect::<String>();
516 let mut s = &s2[..];
517
518 debug!("integer_lit: {}, {:?}", s, suffix);
519
520 let mut base = 10;
521 let orig = s;
522 let mut ty = ast::LitIntType::Unsuffixed;
523
524 if char_at(s, 0) == '0' && s.len() > 1 {
525 match char_at(s, 1) {
526 'x' => base = 16,
527 'o' => base = 8,
528 'b' => base = 2,
529 _ => { }
530 }
531 }
532
533 // 1f64 and 2f32 etc. are valid float literals.
534 if let Some(suf) = suffix {
535 if looks_like_width_suffix(&['f'], &suf.as_str()) {
536 match base {
537 16 => sd.span_err(sp, "hexadecimal float literal is not supported"),
538 8 => sd.span_err(sp, "octal float literal is not supported"),
539 2 => sd.span_err(sp, "binary float literal is not supported"),
540 _ => ()
541 }
542 return filtered_float_lit(Symbol::intern(&s), Some(suf), sd, sp)
543 }
544 }
545
546 if base != 10 {
547 s = &s[2..];
548 }
549
550 if let Some(suf) = suffix {
551 if suf.as_str().is_empty() { sd.span_bug(sp, "found empty literal suffix in Some")}
552 ty = match &*suf.as_str() {
553 "isize" => ast::LitIntType::Signed(ast::IntTy::Is),
554 "i8" => ast::LitIntType::Signed(ast::IntTy::I8),
555 "i16" => ast::LitIntType::Signed(ast::IntTy::I16),
556 "i32" => ast::LitIntType::Signed(ast::IntTy::I32),
557 "i64" => ast::LitIntType::Signed(ast::IntTy::I64),
558 "i128" => ast::LitIntType::Signed(ast::IntTy::I128),
559 "usize" => ast::LitIntType::Unsigned(ast::UintTy::Us),
560 "u8" => ast::LitIntType::Unsigned(ast::UintTy::U8),
561 "u16" => ast::LitIntType::Unsigned(ast::UintTy::U16),
562 "u32" => ast::LitIntType::Unsigned(ast::UintTy::U32),
563 "u64" => ast::LitIntType::Unsigned(ast::UintTy::U64),
564 "u128" => ast::LitIntType::Unsigned(ast::UintTy::U128),
565 suf => {
566 // i<digits> and u<digits> look like widths, so lets
567 // give an error message along those lines
568 if looks_like_width_suffix(&['i', 'u'], suf) {
569 sd.struct_span_err(sp, &format!("invalid width `{}` for integer literal",
570 &suf[1..]))
571 .help("valid widths are 8, 16, 32, 64 and 128")
572 .emit();
573 } else {
574 sd.struct_span_err(sp, &format!("invalid suffix `{}` for numeric literal", suf))
575 .help("the suffix must be one of the integral types \
576 (`u32`, `isize`, etc)")
577 .emit();
578 }
579
580 ty
581 }
582 }
583 }
584
585 debug!("integer_lit: the type is {:?}, base {:?}, the new string is {:?}, the original \
586 string was {:?}, the original suffix was {:?}", ty, base, s, orig, suffix);
587
588 match u128::from_str_radix(s, base) {
589 Ok(r) => ast::LitKind::Int(r, ty),
590 Err(_) => {
591 // small bases are lexed as if they were base 10, e.g, the string
592 // might be `0b10201`. This will cause the conversion above to fail,
593 // but these cases have errors in the lexer: we don't want to emit
594 // two errors, and we especially don't want to emit this error since
595 // it isn't necessarily true.
596 let already_errored = base < 10 &&
597 s.chars().any(|c| c.to_digit(10).map_or(false, |d| d >= base));
598
599 if !already_errored {
600 sd.span_err(sp, "int literal is too large");
601 }
602 ast::LitKind::Int(0, ty)
603 }
604 }
605 }
606
607 #[cfg(test)]
608 mod tests {
609 use super::*;
610 use std::rc::Rc;
611 use syntax_pos::{self, Span, BytePos, Pos, NO_EXPANSION};
612 use codemap::Spanned;
613 use ast::{self, Ident, PatKind};
614 use abi::Abi;
615 use attr::first_attr_value_str_by_name;
616 use parse;
617 use parse::parser::Parser;
618 use print::pprust::item_to_string;
619 use ptr::P;
620 use tokenstream::{self, TokenTree};
621 use util::parser_testing::{string_to_tts, string_to_parser};
622 use util::parser_testing::{string_to_expr, string_to_item, string_to_stmt};
623 use util::ThinVec;
624
625 // produce a syntax_pos::span
626 fn sp(a: u32, b: u32) -> Span {
627 Span {lo: BytePos(a), hi: BytePos(b), expn_id: NO_EXPANSION}
628 }
629
630 #[test] fn path_exprs_1() {
631 assert!(string_to_expr("a".to_string()) ==
632 P(ast::Expr{
633 id: ast::DUMMY_NODE_ID,
634 node: ast::ExprKind::Path(None, ast::Path {
635 span: sp(0, 1),
636 segments: vec![Ident::from_str("a").into()],
637 }),
638 span: sp(0, 1),
639 attrs: ThinVec::new(),
640 }))
641 }
642
643 #[test] fn path_exprs_2 () {
644 assert!(string_to_expr("::a::b".to_string()) ==
645 P(ast::Expr {
646 id: ast::DUMMY_NODE_ID,
647 node: ast::ExprKind::Path(None, ast::Path {
648 span: sp(0, 6),
649 segments: vec![ast::PathSegment::crate_root(),
650 Ident::from_str("a").into(),
651 Ident::from_str("b").into()]
652 }),
653 span: sp(0, 6),
654 attrs: ThinVec::new(),
655 }))
656 }
657
658 #[should_panic]
659 #[test] fn bad_path_expr_1() {
660 string_to_expr("::abc::def::return".to_string());
661 }
662
663 // check the token-tree-ization of macros
664 #[test]
665 fn string_to_tts_macro () {
666 let tts = string_to_tts("macro_rules! zip (($a)=>($a))".to_string());
667 let tts: &[tokenstream::TokenTree] = &tts[..];
668
669 match (tts.len(), tts.get(0), tts.get(1), tts.get(2), tts.get(3)) {
670 (
671 4,
672 Some(&TokenTree::Token(_, token::Ident(name_macro_rules))),
673 Some(&TokenTree::Token(_, token::Not)),
674 Some(&TokenTree::Token(_, token::Ident(name_zip))),
675 Some(&TokenTree::Delimited(_, ref macro_delimed)),
676 )
677 if name_macro_rules.name == "macro_rules"
678 && name_zip.name == "zip" => {
679 let tts = &macro_delimed.tts[..];
680 match (tts.len(), tts.get(0), tts.get(1), tts.get(2)) {
681 (
682 3,
683 Some(&TokenTree::Delimited(_, ref first_delimed)),
684 Some(&TokenTree::Token(_, token::FatArrow)),
685 Some(&TokenTree::Delimited(_, ref second_delimed)),
686 )
687 if macro_delimed.delim == token::Paren => {
688 let tts = &first_delimed.tts[..];
689 match (tts.len(), tts.get(0), tts.get(1)) {
690 (
691 2,
692 Some(&TokenTree::Token(_, token::Dollar)),
693 Some(&TokenTree::Token(_, token::Ident(ident))),
694 )
695 if first_delimed.delim == token::Paren && ident.name == "a" => {},
696 _ => panic!("value 3: {:?}", **first_delimed),
697 }
698 let tts = &second_delimed.tts[..];
699 match (tts.len(), tts.get(0), tts.get(1)) {
700 (
701 2,
702 Some(&TokenTree::Token(_, token::Dollar)),
703 Some(&TokenTree::Token(_, token::Ident(ident))),
704 )
705 if second_delimed.delim == token::Paren
706 && ident.name == "a" => {},
707 _ => panic!("value 4: {:?}", **second_delimed),
708 }
709 },
710 _ => panic!("value 2: {:?}", **macro_delimed),
711 }
712 },
713 _ => panic!("value: {:?}",tts),
714 }
715 }
716
717 #[test]
718 fn string_to_tts_1() {
719 let tts = string_to_tts("fn a (b : i32) { b; }".to_string());
720
721 let expected = vec![
722 TokenTree::Token(sp(0, 2), token::Ident(Ident::from_str("fn"))),
723 TokenTree::Token(sp(3, 4), token::Ident(Ident::from_str("a"))),
724 TokenTree::Delimited(
725 sp(5, 14),
726 Rc::new(tokenstream::Delimited {
727 delim: token::DelimToken::Paren,
728 tts: vec![
729 TokenTree::Token(sp(6, 7), token::Ident(Ident::from_str("b"))),
730 TokenTree::Token(sp(8, 9), token::Colon),
731 TokenTree::Token(sp(10, 13), token::Ident(Ident::from_str("i32"))),
732 ],
733 })),
734 TokenTree::Delimited(
735 sp(15, 21),
736 Rc::new(tokenstream::Delimited {
737 delim: token::DelimToken::Brace,
738 tts: vec![
739 TokenTree::Token(sp(17, 18), token::Ident(Ident::from_str("b"))),
740 TokenTree::Token(sp(18, 19), token::Semi),
741 ],
742 }))
743 ];
744
745 assert_eq!(tts, expected);
746 }
747
748 #[test] fn ret_expr() {
749 assert!(string_to_expr("return d".to_string()) ==
750 P(ast::Expr{
751 id: ast::DUMMY_NODE_ID,
752 node:ast::ExprKind::Ret(Some(P(ast::Expr{
753 id: ast::DUMMY_NODE_ID,
754 node:ast::ExprKind::Path(None, ast::Path{
755 span: sp(7, 8),
756 segments: vec![Ident::from_str("d").into()],
757 }),
758 span:sp(7,8),
759 attrs: ThinVec::new(),
760 }))),
761 span:sp(0,8),
762 attrs: ThinVec::new(),
763 }))
764 }
765
766 #[test] fn parse_stmt_1 () {
767 assert!(string_to_stmt("b;".to_string()) ==
768 Some(ast::Stmt {
769 node: ast::StmtKind::Expr(P(ast::Expr {
770 id: ast::DUMMY_NODE_ID,
771 node: ast::ExprKind::Path(None, ast::Path {
772 span:sp(0,1),
773 segments: vec![Ident::from_str("b").into()],
774 }),
775 span: sp(0,1),
776 attrs: ThinVec::new()})),
777 id: ast::DUMMY_NODE_ID,
778 span: sp(0,1)}))
779
780 }
781
782 fn parser_done(p: Parser){
783 assert_eq!(p.token.clone(), token::Eof);
784 }
785
786 #[test] fn parse_ident_pat () {
787 let sess = ParseSess::new();
788 let mut parser = string_to_parser(&sess, "b".to_string());
789 assert!(panictry!(parser.parse_pat())
790 == P(ast::Pat{
791 id: ast::DUMMY_NODE_ID,
792 node: PatKind::Ident(ast::BindingMode::ByValue(ast::Mutability::Immutable),
793 Spanned{ span:sp(0, 1),
794 node: Ident::from_str("b")
795 },
796 None),
797 span: sp(0,1)}));
798 parser_done(parser);
799 }
800
801 // check the contents of the tt manually:
802 #[test] fn parse_fundecl () {
803 // this test depends on the intern order of "fn" and "i32"
804 assert_eq!(string_to_item("fn a (b : i32) { b; }".to_string()),
805 Some(
806 P(ast::Item{ident:Ident::from_str("a"),
807 attrs:Vec::new(),
808 id: ast::DUMMY_NODE_ID,
809 node: ast::ItemKind::Fn(P(ast::FnDecl {
810 inputs: vec![ast::Arg{
811 ty: P(ast::Ty{id: ast::DUMMY_NODE_ID,
812 node: ast::TyKind::Path(None, ast::Path{
813 span:sp(10,13),
814 segments: vec![Ident::from_str("i32").into()],
815 }),
816 span:sp(10,13)
817 }),
818 pat: P(ast::Pat {
819 id: ast::DUMMY_NODE_ID,
820 node: PatKind::Ident(
821 ast::BindingMode::ByValue(ast::Mutability::Immutable),
822 Spanned{
823 span: sp(6,7),
824 node: Ident::from_str("b")},
825 None
826 ),
827 span: sp(6,7)
828 }),
829 id: ast::DUMMY_NODE_ID
830 }],
831 output: ast::FunctionRetTy::Default(sp(15, 15)),
832 variadic: false
833 }),
834 ast::Unsafety::Normal,
835 Spanned {
836 span: sp(0,2),
837 node: ast::Constness::NotConst,
838 },
839 Abi::Rust,
840 ast::Generics{ // no idea on either of these:
841 lifetimes: Vec::new(),
842 ty_params: Vec::new(),
843 where_clause: ast::WhereClause {
844 id: ast::DUMMY_NODE_ID,
845 predicates: Vec::new(),
846 },
847 span: syntax_pos::DUMMY_SP,
848 },
849 P(ast::Block {
850 stmts: vec![ast::Stmt {
851 node: ast::StmtKind::Semi(P(ast::Expr{
852 id: ast::DUMMY_NODE_ID,
853 node: ast::ExprKind::Path(None,
854 ast::Path{
855 span:sp(17,18),
856 segments: vec![Ident::from_str("b").into()],
857 }),
858 span: sp(17,18),
859 attrs: ThinVec::new()})),
860 id: ast::DUMMY_NODE_ID,
861 span: sp(17,19)}],
862 id: ast::DUMMY_NODE_ID,
863 rules: ast::BlockCheckMode::Default, // no idea
864 span: sp(15,21),
865 })),
866 vis: ast::Visibility::Inherited,
867 span: sp(0,21)})));
868 }
869
870 #[test] fn parse_use() {
871 let use_s = "use foo::bar::baz;";
872 let vitem = string_to_item(use_s.to_string()).unwrap();
873 let vitem_s = item_to_string(&vitem);
874 assert_eq!(&vitem_s[..], use_s);
875
876 let use_s = "use foo::bar as baz;";
877 let vitem = string_to_item(use_s.to_string()).unwrap();
878 let vitem_s = item_to_string(&vitem);
879 assert_eq!(&vitem_s[..], use_s);
880 }
881
882 #[test] fn parse_extern_crate() {
883 let ex_s = "extern crate foo;";
884 let vitem = string_to_item(ex_s.to_string()).unwrap();
885 let vitem_s = item_to_string(&vitem);
886 assert_eq!(&vitem_s[..], ex_s);
887
888 let ex_s = "extern crate foo as bar;";
889 let vitem = string_to_item(ex_s.to_string()).unwrap();
890 let vitem_s = item_to_string(&vitem);
891 assert_eq!(&vitem_s[..], ex_s);
892 }
893
894 fn get_spans_of_pat_idents(src: &str) -> Vec<Span> {
895 let item = string_to_item(src.to_string()).unwrap();
896
897 struct PatIdentVisitor {
898 spans: Vec<Span>
899 }
900 impl<'a> ::visit::Visitor<'a> for PatIdentVisitor {
901 fn visit_pat(&mut self, p: &'a ast::Pat) {
902 match p.node {
903 PatKind::Ident(_ , ref spannedident, _) => {
904 self.spans.push(spannedident.span.clone());
905 }
906 _ => {
907 ::visit::walk_pat(self, p);
908 }
909 }
910 }
911 }
912 let mut v = PatIdentVisitor { spans: Vec::new() };
913 ::visit::walk_item(&mut v, &item);
914 return v.spans;
915 }
916
917 #[test] fn span_of_self_arg_pat_idents_are_correct() {
918
919 let srcs = ["impl z { fn a (&self, &myarg: i32) {} }",
920 "impl z { fn a (&mut self, &myarg: i32) {} }",
921 "impl z { fn a (&'a self, &myarg: i32) {} }",
922 "impl z { fn a (self, &myarg: i32) {} }",
923 "impl z { fn a (self: Foo, &myarg: i32) {} }",
924 ];
925
926 for &src in &srcs {
927 let spans = get_spans_of_pat_idents(src);
928 let Span{ lo, hi, .. } = spans[0];
929 assert!("self" == &src[lo.to_usize()..hi.to_usize()],
930 "\"{}\" != \"self\". src=\"{}\"",
931 &src[lo.to_usize()..hi.to_usize()], src)
932 }
933 }
934
935 #[test] fn parse_exprs () {
936 // just make sure that they parse....
937 string_to_expr("3 + 4".to_string());
938 string_to_expr("a::z.froob(b,&(987+3))".to_string());
939 }
940
941 #[test] fn attrs_fix_bug () {
942 string_to_item("pub fn mk_file_writer(path: &Path, flags: &[FileFlag])
943 -> Result<Box<Writer>, String> {
944 #[cfg(windows)]
945 fn wb() -> c_int {
946 (O_WRONLY | libc::consts::os::extra::O_BINARY) as c_int
947 }
948
949 #[cfg(unix)]
950 fn wb() -> c_int { O_WRONLY as c_int }
951
952 let mut fflags: c_int = wb();
953 }".to_string());
954 }
955
956 #[test] fn crlf_doc_comments() {
957 let sess = ParseSess::new();
958
959 let name = "<source>".to_string();
960 let source = "/// doc comment\r\nfn foo() {}".to_string();
961 let item = parse_item_from_source_str(name.clone(), source, &sess)
962 .unwrap().unwrap();
963 let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap();
964 assert_eq!(doc, "/// doc comment");
965
966 let source = "/// doc comment\r\n/// line 2\r\nfn foo() {}".to_string();
967 let item = parse_item_from_source_str(name.clone(), source, &sess)
968 .unwrap().unwrap();
969 let docs = item.attrs.iter().filter(|a| a.name() == "doc")
970 .map(|a| a.value_str().unwrap().to_string()).collect::<Vec<_>>();
971 let b: &[_] = &["/// doc comment".to_string(), "/// line 2".to_string()];
972 assert_eq!(&docs[..], b);
973
974 let source = "/** doc comment\r\n * with CRLF */\r\nfn foo() {}".to_string();
975 let item = parse_item_from_source_str(name, source, &sess).unwrap().unwrap();
976 let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap();
977 assert_eq!(doc, "/** doc comment\n * with CRLF */");
978 }
979
980 #[test]
981 fn ttdelim_span() {
982 let sess = ParseSess::new();
983 let expr = parse::parse_expr_from_source_str("foo".to_string(),
984 "foo!( fn main() { body } )".to_string(), &sess).unwrap();
985
986 let tts = match expr.node {
987 ast::ExprKind::Mac(ref mac) => mac.node.tts.clone(),
988 _ => panic!("not a macro"),
989 };
990
991 let span = tts.iter().rev().next().unwrap().get_span();
992
993 match sess.codemap().span_to_snippet(span) {
994 Ok(s) => assert_eq!(&s[..], "{ body }"),
995 Err(_) => panic!("could not get snippet"),
996 }
997 }
998 }