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
13 use ast
::{self, CrateConfig}
;
15 use syntax_pos
::{self, Span, FileMap}
;
16 use errors
::{Handler, ColorConfig, DiagnosticBuilder}
;
17 use feature_gate
::UnstableFeatures
;
18 use parse
::parser
::Parser
;
24 use std
::cell
::RefCell
;
25 use std
::collections
::HashSet
;
27 use std
::path
::{Path, PathBuf}
;
33 pub type PResult
<'a
, T
> = Result
<T
, DiagnosticBuilder
<'a
>>;
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
>,
57 pub fn new() -> Self {
58 let cm
= Rc
::new(CodeMap
::new());
59 let handler
= Handler
::with_tty_emitter(ColorConfig
::Auto
,
63 ParseSess
::with_span_handler(handler
, cm
)
66 pub fn with_span_handler(handler
: Handler
, code_map
: Rc
<CodeMap
>) -> ParseSess
{
68 span_diagnostic
: handler
,
69 unstable_features
: UnstableFeatures
::from_environment(),
70 config
: HashSet
::new(),
71 included_mod_stack
: RefCell
::new(vec
![]),
76 pub fn codemap(&self) -> &CodeMap
{
82 pub struct Directory
{
84 pub ownership
: DirectoryOwnership
,
87 #[derive(Copy, Clone)]
88 pub enum DirectoryOwnership
{
91 UnownedViaMod(bool
/* legacy warnings? */),
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
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()
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()
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()
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()
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()
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()
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()
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()
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
);
149 // right now this is re-creating the token trees from ... token trees.
150 p
.parse_all_token_trees()
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
)
156 filemap_to_parser(sess
, sess
.codemap().new_filemap(name
, None
, source
))
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
))
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
,
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
;
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
));
184 if parser
.token
== token
::Eof
&& parser
.span
== syntax_pos
::DUMMY_SP
{
185 parser
.span
= syntax_pos
::mk_sp(end_pos
, end_pos
);
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
>)
195 tts_to_parser(sess
, tts
)
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())
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
>)
209 match sess
.codemap().load_file(path
) {
210 Ok(filemap
) => filemap
,
212 let msg
= format
!("couldn't read {:?}: {}", path
.display(), e
);
214 Some(sp
) => panic
!(sess
.span_diagnostic
.span_fatal(sp
, &msg
)),
215 None
=> panic
!(sess
.span_diagnostic
.fatal(&msg
))
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
);
225 panictry
!(srdr
.parse_all_token_trees())
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();
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) {
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();
250 // Handle escaped chars.
251 match lit
.as_bytes()[1] as char {
260 let v
= u32::from_str_radix(&lit
[2..4], 16).unwrap();
261 let c
= char::from_u32(v
).unwrap();
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)
271 _
=> panic
!("lexer should have rejected a bad character escape {}", lit
)
275 /// Parse a string representing a string literal into its final form. Does
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());
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
);
284 /// Eat everything up to a non-whitespace
285 fn eat
<'a
>(it
: &mut iter
::Peekable
<str::CharIndices
<'a
>>) {
287 match it
.peek().map(|x
| x
.1) {
288 Some(' '
) | Some('
\n'
) | Some('
\r'
) | Some('
\t'
) => {
296 let mut chars
= lit
.char_indices().peekable();
302 let ch
= chars
.peek().unwrap_or_else(|| {
303 panic
!("{}", error(i
))
308 } else if ch
== '
\r'
{
310 let ch
= chars
.peek().unwrap_or_else(|| {
311 panic
!("{}", error(i
))
315 panic
!("lexer accepted bare CR");
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 \
328 let ch
= chars
.peek().unwrap_or_else(|| {
329 panic
!("{}", error(i
))
333 panic
!("lexer accepted bare CR");
345 res
.shrink_to_fit(); // probably not going to do anything, unless there was an escape.
346 debug
!("parse_str_lit: returning {}", res
);
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());
356 // FIXME #8372: This could be a for-loop if it didn't borrow the iterator
357 let mut chars
= lit
.chars().peekable();
362 if *chars
.peek().unwrap() != '
\n'
{
363 panic
!("lexer accepted bare CR");
379 // check if `s` looks like i32 or u1234 etc.
380 fn looks_like_width_suffix(first_chars
: &[char], s
: &str) -> bool
{
382 first_chars
.contains(&char_at(s
, 0)) &&
383 s
[1..].chars().all(|c
| '
0'
<= c
&& c
<= '
9'
)
386 fn filtered_float_lit(data
: Symbol
, suffix
: Option
<Symbol
>, sd
: &Handler
, sp
: Span
)
388 debug
!("filtered_float_lit: {}, {:?}", data
, suffix
);
389 let suffix
= match suffix
{
390 Some(suffix
) => suffix
,
391 None
=> return ast
::LitKind
::FloatUnsuffixed(data
),
394 match &*suffix
.as_str() {
395 "f32" => ast
::LitKind
::Float(data
, ast
::FloatTy
::F32
),
396 "f64" => ast
::LitKind
::Float(data
, ast
::FloatTy
::F64
),
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")
404 sd
.struct_span_err(sp
, &format
!("invalid suffix `{}` for float literal", suf
))
405 .help("valid suffixes are `f32` and `f64`")
409 ast
::LitKind
::FloatUnsuffixed(data
)
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
)
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
);
425 (lit
.as_bytes()[0], 1)
427 assert
!(lit
.as_bytes()[0] == b'
\\'
, err(0));
428 let b
= match lit
.as_bytes()[1] {
437 match u64::from_str_radix(&lit
[2..4], 16).ok() {
444 None
=> panic
!(err(3))
452 pub fn byte_str_lit(lit
: &str) -> Rc
<Vec
<u8>> {
453 let mut res
= Vec
::with_capacity(lit
.len());
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
);
458 /// Eat everything up to a non-whitespace
459 fn eat
<'a
, I
: Iterator
<Item
=(usize, u8)>>(it
: &mut iter
::Peekable
<I
>) {
461 match it
.peek().map(|x
| x
.1) {
462 Some(b' '
) | Some(b'
\n'
) | Some(b'
\r'
) | Some(b'
\t'
) => {
470 // byte string literals *must* be ASCII, but the escapes don't have to be
471 let mut chars
= lit
.bytes().enumerate().peekable();
474 Some((i
, b'
\\'
)) => {
476 match chars
.peek().expect(&em
).1 {
477 b'
\n'
=> eat(&mut chars
),
480 if chars
.peek().expect(&em
).1 != b'
\n'
{
481 panic
!("lexer accepted bare CR");
486 // otherwise, a normal escape
487 let (c
, n
) = byte_lit(&lit
[i
..]);
488 // we don't need to move past the first \
496 Some((i
, b'
\r'
)) => {
498 if chars
.peek().expect(&em
).1 != b'
\n'
{
499 panic
!("lexer accepted bare CR");
504 Some((_
, c
)) => res
.push(c
),
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
515 let s2
= s
.chars().filter(|&c
| c
!= '_'
).collect
::<String
>();
518 debug
!("integer_lit: {}, {:?}", s
, suffix
);
522 let mut ty
= ast
::LitIntType
::Unsuffixed
;
524 if char_at(s
, 0) == '
0'
&& s
.len() > 1 {
525 match char_at(s
, 1) {
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()) {
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"),
542 return filtered_float_lit(Symbol
::intern(&s
), Some(suf
), sd
, sp
)
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
),
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",
571 .help("valid widths are 8, 16, 32, 64 and 128")
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)")
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
);
588 match u128
::from_str_radix(s
, base
) {
589 Ok(r
) => ast
::LitKind
::Int(r
, ty
),
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
));
599 if !already_errored
{
600 sd
.span_err(sp
, "int literal is too large");
602 ast
::LitKind
::Int(0, ty
)
611 use syntax_pos
::{self, Span, BytePos, Pos, NO_EXPANSION}
;
612 use codemap
::Spanned
;
613 use ast
::{self, Ident, PatKind}
;
615 use attr
::first_attr_value_str_by_name
;
617 use parse
::parser
::Parser
;
618 use print
::pprust
::item_to_string
;
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}
;
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}
630 #[test] fn path_exprs_1() {
631 assert
!(string_to_expr("a".to_string()) ==
633 id
: ast
::DUMMY_NODE_ID
,
634 node
: ast
::ExprKind
::Path(None
, ast
::Path
{
636 segments
: vec
![Ident
::from_str("a").into()],
639 attrs
: ThinVec
::new(),
643 #[test] fn path_exprs_2 () {
644 assert
!(string_to_expr("::a::b".to_string()) ==
646 id
: ast
::DUMMY_NODE_ID
,
647 node
: ast
::ExprKind
::Path(None
, ast
::Path
{
649 segments
: vec
![ast
::PathSegment
::crate_root(),
650 Ident
::from_str("a").into(),
651 Ident
::from_str("b").into()]
654 attrs
: ThinVec
::new(),
659 #[test] fn bad_path_expr_1() {
660 string_to_expr("::abc::def::return".to_string());
663 // check the token-tree-ization of macros
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
[..];
669 match (tts
.len(), tts
.get(0), tts
.get(1), tts
.get(2), tts
.get(3)) {
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
)),
677 if name_macro_rules
.name
== "macro_rules"
678 && name_zip
.name
== "zip" => {
679 let tts
= ¯o_delimed
.tts
[..];
680 match (tts
.len(), tts
.get(0), tts
.get(1), tts
.get(2)) {
683 Some(&TokenTree
::Delimited(_
, ref first_delimed
)),
684 Some(&TokenTree
::Token(_
, token
::FatArrow
)),
685 Some(&TokenTree
::Delimited(_
, ref second_delimed
)),
687 if macro_delimed
.delim
== token
::Paren
=> {
688 let tts
= &first_delimed
.tts
[..];
689 match (tts
.len(), tts
.get(0), tts
.get(1)) {
692 Some(&TokenTree
::Token(_
, token
::Dollar
)),
693 Some(&TokenTree
::Token(_
, token
::Ident(ident
))),
695 if first_delimed
.delim
== token
::Paren
&& ident
.name
== "a" => {}
,
696 _
=> panic
!("value 3: {:?}", **first_delimed
),
698 let tts
= &second_delimed
.tts
[..];
699 match (tts
.len(), tts
.get(0), tts
.get(1)) {
702 Some(&TokenTree
::Token(_
, token
::Dollar
)),
703 Some(&TokenTree
::Token(_
, token
::Ident(ident
))),
705 if second_delimed
.delim
== token
::Paren
706 && ident
.name
== "a" => {}
,
707 _
=> panic
!("value 4: {:?}", **second_delimed
),
710 _
=> panic
!("value 2: {:?}", **macro_delimed
),
713 _
=> panic
!("value: {:?}",tts
),
718 fn string_to_tts_1() {
719 let tts
= string_to_tts("fn a (b : i32) { b; }".to_string());
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(
726 Rc
::new(tokenstream
::Delimited
{
727 delim
: token
::DelimToken
::Paren
,
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"))),
734 TokenTree
::Delimited(
736 Rc
::new(tokenstream
::Delimited
{
737 delim
: token
::DelimToken
::Brace
,
739 TokenTree
::Token(sp(17, 18), token
::Ident(Ident
::from_str("b"))),
740 TokenTree
::Token(sp(18, 19), token
::Semi
),
745 assert_eq
!(tts
, expected
);
748 #[test] fn ret_expr() {
749 assert
!(string_to_expr("return d".to_string()) ==
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
{
756 segments
: vec
![Ident
::from_str("d").into()],
759 attrs
: ThinVec
::new(),
762 attrs
: ThinVec
::new(),
766 #[test] fn parse_stmt_1 () {
767 assert
!(string_to_stmt("b;".to_string()) ==
769 node
: ast
::StmtKind
::Expr(P(ast
::Expr
{
770 id
: ast
::DUMMY_NODE_ID
,
771 node
: ast
::ExprKind
::Path(None
, ast
::Path
{
773 segments
: vec
![Ident
::from_str("b").into()],
776 attrs
: ThinVec
::new()})),
777 id
: ast
::DUMMY_NODE_ID
,
782 fn parser_done(p
: Parser
){
783 assert_eq
!(p
.token
.clone(), token
::Eof
);
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())
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")
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()),
806 P(ast
::Item
{ident
:Ident
::from_str("a"),
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
{
814 segments
: vec
![Ident
::from_str("i32").into()],
819 id
: ast
::DUMMY_NODE_ID
,
820 node
: PatKind
::Ident(
821 ast
::BindingMode
::ByValue(ast
::Mutability
::Immutable
),
824 node
: Ident
::from_str("b")},
829 id
: ast
::DUMMY_NODE_ID
831 output
: ast
::FunctionRetTy
::Default(sp(15, 15)),
834 ast
::Unsafety
::Normal
,
837 node
: ast
::Constness
::NotConst
,
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(),
847 span
: syntax_pos
::DUMMY_SP
,
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
,
856 segments
: vec
![Ident
::from_str("b").into()],
859 attrs
: ThinVec
::new()})),
860 id
: ast
::DUMMY_NODE_ID
,
862 id
: ast
::DUMMY_NODE_ID
,
863 rules
: ast
::BlockCheckMode
::Default
, // no idea
866 vis
: ast
::Visibility
::Inherited
,
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
);
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
);
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
);
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
);
894 fn get_spans_of_pat_idents(src
: &str) -> Vec
<Span
> {
895 let item
= string_to_item(src
.to_string()).unwrap();
897 struct PatIdentVisitor
{
900 impl<'a
> ::visit
::Visitor
<'a
> for PatIdentVisitor
{
901 fn visit_pat(&mut self, p
: &'a ast
::Pat
) {
903 PatKind
::Ident(_
, ref spannedident
, _
) => {
904 self.spans
.push(spannedident
.span
.clone());
907 ::visit
::walk_pat(self, p
);
912 let mut v
= PatIdentVisitor { spans: Vec::new() }
;
913 ::visit
::walk_item(&mut v
, &item
);
917 #[test] fn span_of_self_arg_pat_idents_are_correct() {
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) {} }",
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
)
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());
941 #[test] fn attrs_fix_bug () {
942 string_to_item("pub fn mk_file_writer(path: &Path, flags: &[FileFlag])
943 -> Result<Box<Writer>, String> {
946 (O_WRONLY | libc::consts::os::extra::O_BINARY) as c_int
950 fn wb() -> c_int { O_WRONLY as c_int }
952 let mut fflags: c_int = wb();
956 #[test] fn crlf_doc_comments() {
957 let sess
= ParseSess
::new();
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
)
963 let doc
= first_attr_value_str_by_name(&item
.attrs
, "doc").unwrap();
964 assert_eq
!(doc
, "/// doc comment");
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
)
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
);
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 */");
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();
986 let tts
= match expr
.node
{
987 ast
::ExprKind
::Mac(ref mac
) => mac
.node
.tts
.clone(),
988 _
=> panic
!("not a macro"),
991 let span
= tts
.iter().rev().next().unwrap().get_span();
993 match sess
.codemap().span_to_snippet(span
) {
994 Ok(s
) => assert_eq
!(&s
[..], "{ body }"),
995 Err(_
) => panic
!("could not get snippet"),