blob: 08afc7f1ad0a7dcddc719fb677cdea8133a71f2f [file] [log] [blame]
Alex Crichton76a5cc82017-05-23 07:01:44 -07001use std::ascii;
Alex Crichton44bffbc2017-05-19 17:51:59 -07002use std::borrow::Borrow;
3use std::cell::RefCell;
4use std::collections::HashMap;
5use std::fmt;
6use std::iter;
7use std::ops;
8use std::rc::Rc;
9use std::str::FromStr;
10use std::vec;
11
12use proc_macro;
David Tolnayb1032662017-05-31 15:52:28 -070013use unicode_xid::UnicodeXID;
14use strnom::{IResult, skip_whitespace, block_comment, whitespace};
Alex Crichton44bffbc2017-05-19 17:51:59 -070015
16use {TokenTree, TokenKind, Delimiter, OpKind};
17
David Tolnay977f8282017-05-31 17:41:33 -070018#[derive(Clone, Debug)]
Alex Crichton44bffbc2017-05-19 17:51:59 -070019pub struct TokenStream {
20 inner: Vec<TokenTree>,
21}
22
23#[derive(Debug)]
24pub struct LexError;
25
26impl TokenStream {
27 pub fn empty() -> TokenStream {
28 TokenStream { inner: Vec::new() }
29 }
30
31 pub fn is_empty(&self) -> bool {
32 self.inner.len() == 0
33 }
34}
35
36impl FromStr for TokenStream {
37 type Err = LexError;
38
39 fn from_str(src: &str) -> Result<TokenStream, LexError> {
40 match token_stream(src) {
41 IResult::Done(input, output) => {
42 if skip_whitespace(input).len() != 0 {
43 Err(LexError)
44 } else {
45 Ok(output)
46 }
47 }
48 IResult::Error => Err(LexError),
49 }
50 }
51}
52
53impl fmt::Display for TokenStream {
54 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
55 let mut joint = false;
56 for (i, tt) in self.inner.iter().enumerate() {
57 if i != 0 && !joint {
58 write!(f, " ")?;
59 }
60 joint = false;
61 match tt.kind {
62 TokenKind::Sequence(delim, ref stream) => {
63 let (start, end) = match delim {
64 Delimiter::Parenthesis => ("(", ")"),
65 Delimiter::Brace => ("{", "}"),
66 Delimiter::Bracket => ("[", "]"),
67 Delimiter::None => ("", ""),
68 };
Alex Crichton852d53d2017-05-19 19:25:08 -070069 if stream.0.inner.len() == 0 {
70 write!(f, "{} {}", start, end)?
71 } else {
72 write!(f, "{} {} {}", start, stream, end)?
73 }
Alex Crichton44bffbc2017-05-19 17:51:59 -070074 }
Alex Crichton9c2fb0a2017-05-26 08:49:31 -070075 TokenKind::Word(ref sym) => write!(f, "{}", sym.as_str())?,
Alex Crichton44bffbc2017-05-19 17:51:59 -070076 TokenKind::Op(ch, ref op) => {
77 write!(f, "{}", ch)?;
78 match *op {
79 OpKind::Alone => {}
80 OpKind::Joint => joint = true,
81 }
82 }
83 TokenKind::Literal(ref literal) => {
84 write!(f, "{}", literal)?;
85 // handle comments
86 if (literal.0).0.starts_with("/") {
87 write!(f, "\n")?;
88 }
89 }
90 }
91 }
92
93 Ok(())
94 }
95}
96
97impl From<proc_macro::TokenStream> for TokenStream {
98 fn from(inner: proc_macro::TokenStream) -> TokenStream {
99 inner.to_string().parse().expect("compiler token stream parse failed")
100 }
101}
102
103impl From<TokenStream> for proc_macro::TokenStream {
104 fn from(inner: TokenStream) -> proc_macro::TokenStream {
105 inner.to_string().parse().expect("failed to parse to compiler tokens")
106 }
107}
108
109
110impl From<TokenTree> for TokenStream {
111 fn from(tree: TokenTree) -> TokenStream {
112 TokenStream { inner: vec![tree] }
113 }
114}
115
116impl iter::FromIterator<TokenStream> for TokenStream {
117 fn from_iter<I: IntoIterator<Item=TokenStream>>(streams: I) -> Self {
118 let mut v = Vec::new();
119
120 for stream in streams.into_iter() {
121 v.extend(stream.inner);
122 }
123
124 TokenStream { inner: v }
125 }
126}
127
128pub type TokenIter = vec::IntoIter<TokenTree>;
129
130impl IntoIterator for TokenStream {
131 type Item = TokenTree;
132 type IntoIter = TokenIter;
133
134 fn into_iter(self) -> TokenIter {
135 self.inner.into_iter()
136 }
137}
138
David Tolnay977f8282017-05-31 17:41:33 -0700139#[derive(Clone, Copy, Default, Debug)]
Alex Crichton44bffbc2017-05-19 17:51:59 -0700140pub struct Span;
141
142impl Span {
143 pub fn call_site() -> Span {
144 Span
145 }
146}
147
David Tolnay977f8282017-05-31 17:41:33 -0700148#[derive(Copy, Clone, Debug)]
Alex Crichton44bffbc2017-05-19 17:51:59 -0700149pub struct Symbol(usize);
150
151thread_local!(static SYMBOLS: RefCell<Interner> = RefCell::new(Interner::new()));
152
153impl<'a> From<&'a str> for Symbol {
154 fn from(string: &'a str) -> Symbol {
155 Symbol(SYMBOLS.with(|s| s.borrow_mut().intern(string)))
156 }
157}
158
159impl ops::Deref for Symbol {
160 type Target = str;
161
162 fn deref(&self) -> &str {
163 SYMBOLS.with(|interner| {
164 let interner = interner.borrow();
165 let s = interner.get(self.0);
166 unsafe {
167 &*(s as *const str)
168 }
169 })
170 }
171}
172
173struct Interner {
174 string_to_index: HashMap<MyRc, usize>,
175 index_to_string: Vec<Rc<String>>,
176}
177
178#[derive(Hash, Eq, PartialEq)]
179struct MyRc(Rc<String>);
180
181impl Borrow<str> for MyRc {
182 fn borrow(&self) -> &str {
183 &self.0
184 }
185}
186
187impl Interner {
188 fn new() -> Interner {
189 Interner {
190 string_to_index: HashMap::new(),
191 index_to_string: Vec::new(),
192 }
193 }
194
195 fn intern(&mut self, s: &str) -> usize {
196 if let Some(&idx) = self.string_to_index.get(s) {
197 return idx
198 }
199 let s = Rc::new(s.to_string());
200 self.index_to_string.push(s.clone());
201 self.string_to_index.insert(MyRc(s), self.index_to_string.len() - 1);
202 self.index_to_string.len() - 1
203 }
204
205 fn get(&self, idx: usize) -> &str {
206 &self.index_to_string[idx]
207 }
208}
209
David Tolnay977f8282017-05-31 17:41:33 -0700210#[derive(Clone, Debug)]
Alex Crichton44bffbc2017-05-19 17:51:59 -0700211pub struct Literal(String);
212
Alex Crichton852d53d2017-05-19 19:25:08 -0700213impl Literal {
Alex Crichton9c2fb0a2017-05-26 08:49:31 -0700214 pub fn byte_char(byte: u8) -> Literal {
Alex Crichton76a5cc82017-05-23 07:01:44 -0700215 match byte {
216 0 => Literal(format!("b'\\0'")),
217 b'\"' => Literal(format!("b'\"'")),
218 n => {
219 let mut escaped = "b'".to_string();
220 escaped.extend(ascii::escape_default(n).map(|c| c as char));
221 escaped.push('\'');
222 Literal(escaped)
223 }
224 }
225 }
226
Alex Crichton9c2fb0a2017-05-26 08:49:31 -0700227 pub fn byte_string(bytes: &[u8]) -> Literal {
Alex Crichton852d53d2017-05-19 19:25:08 -0700228 let mut escaped = "b\"".to_string();
229 for b in bytes {
230 match *b {
231 b'\0' => escaped.push_str(r"\0"),
232 b'\t' => escaped.push_str(r"\t"),
233 b'\n' => escaped.push_str(r"\n"),
234 b'\r' => escaped.push_str(r"\r"),
235 b'"' => escaped.push_str("\\\""),
236 b'\\' => escaped.push_str("\\\\"),
237 b'\x20' ... b'\x7E' => escaped.push(*b as char),
238 _ => escaped.push_str(&format!("\\x{:02X}", b)),
239 }
240 }
241 escaped.push('"');
242 Literal(escaped)
243 }
Alex Crichton76a5cc82017-05-23 07:01:44 -0700244
245 pub fn doccomment(s: &str) -> Literal {
246 Literal(s.to_string())
247 }
Alex Crichton9c2fb0a2017-05-26 08:49:31 -0700248
249 pub fn float(s: &str) -> Literal {
250 Literal(s.to_string())
251 }
252
253 pub fn integer(s: &str) -> Literal {
254 Literal(s.to_string())
255 }
Alex Crichton31316622017-05-26 12:54:47 -0700256
257 pub fn raw_string(s: &str, pounds: usize) -> Literal {
258 let mut ret = format!("r");
259 ret.extend((0..pounds).map(|_| "#"));
260 ret.push('"');
261 ret.push_str(s);
262 ret.push('"');
263 ret.extend((0..pounds).map(|_| "#"));
264 Literal(ret)
265 }
266
267 pub fn raw_byte_string(s: &str, pounds: usize) -> Literal {
Alex Crichton7ed6d282017-05-26 13:42:50 -0700268 let mut ret = format!("br");
Alex Crichton31316622017-05-26 12:54:47 -0700269 ret.extend((0..pounds).map(|_| "#"));
270 ret.push('"');
271 ret.push_str(s);
272 ret.push('"');
273 ret.extend((0..pounds).map(|_| "#"));
274 Literal(ret)
275 }
Alex Crichton852d53d2017-05-19 19:25:08 -0700276}
277
Alex Crichton44bffbc2017-05-19 17:51:59 -0700278impl fmt::Display for Literal {
279 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
280 self.0.fmt(f)
281 }
282}
283
Alex Crichton9c2fb0a2017-05-26 08:49:31 -0700284macro_rules! ints {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700285 ($($t:ty,)*) => {$(
286 impl From<$t> for Literal {
287 fn from(t: $t) -> Literal {
Alex Crichton852d53d2017-05-19 19:25:08 -0700288 Literal(format!(concat!("{}", stringify!($t)), t))
Alex Crichton44bffbc2017-05-19 17:51:59 -0700289 }
290 }
291 )*}
292}
293
Alex Crichton9c2fb0a2017-05-26 08:49:31 -0700294ints! {
Alex Crichton852d53d2017-05-19 19:25:08 -0700295 u8, u16, u32, u64, usize,
296 i8, i16, i32, i64, isize,
Alex Crichton9c2fb0a2017-05-26 08:49:31 -0700297}
298
299macro_rules! floats {
300 ($($t:ty,)*) => {$(
301 impl From<$t> for Literal {
302 fn from(t: $t) -> Literal {
303 assert!(!t.is_nan());
304 assert!(!t.is_infinite());
305 Literal(format!(concat!("{}", stringify!($t)), t))
306 }
307 }
308 )*}
309}
310
311floats! {
Alex Crichton852d53d2017-05-19 19:25:08 -0700312 f32, f64,
313}
314
Alex Crichton44bffbc2017-05-19 17:51:59 -0700315impl<'a> From<&'a str> for Literal {
316 fn from(t: &'a str) -> Literal {
317 let mut s = t.chars().flat_map(|c| c.escape_default()).collect::<String>();
318 s.push('"');
319 s.insert(0, '"');
320 Literal(s)
321 }
322}
323
324impl From<char> for Literal {
325 fn from(t: char) -> Literal {
Alex Crichton2d0cf0b2017-05-26 14:00:16 -0700326 Literal(format!("'{}'", t.escape_default().collect::<String>()))
Alex Crichton44bffbc2017-05-19 17:51:59 -0700327 }
328}
329
330named!(token_stream -> TokenStream,
331 map!(token_trees, |s: Vec<TokenTree>| TokenStream { inner: s }));
332
333named!(token_trees -> Vec<TokenTree>, many0!(token_tree));
334
335named!(token_tree -> TokenTree,
336 map!(token_kind, |s: TokenKind| {
337 TokenTree {
338 span: ::Span(Span),
339 kind: s,
340 }
341 }));
342
343named!(token_kind -> TokenKind, alt!(
344 map!(delimited, |(d, s): (Delimiter, TokenStream)| {
345 TokenKind::Sequence(d, ::TokenStream(s))
346 })
347 |
Michael Layzellbad58012017-05-24 20:42:52 -0400348 map!(literal, |l| TokenKind::Literal(::Literal(l))) // must be before symbol
Alex Crichton44bffbc2017-05-19 17:51:59 -0700349 |
Michael Layzellbad58012017-05-24 20:42:52 -0400350 map!(symbol, |w| TokenKind::Word(::Symbol(w)))
Alex Crichton44bffbc2017-05-19 17:51:59 -0700351 |
352 map!(op, |(op, kind): (char, OpKind)| {
353 TokenKind::Op(op, kind)
354 })
355));
356
357named!(delimited -> (Delimiter, TokenStream), alt!(
358 delimited!(
359 punct!("("),
360 token_stream,
361 punct!(")")
362 ) => { |ts| (Delimiter::Parenthesis, ts) }
363 |
364 delimited!(
365 punct!("["),
366 token_stream,
367 punct!("]")
368 ) => { |ts| (Delimiter::Bracket, ts) }
369 |
370 delimited!(
371 punct!("{"),
372 token_stream,
373 punct!("}")
374 ) => { |ts| (Delimiter::Brace, ts) }
375));
376
377named!(symbol -> Symbol, alt!(
378 lifetime
379 |
380 map!(word, Symbol::from)
381));
382
383named!(lifetime -> Symbol, preceded!(
384 punct!("'"),
385 alt!(
386 // TODO: can we get rid of this allocation?
387 map!(word, |id| Symbol::from(&format!("'{}", id)[..]))
388 |
389 map!(keyword!("static"), |_| Symbol::from("'static"))
390 )
391));
392
393fn word(mut input: &str) -> IResult<&str, &str> {
394 input = skip_whitespace(input);
395
396 let mut chars = input.char_indices();
397 match chars.next() {
398 Some((_, ch)) if UnicodeXID::is_xid_start(ch) || ch == '_' => {}
399 _ => return IResult::Error,
400 }
401
402 for (i, ch) in chars {
403 if !UnicodeXID::is_xid_continue(ch) {
404 return IResult::Done(&input[i..], &input[..i])
405 }
406 }
407
408 IResult::Done("", input)
409}
410
411fn literal(input: &str) -> IResult<&str, Literal> {
412 let input_no_ws = skip_whitespace(input);
413
414 match literal_nocapture(input_no_ws) {
415 IResult::Done(a, ()) => {
416 let start = input.len() - input_no_ws.len();
417 let len = input_no_ws.len() - a.len();
418 let end = start + len;
Alex Crichton44bffbc2017-05-19 17:51:59 -0700419 IResult::Done(a, Literal(input[start..end].to_string()))
420 }
421 IResult::Error => IResult::Error,
422 }
423}
424
425named!(literal_nocapture -> (), alt!(
426 string
427 |
428 byte_string
429 |
430 byte
431 |
432 character
433 |
434 float
435 |
436 int
437 |
438 boolean
439 |
440 doc_comment
441));
442
443named!(string -> (), alt!(
444 quoted_string
445 |
446 preceded!(
447 punct!("r"),
448 raw_string
449 ) => { |_| () }
450));
451
452named!(quoted_string -> (), delimited!(
453 punct!("\""),
454 cooked_string,
455 tag!("\"")
456));
457
458fn cooked_string(input: &str) -> IResult<&str, ()> {
459 let mut chars = input.char_indices().peekable();
460 while let Some((byte_offset, ch)) = chars.next() {
461 match ch {
462 '"' => {
463 return IResult::Done(&input[byte_offset..], ());
464 }
465 '\r' => {
466 if let Some((_, '\n')) = chars.next() {
467 // ...
468 } else {
469 break;
470 }
471 }
472 '\\' => {
473 match chars.next() {
474 Some((_, 'x')) => {
475 if !backslash_x_char(&mut chars) {
476 break
477 }
478 }
479 Some((_, 'n')) |
480 Some((_, 'r')) |
481 Some((_, 't')) |
482 Some((_, '\\')) |
483 Some((_, '\'')) |
484 Some((_, '"')) |
485 Some((_, '0')) => {}
486 Some((_, 'u')) => {
487 if !backslash_u(&mut chars) {
488 break
489 }
490 }
491 Some((_, '\n')) | Some((_, '\r')) => {
492 while let Some(&(_, ch)) = chars.peek() {
493 if ch.is_whitespace() {
494 chars.next();
495 } else {
496 break;
497 }
498 }
499 }
500 _ => break,
501 }
502 }
503 _ch => {}
504 }
505 }
506 IResult::Error
507}
508
509named!(byte_string -> (), alt!(
510 delimited!(
511 punct!("b\""),
512 cooked_byte_string,
513 tag!("\"")
514 ) => { |_| () }
515 |
516 preceded!(
517 punct!("br"),
518 raw_string
519 ) => { |_| () }
520));
521
522fn cooked_byte_string(mut input: &str) -> IResult<&str, ()> {
523 let mut bytes = input.bytes().enumerate();
524 'outer: while let Some((offset, b)) = bytes.next() {
525 match b {
526 b'"' => {
527 return IResult::Done(&input[offset..], ());
528 }
529 b'\r' => {
530 if let Some((_, b'\n')) = bytes.next() {
531 // ...
532 } else {
533 break;
534 }
535 }
536 b'\\' => {
537 match bytes.next() {
538 Some((_, b'x')) => {
539 if !backslash_x_byte(&mut bytes) {
540 break
541 }
542 }
543 Some((_, b'n')) |
544 Some((_, b'r')) |
545 Some((_, b't')) |
546 Some((_, b'\\')) |
547 Some((_, b'0')) |
548 Some((_, b'\'')) |
549 Some((_, b'"')) => {}
550 Some((newline, b'\n')) |
551 Some((newline, b'\r')) => {
552 let rest = &input[newline + 1..];
553 for (offset, ch) in rest.char_indices() {
554 if !ch.is_whitespace() {
555 input = &rest[offset..];
556 bytes = input.bytes().enumerate();
557 continue 'outer;
558 }
559 }
560 break;
561 }
562 _ => break,
563 }
564 }
565 b if b < 0x80 => {}
566 _ => break,
567 }
568 }
569 IResult::Error
570}
571
572fn raw_string(input: &str) -> IResult<&str, ()> {
573 let mut chars = input.char_indices();
574 let mut n = 0;
575 while let Some((byte_offset, ch)) = chars.next() {
576 match ch {
577 '"' => {
578 n = byte_offset;
579 break;
580 }
581 '#' => {}
582 _ => return IResult::Error,
583 }
584 }
585 for (byte_offset, ch) in chars {
586 match ch {
587 '"' if input[byte_offset + 1..].starts_with(&input[..n]) => {
588 let rest = &input[byte_offset + 1 + n..];
589 return IResult::Done(rest, ())
590 }
591 '\r' => {}
592 _ => {}
593 }
594 }
595 IResult::Error
596}
597
598named!(byte -> (), do_parse!(
599 punct!("b") >>
600 tag!("'") >>
601 cooked_byte >>
602 tag!("'") >>
603 (())
604));
605
606fn cooked_byte(input: &str) -> IResult<&str, ()> {
607 let mut bytes = input.bytes().enumerate();
608 let ok = match bytes.next().map(|(_, b)| b) {
609 Some(b'\\') => {
610 match bytes.next().map(|(_, b)| b) {
611 Some(b'x') => backslash_x_byte(&mut bytes),
612 Some(b'n') |
613 Some(b'r') |
614 Some(b't') |
615 Some(b'\\') |
616 Some(b'0') |
617 Some(b'\'') |
618 Some(b'"') => true,
619 _ => false,
620 }
621 }
622 b => b.is_some(),
623 };
624 if ok {
625 match bytes.next() {
626 Some((offset, _)) => IResult::Done(&input[offset..], ()),
627 None => IResult::Done("", ()),
628 }
629 } else {
630 IResult::Error
631 }
632}
633
634named!(character -> (), do_parse!(
635 punct!("'") >>
636 cooked_char >>
637 tag!("'") >>
638 (())
639));
640
641fn cooked_char(input: &str) -> IResult<&str, ()> {
642 let mut chars = input.char_indices();
643 let ok = match chars.next().map(|(_, ch)| ch) {
644 Some('\\') => {
645 match chars.next().map(|(_, ch)| ch) {
646 Some('x') => backslash_x_char(&mut chars),
647 Some('u') => backslash_u(&mut chars),
648 Some('n') |
649 Some('r') |
650 Some('t') |
651 Some('\\') |
652 Some('0') |
653 Some('\'') |
654 Some('"') => true,
655 _ => false,
656 }
657 }
658 ch => ch.is_some(),
659 };
660 if ok {
661 IResult::Done(chars.as_str(), ())
662 } else {
663 IResult::Error
664 }
665}
666
667macro_rules! next_ch {
668 ($chars:ident @ $pat:pat $(| $rest:pat)*) => {
669 match $chars.next() {
670 Some((_, ch)) => match ch {
671 $pat $(| $rest)* => ch,
672 _ => return false,
673 },
674 None => return false
675 }
676 };
677}
678
679fn backslash_x_char<I>(chars: &mut I) -> bool
680 where I: Iterator<Item = (usize, char)>
681{
682 next_ch!(chars @ '0'...'7');
683 next_ch!(chars @ '0'...'9' | 'a'...'f' | 'A'...'F');
684 true
685}
686
687fn backslash_x_byte<I>(chars: &mut I) -> bool
688 where I: Iterator<Item = (usize, u8)>
689{
690 next_ch!(chars @ b'0'...b'9' | b'a'...b'f' | b'A'...b'F');
691 next_ch!(chars @ b'0'...b'9' | b'a'...b'f' | b'A'...b'F');
692 true
693}
694
695fn backslash_u<I>(chars: &mut I) -> bool
696 where I: Iterator<Item = (usize, char)>
697{
698 next_ch!(chars @ '{');
699 next_ch!(chars @ '0'...'9' | 'a'...'f' | 'A'...'F');
700 let b = next_ch!(chars @ '0'...'9' | 'a'...'f' | 'A'...'F' | '}');
701 if b == '}' {
702 return true
703 }
704 let c = next_ch!(chars @ '0'...'9' | 'a'...'f' | 'A'...'F' | '}');
705 if c == '}' {
706 return true
707 }
708 let d = next_ch!(chars @ '0'...'9' | 'a'...'f' | 'A'...'F' | '}');
709 if d == '}' {
710 return true
711 }
712 let e = next_ch!(chars @ '0'...'9' | 'a'...'f' | 'A'...'F' | '}');
713 if e == '}' {
714 return true
715 }
716 let f = next_ch!(chars @ '0'...'9' | 'a'...'f' | 'A'...'F' | '}');
717 if f == '}' {
718 return true
719 }
720 next_ch!(chars @ '}');
721 true
722}
723
724named!(float -> (), do_parse!(
725 float_string >>
726 alt!(
727 tag!("f32") => { |_| () }
728 |
729 tag!("f64") => { |_| () }
730 |
731 epsilon!()
732 ) >>
733 (())
734));
735
736fn float_string(input: &str) -> IResult<&str, ()> {
737 let mut chars = input.chars().peekable();
738 match chars.next() {
739 Some(ch) if ch >= '0' && ch <= '9' => {}
740 _ => return IResult::Error,
741 }
742
743 let mut len = 1;
744 let mut has_dot = false;
745 let mut has_exp = false;
746 while let Some(&ch) = chars.peek() {
747 match ch {
748 '0'...'9' | '_' => {
749 chars.next();
750 len += 1;
751 }
752 '.' => {
753 if has_dot {
754 break;
755 }
756 chars.next();
757 if chars.peek()
758 .map(|&ch| ch == '.' || UnicodeXID::is_xid_start(ch))
759 .unwrap_or(false) {
760 return IResult::Error;
761 }
762 len += 1;
763 has_dot = true;
764 }
765 'e' | 'E' => {
766 chars.next();
767 len += 1;
768 has_exp = true;
769 break;
770 }
771 _ => break,
772 }
773 }
774
775 let rest = &input[len..];
776 if !(has_dot || has_exp || rest.starts_with("f32") || rest.starts_with("f64")) {
777 return IResult::Error;
778 }
779
780 if has_exp {
781 let mut has_exp_value = false;
782 while let Some(&ch) = chars.peek() {
783 match ch {
784 '+' | '-' => {
785 if has_exp_value {
786 break;
787 }
788 chars.next();
789 len += 1;
790 }
791 '0'...'9' => {
792 chars.next();
793 len += 1;
794 has_exp_value = true;
795 }
796 '_' => {
797 chars.next();
798 len += 1;
799 }
800 _ => break,
801 }
802 }
803 if !has_exp_value {
804 return IResult::Error;
805 }
806 }
807
808 IResult::Done(&input[len..], ())
809}
810
811named!(int -> (), do_parse!(
812 digits >>
813 alt!(
814 tag!("isize") => { |_| () }
815 |
816 tag!("i8") => { |_| () }
817 |
818 tag!("i16") => { |_| () }
819 |
820 tag!("i32") => { |_| () }
821 |
822 tag!("i64") => { |_| () }
823 |
Michael Layzell30e35892017-05-31 19:49:31 -0400824 tag!("i128") => { |_| () }
825 |
Alex Crichton44bffbc2017-05-19 17:51:59 -0700826 tag!("usize") => { |_| () }
827 |
828 tag!("u8") => { |_| () }
829 |
830 tag!("u16") => { |_| () }
831 |
832 tag!("u32") => { |_| () }
833 |
834 tag!("u64") => { |_| () }
835 |
Michael Layzell30e35892017-05-31 19:49:31 -0400836 tag!("u128") => { |_| () }
837 |
Alex Crichton44bffbc2017-05-19 17:51:59 -0700838 epsilon!()
839 ) >>
840 (())
841));
842
843fn digits(mut input: &str) -> IResult<&str, ()> {
844 let base = if input.starts_with("0x") {
845 input = &input[2..];
846 16
847 } else if input.starts_with("0o") {
848 input = &input[2..];
849 8
850 } else if input.starts_with("0b") {
851 input = &input[2..];
852 2
853 } else {
854 10
855 };
856
Alex Crichton44bffbc2017-05-19 17:51:59 -0700857 let mut len = 0;
858 let mut empty = true;
859 for b in input.bytes() {
860 let digit = match b {
861 b'0'...b'9' => (b - b'0') as u64,
862 b'a'...b'f' => 10 + (b - b'a') as u64,
863 b'A'...b'F' => 10 + (b - b'A') as u64,
864 b'_' => {
865 if empty && base == 10 {
866 return IResult::Error;
867 }
868 len += 1;
869 continue;
870 }
871 _ => break,
872 };
873 if digit >= base {
874 return IResult::Error;
875 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700876 len += 1;
877 empty = false;
878 }
879 if empty {
880 IResult::Error
881 } else {
882 IResult::Done(&input[len..], ())
883 }
884}
885
886named!(boolean -> (), alt!(
887 keyword!("true") => { |_| () }
888 |
889 keyword!("false") => { |_| () }
890));
891
David Tolnayea75c5f2017-05-31 23:40:33 -0700892fn op(input: &str) -> IResult<&str, (char, OpKind)> {
893 let input = skip_whitespace(input);
894 match op_char(input) {
895 IResult::Done(rest, ch) => {
896 let kind = match op_char(rest) {
897 IResult::Done(_, _) => OpKind::Joint,
898 IResult::Error => OpKind::Alone,
899 };
900 IResult::Done(rest, (ch, kind))
901 }
902 IResult::Error => IResult::Error,
Alex Crichton44bffbc2017-05-19 17:51:59 -0700903 }
904}
905
David Tolnayea75c5f2017-05-31 23:40:33 -0700906fn op_char(input: &str) -> IResult<&str, char> {
907 let mut chars = input.chars();
908 let first = match chars.next() {
909 Some(ch) => ch,
910 None => {
911 return IResult::Error;
912 }
913 };
914 let recognized = "~!@#$%^&*-=+|;:,<.>/?";
915 if recognized.contains(first) {
916 IResult::Done(chars.as_str(), first)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700917 } else {
918 IResult::Error
919 }
920}
921
Alex Crichton44bffbc2017-05-19 17:51:59 -0700922named!(doc_comment -> (), alt!(
923 do_parse!(
924 punct!("//!") >>
925 take_until!("\n") >>
926 (())
927 )
928 |
929 do_parse!(
930 option!(whitespace) >>
931 peek!(tag!("/*!")) >>
932 block_comment >>
933 (())
934 )
935 |
936 do_parse!(
937 punct!("///") >>
938 not!(tag!("/")) >>
939 take_until!("\n") >>
940 (())
941 )
942 |
943 do_parse!(
944 option!(whitespace) >>
945 peek!(tuple!(tag!("/**"), not!(tag!("*")))) >>
946 block_comment >>
947 (())
948 )
949));
950
951#[cfg(test)]
952mod tests {
953 use super::*;
954
955 #[test]
956 fn symbols() {
957 assert_eq!(&*Symbol::from("foo"), "foo");
958 assert_eq!(&*Symbol::from("bar"), "bar");
959 }
960
961 #[test]
962 fn literals() {
963 assert_eq!(Literal::from("foo").to_string(), "\"foo\"");
964 assert_eq!(Literal::from("\"").to_string(), "\"\\\"\"");
965 }
966
967 #[test]
968 fn roundtrip() {
969 fn roundtrip(p: &str) {
970 println!("parse: {}", p);
971 let s = p.parse::<TokenStream>().unwrap().to_string();
972 println!("first: {}", s);
973 let s2 = s.to_string().parse::<TokenStream>().unwrap().to_string();
974 assert_eq!(s, s2);
975 }
976 roundtrip("a");
977 roundtrip("<<");
978 roundtrip("<<=");
979 roundtrip("
980 /// a
981 wut
982 ");
983 roundtrip("
984 1
985 1.0
986 1f32
987 2f64
988 1usize
989 4isize
990 4e10
991 1_000
992 1_0i32
993 8u8
994 9
995 0
Michael Layzell9ee75c92017-05-31 19:44:26 -0400996 0xffffffffffffffffffffffffffffffff
Alex Crichton44bffbc2017-05-19 17:51:59 -0700997 ");
998 }
999}