blob: 0d8aac9da426ac155d0b031fa165eb2886f4f5f9 [file] [log] [blame]
Alex Crichtona914a612018-04-04 07:48:44 -07001#![cfg_attr(not(procmacro2_semver_exempt), allow(dead_code))]
Alex Crichtonaf5bad42018-03-27 14:45:10 -07002
David Tolnayc2309ca2018-06-02 15:47:57 -07003#[cfg(procmacro2_semver_exempt)]
Alex Crichton44bffbc2017-05-19 17:51:59 -07004use std::cell::RefCell;
David Tolnay1ebe3972018-01-02 20:14:20 -08005#[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -05006use std::cmp;
Alex Crichton44bffbc2017-05-19 17:51:59 -07007use std::fmt;
8use std::iter;
Alex Crichton44bffbc2017-05-19 17:51:59 -07009use std::str::FromStr;
10use std::vec;
11
David Tolnayb28f38a2018-03-31 22:02:29 +020012use strnom::{block_comment, skip_whitespace, whitespace, word_break, Cursor, PResult};
David Tolnayb1032662017-05-31 15:52:28 -070013use unicode_xid::UnicodeXID;
Alex Crichton44bffbc2017-05-19 17:51:59 -070014
David Tolnayf14813f2018-09-08 17:14:07 -070015use {Delimiter, Punct, Spacing, TokenTree};
Alex Crichton44bffbc2017-05-19 17:51:59 -070016
David Tolnay034205f2018-04-22 16:45:28 -070017#[derive(Clone)]
Alex Crichton44bffbc2017-05-19 17:51:59 -070018pub struct TokenStream {
19 inner: Vec<TokenTree>,
20}
21
22#[derive(Debug)]
23pub struct LexError;
24
25impl TokenStream {
David Tolnayc3bb4592018-05-28 20:09:44 -070026 pub fn new() -> TokenStream {
Alex Crichton44bffbc2017-05-19 17:51:59 -070027 TokenStream { inner: Vec::new() }
28 }
29
30 pub fn is_empty(&self) -> bool {
31 self.inner.len() == 0
32 }
33}
34
David Tolnay1ebe3972018-01-02 20:14:20 -080035#[cfg(procmacro2_semver_exempt)]
Nika Layzella9dbc182017-12-30 14:50:13 -050036fn get_cursor(src: &str) -> Cursor {
37 // Create a dummy file & add it to the codemap
38 CODEMAP.with(|cm| {
39 let mut cm = cm.borrow_mut();
40 let name = format!("<parsed string {}>", cm.files.len());
41 let span = cm.add_file(&name, src);
42 Cursor {
43 rest: src,
44 off: span.lo,
45 }
46 })
47}
48
David Tolnay1ebe3972018-01-02 20:14:20 -080049#[cfg(not(procmacro2_semver_exempt))]
Nika Layzella9dbc182017-12-30 14:50:13 -050050fn get_cursor(src: &str) -> Cursor {
David Tolnayb28f38a2018-03-31 22:02:29 +020051 Cursor { rest: src }
Nika Layzella9dbc182017-12-30 14:50:13 -050052}
53
Alex Crichton44bffbc2017-05-19 17:51:59 -070054impl FromStr for TokenStream {
55 type Err = LexError;
56
57 fn from_str(src: &str) -> Result<TokenStream, LexError> {
Nika Layzellf8d5f212017-12-11 14:07:02 -050058 // Create a dummy file & add it to the codemap
Nika Layzella9dbc182017-12-30 14:50:13 -050059 let cursor = get_cursor(src);
Nika Layzellf8d5f212017-12-11 14:07:02 -050060
61 match token_stream(cursor) {
David Tolnay1218e122017-06-01 11:13:45 -070062 Ok((input, output)) => {
Alex Crichton44bffbc2017-05-19 17:51:59 -070063 if skip_whitespace(input).len() != 0 {
64 Err(LexError)
65 } else {
Alex Crichton30a4e9e2018-04-27 17:02:19 -070066 Ok(output)
Alex Crichton44bffbc2017-05-19 17:51:59 -070067 }
68 }
David Tolnay1218e122017-06-01 11:13:45 -070069 Err(LexError) => Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -070070 }
71 }
72}
73
74impl fmt::Display for TokenStream {
75 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
76 let mut joint = false;
77 for (i, tt) in self.inner.iter().enumerate() {
78 if i != 0 && !joint {
79 write!(f, " ")?;
80 }
81 joint = false;
Alex Crichtonaf5bad42018-03-27 14:45:10 -070082 match *tt {
83 TokenTree::Group(ref tt) => {
84 let (start, end) = match tt.delimiter() {
Alex Crichton44bffbc2017-05-19 17:51:59 -070085 Delimiter::Parenthesis => ("(", ")"),
86 Delimiter::Brace => ("{", "}"),
87 Delimiter::Bracket => ("[", "]"),
88 Delimiter::None => ("", ""),
89 };
Alex Crichton30a4e9e2018-04-27 17:02:19 -070090 if tt.stream().into_iter().next().is_none() {
Alex Crichton852d53d2017-05-19 19:25:08 -070091 write!(f, "{} {}", start, end)?
92 } else {
Alex Crichtonaf5bad42018-03-27 14:45:10 -070093 write!(f, "{} {} {}", start, tt.stream(), end)?
Alex Crichton852d53d2017-05-19 19:25:08 -070094 }
Alex Crichton44bffbc2017-05-19 17:51:59 -070095 }
Alex Crichtonf3888432018-05-16 09:11:05 -070096 TokenTree::Ident(ref tt) => write!(f, "{}", tt)?,
97 TokenTree::Punct(ref tt) => {
98 write!(f, "{}", tt.as_char())?;
Alex Crichtonaf5bad42018-03-27 14:45:10 -070099 match tt.spacing() {
Alex Crichton1a7f7622017-07-05 17:47:15 -0700100 Spacing::Alone => {}
101 Spacing::Joint => joint = true,
Alex Crichton44bffbc2017-05-19 17:51:59 -0700102 }
103 }
Alex Crichtonb2c94622018-04-04 07:36:41 -0700104 TokenTree::Literal(ref tt) => write!(f, "{}", tt)?,
Alex Crichton44bffbc2017-05-19 17:51:59 -0700105 }
106 }
107
108 Ok(())
109 }
110}
111
David Tolnay034205f2018-04-22 16:45:28 -0700112impl fmt::Debug for TokenStream {
113 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
114 f.write_str("TokenStream ")?;
115 f.debug_list().entries(self.clone()).finish()
116 }
117}
118
Alex Crichton53548482018-08-11 21:54:05 -0700119#[cfg(use_proc_macro)]
Alex Crichton0e8e7f42018-02-22 06:15:13 -0800120impl From<::proc_macro::TokenStream> for TokenStream {
121 fn from(inner: ::proc_macro::TokenStream) -> TokenStream {
David Tolnayb28f38a2018-03-31 22:02:29 +0200122 inner
123 .to_string()
124 .parse()
125 .expect("compiler token stream parse failed")
Alex Crichton44bffbc2017-05-19 17:51:59 -0700126 }
127}
128
Alex Crichton53548482018-08-11 21:54:05 -0700129#[cfg(use_proc_macro)]
Alex Crichton0e8e7f42018-02-22 06:15:13 -0800130impl From<TokenStream> for ::proc_macro::TokenStream {
131 fn from(inner: TokenStream) -> ::proc_macro::TokenStream {
David Tolnayb28f38a2018-03-31 22:02:29 +0200132 inner
133 .to_string()
134 .parse()
135 .expect("failed to parse to compiler tokens")
Alex Crichton44bffbc2017-05-19 17:51:59 -0700136 }
137}
138
Alex Crichton44bffbc2017-05-19 17:51:59 -0700139impl From<TokenTree> for TokenStream {
140 fn from(tree: TokenTree) -> TokenStream {
141 TokenStream { inner: vec![tree] }
142 }
143}
144
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700145impl iter::FromIterator<TokenTree> for TokenStream {
David Tolnayb28f38a2018-03-31 22:02:29 +0200146 fn from_iter<I: IntoIterator<Item = TokenTree>>(streams: I) -> Self {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700147 let mut v = Vec::new();
148
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700149 for token in streams.into_iter() {
150 v.push(token);
Alex Crichton44bffbc2017-05-19 17:51:59 -0700151 }
152
153 TokenStream { inner: v }
154 }
155}
156
Alex Crichton53b00672018-09-06 17:16:10 -0700157impl iter::FromIterator<TokenStream> for TokenStream {
158 fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
159 let mut v = Vec::new();
160
161 for stream in streams.into_iter() {
162 v.extend(stream.inner);
163 }
164
165 TokenStream { inner: v }
166 }
167}
168
Alex Crichtonf3888432018-05-16 09:11:05 -0700169impl Extend<TokenTree> for TokenStream {
170 fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, streams: I) {
171 self.inner.extend(streams);
172 }
173}
174
David Tolnay5c58c532018-08-13 11:33:51 -0700175impl Extend<TokenStream> for TokenStream {
176 fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
177 self.inner
178 .extend(streams.into_iter().flat_map(|stream| stream));
179 }
180}
181
Alex Crichton1a7f7622017-07-05 17:47:15 -0700182pub type TokenTreeIter = vec::IntoIter<TokenTree>;
Alex Crichton44bffbc2017-05-19 17:51:59 -0700183
184impl IntoIterator for TokenStream {
185 type Item = TokenTree;
Alex Crichton1a7f7622017-07-05 17:47:15 -0700186 type IntoIter = TokenTreeIter;
Alex Crichton44bffbc2017-05-19 17:51:59 -0700187
Alex Crichton1a7f7622017-07-05 17:47:15 -0700188 fn into_iter(self) -> TokenTreeIter {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700189 self.inner.into_iter()
190 }
191}
192
Nika Layzellb35a9a32017-12-30 14:34:35 -0500193#[derive(Clone, PartialEq, Eq, Debug)]
194pub struct FileName(String);
195
Alex Crichtonf3888432018-05-16 09:11:05 -0700196#[allow(dead_code)]
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700197pub fn file_name(s: String) -> FileName {
198 FileName(s)
199}
200
Nika Layzellb35a9a32017-12-30 14:34:35 -0500201impl fmt::Display for FileName {
202 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
203 self.0.fmt(f)
204 }
205}
206
Nika Layzellf8d5f212017-12-11 14:07:02 -0500207#[derive(Clone, PartialEq, Eq)]
208pub struct SourceFile {
Nika Layzellb35a9a32017-12-30 14:34:35 -0500209 name: FileName,
Nika Layzellf8d5f212017-12-11 14:07:02 -0500210}
211
212impl SourceFile {
213 /// Get the path to this source file as a string.
Nika Layzellb35a9a32017-12-30 14:34:35 -0500214 pub fn path(&self) -> &FileName {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500215 &self.name
216 }
217
218 pub fn is_real(&self) -> bool {
219 // XXX(nika): Support real files in the future?
220 false
221 }
222}
223
Nika Layzellb35a9a32017-12-30 14:34:35 -0500224impl AsRef<FileName> for SourceFile {
225 fn as_ref(&self) -> &FileName {
226 self.path()
Nika Layzellf8d5f212017-12-11 14:07:02 -0500227 }
228}
229
230impl fmt::Debug for SourceFile {
231 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
232 f.debug_struct("SourceFile")
Nika Layzellb35a9a32017-12-30 14:34:35 -0500233 .field("path", &self.path())
Nika Layzellf8d5f212017-12-11 14:07:02 -0500234 .field("is_real", &self.is_real())
235 .finish()
236 }
237}
238
239#[derive(Clone, Copy, Debug, PartialEq, Eq)]
240pub struct LineColumn {
241 pub line: usize,
242 pub column: usize,
243}
244
David Tolnay1ebe3972018-01-02 20:14:20 -0800245#[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500246thread_local! {
247 static CODEMAP: RefCell<Codemap> = RefCell::new(Codemap {
248 // NOTE: We start with a single dummy file which all call_site() and
249 // def_site() spans reference.
250 files: vec![FileInfo {
251 name: "<unspecified>".to_owned(),
252 span: Span { lo: 0, hi: 0 },
253 lines: vec![0],
254 }],
255 });
256}
257
David Tolnay1ebe3972018-01-02 20:14:20 -0800258#[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500259struct FileInfo {
260 name: String,
261 span: Span,
262 lines: Vec<usize>,
263}
264
David Tolnay1ebe3972018-01-02 20:14:20 -0800265#[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500266impl FileInfo {
267 fn offset_line_column(&self, offset: usize) -> LineColumn {
David Tolnayb28f38a2018-03-31 22:02:29 +0200268 assert!(self.span_within(Span {
269 lo: offset as u32,
270 hi: offset as u32
271 }));
Nika Layzellf8d5f212017-12-11 14:07:02 -0500272 let offset = offset - self.span.lo as usize;
273 match self.lines.binary_search(&offset) {
274 Ok(found) => LineColumn {
275 line: found + 1,
David Tolnayb28f38a2018-03-31 22:02:29 +0200276 column: 0,
Nika Layzellf8d5f212017-12-11 14:07:02 -0500277 },
278 Err(idx) => LineColumn {
279 line: idx,
David Tolnayb28f38a2018-03-31 22:02:29 +0200280 column: offset - self.lines[idx - 1],
Nika Layzellf8d5f212017-12-11 14:07:02 -0500281 },
282 }
283 }
284
285 fn span_within(&self, span: Span) -> bool {
286 span.lo >= self.span.lo && span.hi <= self.span.hi
287 }
288}
289
Alex Crichtona914a612018-04-04 07:48:44 -0700290/// Computesthe offsets of each line in the given source string.
David Tolnay1ebe3972018-01-02 20:14:20 -0800291#[cfg(procmacro2_semver_exempt)]
Nika Layzella0a7c3d2017-12-30 14:52:39 -0500292fn lines_offsets(s: &str) -> Vec<usize> {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500293 let mut lines = vec![0];
294 let mut prev = 0;
Nika Layzella0a7c3d2017-12-30 14:52:39 -0500295 while let Some(len) = s[prev..].find('\n') {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500296 prev += len + 1;
297 lines.push(prev);
298 }
299 lines
300}
301
David Tolnay1ebe3972018-01-02 20:14:20 -0800302#[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500303struct Codemap {
304 files: Vec<FileInfo>,
305}
306
David Tolnay1ebe3972018-01-02 20:14:20 -0800307#[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500308impl Codemap {
309 fn next_start_pos(&self) -> u32 {
310 // Add 1 so there's always space between files.
311 //
312 // We'll always have at least 1 file, as we initialize our files list
313 // with a dummy file.
314 self.files.last().unwrap().span.hi + 1
315 }
316
317 fn add_file(&mut self, name: &str, src: &str) -> Span {
Nika Layzella0a7c3d2017-12-30 14:52:39 -0500318 let lines = lines_offsets(src);
Nika Layzellf8d5f212017-12-11 14:07:02 -0500319 let lo = self.next_start_pos();
320 // XXX(nika): Shouild we bother doing a checked cast or checked add here?
David Tolnayb28f38a2018-03-31 22:02:29 +0200321 let span = Span {
322 lo: lo,
323 hi: lo + (src.len() as u32),
324 };
Nika Layzellf8d5f212017-12-11 14:07:02 -0500325
326 self.files.push(FileInfo {
327 name: name.to_owned(),
328 span: span,
329 lines: lines,
330 });
331
332 span
333 }
334
335 fn fileinfo(&self, span: Span) -> &FileInfo {
336 for file in &self.files {
337 if file.span_within(span) {
338 return file;
339 }
340 }
341 panic!("Invalid span with no related FileInfo!");
342 }
343}
344
David Tolnay034205f2018-04-22 16:45:28 -0700345#[derive(Clone, Copy, PartialEq, Eq)]
David Tolnayddfca052017-12-31 10:41:24 -0500346pub struct Span {
David Tolnay1ebe3972018-01-02 20:14:20 -0800347 #[cfg(procmacro2_semver_exempt)]
David Tolnayddfca052017-12-31 10:41:24 -0500348 lo: u32,
David Tolnay1ebe3972018-01-02 20:14:20 -0800349 #[cfg(procmacro2_semver_exempt)]
David Tolnayddfca052017-12-31 10:41:24 -0500350 hi: u32,
351}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700352
353impl Span {
David Tolnay1ebe3972018-01-02 20:14:20 -0800354 #[cfg(not(procmacro2_semver_exempt))]
Alex Crichton44bffbc2017-05-19 17:51:59 -0700355 pub fn call_site() -> Span {
David Tolnay79105e52017-12-31 11:03:04 -0500356 Span {}
357 }
358
David Tolnay1ebe3972018-01-02 20:14:20 -0800359 #[cfg(procmacro2_semver_exempt)]
David Tolnay79105e52017-12-31 11:03:04 -0500360 pub fn call_site() -> Span {
361 Span { lo: 0, hi: 0 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700362 }
Alex Crichtone6085b72017-11-21 07:24:25 -0800363
364 pub fn def_site() -> Span {
David Tolnay79105e52017-12-31 11:03:04 -0500365 Span::call_site()
Nika Layzellf8d5f212017-12-11 14:07:02 -0500366 }
367
David Tolnay4e8e3972018-01-05 18:10:22 -0800368 pub fn resolved_at(&self, _other: Span) -> Span {
369 // Stable spans consist only of line/column information, so
370 // `resolved_at` and `located_at` only select which span the
371 // caller wants line/column information from.
372 *self
373 }
374
375 pub fn located_at(&self, other: Span) -> Span {
376 other
377 }
378
David Tolnay1ebe3972018-01-02 20:14:20 -0800379 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500380 pub fn source_file(&self) -> SourceFile {
381 CODEMAP.with(|cm| {
382 let cm = cm.borrow();
383 let fi = cm.fileinfo(*self);
384 SourceFile {
Nika Layzellb35a9a32017-12-30 14:34:35 -0500385 name: FileName(fi.name.clone()),
Nika Layzellf8d5f212017-12-11 14:07:02 -0500386 }
387 })
388 }
389
David Tolnay1ebe3972018-01-02 20:14:20 -0800390 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500391 pub fn start(&self) -> LineColumn {
392 CODEMAP.with(|cm| {
393 let cm = cm.borrow();
394 let fi = cm.fileinfo(*self);
395 fi.offset_line_column(self.lo as usize)
396 })
397 }
398
David Tolnay1ebe3972018-01-02 20:14:20 -0800399 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500400 pub fn end(&self) -> LineColumn {
401 CODEMAP.with(|cm| {
402 let cm = cm.borrow();
403 let fi = cm.fileinfo(*self);
404 fi.offset_line_column(self.hi as usize)
405 })
406 }
407
David Tolnay1ebe3972018-01-02 20:14:20 -0800408 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500409 pub fn join(&self, other: Span) -> Option<Span> {
410 CODEMAP.with(|cm| {
411 let cm = cm.borrow();
412 // If `other` is not within the same FileInfo as us, return None.
413 if !cm.fileinfo(*self).span_within(other) {
414 return None;
415 }
416 Some(Span {
417 lo: cmp::min(self.lo, other.lo),
418 hi: cmp::max(self.hi, other.hi),
419 })
420 })
Alex Crichtone6085b72017-11-21 07:24:25 -0800421 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700422}
423
David Tolnay034205f2018-04-22 16:45:28 -0700424impl fmt::Debug for Span {
425 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
426 #[cfg(procmacro2_semver_exempt)]
427 return write!(f, "bytes({}..{})", self.lo, self.hi);
428
429 #[cfg(not(procmacro2_semver_exempt))]
430 write!(f, "Span")
431 }
432}
433
Alex Crichtonf3888432018-05-16 09:11:05 -0700434#[derive(Clone)]
David Tolnayf14813f2018-09-08 17:14:07 -0700435pub struct Group {
436 delimiter: Delimiter,
437 stream: TokenStream,
438 span: Span,
439}
440
441impl Group {
442 pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
443 Group {
444 delimiter: delimiter,
445 stream: stream,
446 span: Span::call_site(),
447 }
448 }
449
450 pub fn delimiter(&self) -> Delimiter {
451 self.delimiter
452 }
453
454 pub fn stream(&self) -> TokenStream {
455 self.stream.clone()
456 }
457
458 pub fn span(&self) -> Span {
459 self.span
460 }
461
462 pub fn span_open(&self) -> Span {
463 self.span
464 }
465
466 pub fn span_close(&self) -> Span {
467 self.span
468 }
469
470 pub fn set_span(&mut self, span: Span) {
471 self.span = span;
472 }
473}
474
475impl fmt::Display for Group {
476 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
477 let (left, right) = match self.delimiter {
478 Delimiter::Parenthesis => ("(", ")"),
479 Delimiter::Brace => ("{", "}"),
480 Delimiter::Bracket => ("[", "]"),
481 Delimiter::None => ("", ""),
482 };
483
484 f.write_str(left)?;
485 self.stream.fmt(f)?;
486 f.write_str(right)?;
487
488 Ok(())
489 }
490}
491
492impl fmt::Debug for Group {
493 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
494 let mut debug = fmt.debug_struct("Group");
495 debug.field("delimiter", &self.delimiter);
496 debug.field("stream", &self.stream);
497 #[cfg(procmacro2_semver_exempt)]
498 debug.field("span", &self.span);
499 debug.finish()
500 }
501}
502
503#[derive(Clone)]
Alex Crichtonf3888432018-05-16 09:11:05 -0700504pub struct Ident {
David Tolnayc2309ca2018-06-02 15:47:57 -0700505 sym: String,
Alex Crichtonb2c94622018-04-04 07:36:41 -0700506 span: Span,
Alex Crichtonf3888432018-05-16 09:11:05 -0700507 raw: bool,
David Tolnay041bcd42017-06-03 09:18:04 -0700508}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700509
Alex Crichtonf3888432018-05-16 09:11:05 -0700510impl Ident {
511 fn _new(string: &str, raw: bool, span: Span) -> Ident {
David Tolnay489c6422018-04-07 08:37:28 -0700512 validate_term(string);
513
Alex Crichtonf3888432018-05-16 09:11:05 -0700514 Ident {
David Tolnayc2309ca2018-06-02 15:47:57 -0700515 sym: string.to_owned(),
Alex Crichtona914a612018-04-04 07:48:44 -0700516 span: span,
Alex Crichtonf3888432018-05-16 09:11:05 -0700517 raw: raw,
David Tolnay041bcd42017-06-03 09:18:04 -0700518 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700519 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700520
Alex Crichtonf3888432018-05-16 09:11:05 -0700521 pub fn new(string: &str, span: Span) -> Ident {
522 Ident::_new(string, false, span)
523 }
524
525 pub fn new_raw(string: &str, span: Span) -> Ident {
526 Ident::_new(string, true, span)
527 }
528
Alex Crichtonb2c94622018-04-04 07:36:41 -0700529 pub fn span(&self) -> Span {
530 self.span
531 }
532
533 pub fn set_span(&mut self, span: Span) {
534 self.span = span;
535 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700536}
537
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000538#[inline]
539fn is_ident_start(c: char) -> bool {
David Tolnay03b43da2018-06-02 15:25:57 -0700540 ('a' <= c && c <= 'z')
541 || ('A' <= c && c <= 'Z')
542 || c == '_'
543 || (c > '\x7f' && UnicodeXID::is_xid_start(c))
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000544}
545
546#[inline]
547fn is_ident_continue(c: char) -> bool {
David Tolnay03b43da2018-06-02 15:25:57 -0700548 ('a' <= c && c <= 'z')
549 || ('A' <= c && c <= 'Z')
550 || c == '_'
551 || ('0' <= c && c <= '9')
552 || (c > '\x7f' && UnicodeXID::is_xid_continue(c))
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000553}
554
David Tolnay489c6422018-04-07 08:37:28 -0700555fn validate_term(string: &str) {
Alex Crichtonf3888432018-05-16 09:11:05 -0700556 let validate = string;
David Tolnay489c6422018-04-07 08:37:28 -0700557 if validate.is_empty() {
Alex Crichtonf3888432018-05-16 09:11:05 -0700558 panic!("Ident is not allowed to be empty; use Option<Ident>");
David Tolnay489c6422018-04-07 08:37:28 -0700559 }
560
561 if validate.bytes().all(|digit| digit >= b'0' && digit <= b'9') {
Alex Crichtonf3888432018-05-16 09:11:05 -0700562 panic!("Ident cannot be a number; use Literal instead");
David Tolnay489c6422018-04-07 08:37:28 -0700563 }
564
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000565 fn ident_ok(string: &str) -> bool {
David Tolnay489c6422018-04-07 08:37:28 -0700566 let mut chars = string.chars();
567 let first = chars.next().unwrap();
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000568 if !is_ident_start(first) {
David Tolnay489c6422018-04-07 08:37:28 -0700569 return false;
570 }
571 for ch in chars {
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000572 if !is_ident_continue(ch) {
David Tolnay489c6422018-04-07 08:37:28 -0700573 return false;
574 }
575 }
576 true
577 }
578
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000579 if !ident_ok(validate) {
Alex Crichtonf3888432018-05-16 09:11:05 -0700580 panic!("{:?} is not a valid Ident", string);
David Tolnay489c6422018-04-07 08:37:28 -0700581 }
582}
583
David Tolnayc0b0f2e2018-09-02 17:56:08 -0700584impl PartialEq for Ident {
585 fn eq(&self, other: &Ident) -> bool {
586 self.sym == other.sym && self.raw == other.raw
587 }
588}
589
590impl<T> PartialEq<T> for Ident
591where
592 T: ?Sized + AsRef<str>,
593{
594 fn eq(&self, other: &T) -> bool {
595 let other = other.as_ref();
596 if self.raw {
597 other.starts_with("r#") && self.sym == other[2..]
598 } else {
599 self.sym == other
600 }
601 }
602}
603
Alex Crichtonf3888432018-05-16 09:11:05 -0700604impl fmt::Display for Ident {
David Tolnay8ad3e3e2017-06-03 16:45:00 -0700605 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Alex Crichtonf3888432018-05-16 09:11:05 -0700606 if self.raw {
607 "r#".fmt(f)?;
608 }
David Tolnayc2309ca2018-06-02 15:47:57 -0700609 self.sym.fmt(f)
Alex Crichtonf3888432018-05-16 09:11:05 -0700610 }
611}
612
613impl fmt::Debug for Ident {
David Tolnayd8fcdb82018-06-02 15:43:53 -0700614 // Ident(proc_macro), Ident(r#union)
615 #[cfg(not(procmacro2_semver_exempt))]
616 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
617 let mut debug = f.debug_tuple("Ident");
618 debug.field(&format_args!("{}", self));
619 debug.finish()
620 }
621
622 // Ident {
623 // sym: proc_macro,
624 // span: bytes(128..138)
625 // }
626 #[cfg(procmacro2_semver_exempt)]
Alex Crichtonf3888432018-05-16 09:11:05 -0700627 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
628 let mut debug = f.debug_struct("Ident");
David Tolnayd8fcdb82018-06-02 15:43:53 -0700629 debug.field("sym", &format_args!("{}", self));
David Tolnay034205f2018-04-22 16:45:28 -0700630 debug.field("span", &self.span);
631 debug.finish()
David Tolnay8ad3e3e2017-06-03 16:45:00 -0700632 }
633}
634
David Tolnay034205f2018-04-22 16:45:28 -0700635#[derive(Clone)]
Alex Crichtonb2c94622018-04-04 07:36:41 -0700636pub struct Literal {
637 text: String,
638 span: Span,
639}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700640
Alex Crichtona914a612018-04-04 07:48:44 -0700641macro_rules! suffixed_numbers {
642 ($($name:ident => $kind:ident,)*) => ($(
643 pub fn $name(n: $kind) -> Literal {
644 Literal::_new(format!(concat!("{}", stringify!($kind)), n))
645 }
646 )*)
647}
648
649macro_rules! unsuffixed_numbers {
650 ($($name:ident => $kind:ident,)*) => ($(
651 pub fn $name(n: $kind) -> Literal {
652 Literal::_new(n.to_string())
653 }
654 )*)
655}
656
Alex Crichton852d53d2017-05-19 19:25:08 -0700657impl Literal {
Alex Crichtonb2c94622018-04-04 07:36:41 -0700658 fn _new(text: String) -> Literal {
659 Literal {
Alex Crichtona914a612018-04-04 07:48:44 -0700660 text: text,
Alex Crichtonb2c94622018-04-04 07:36:41 -0700661 span: Span::call_site(),
662 }
663 }
664
Alex Crichtona914a612018-04-04 07:48:44 -0700665 suffixed_numbers! {
666 u8_suffixed => u8,
667 u16_suffixed => u16,
668 u32_suffixed => u32,
669 u64_suffixed => u64,
670 usize_suffixed => usize,
671 i8_suffixed => i8,
672 i16_suffixed => i16,
673 i32_suffixed => i32,
674 i64_suffixed => i64,
675 isize_suffixed => isize,
676
677 f32_suffixed => f32,
678 f64_suffixed => f64,
679 }
680
Alex Crichton69385662018-11-08 06:30:04 -0800681 #[cfg(u128)]
682 suffixed_numbers! {
683 u128_suffixed => u128,
684 i128_suffixed => i128,
685 }
686
Alex Crichtona914a612018-04-04 07:48:44 -0700687 unsuffixed_numbers! {
688 u8_unsuffixed => u8,
689 u16_unsuffixed => u16,
690 u32_unsuffixed => u32,
691 u64_unsuffixed => u64,
692 usize_unsuffixed => usize,
693 i8_unsuffixed => i8,
694 i16_unsuffixed => i16,
695 i32_unsuffixed => i32,
696 i64_unsuffixed => i64,
697 isize_unsuffixed => isize,
698 }
699
Alex Crichton69385662018-11-08 06:30:04 -0800700 #[cfg(u128)]
701 unsuffixed_numbers! {
702 u128_unsuffixed => u128,
703 i128_unsuffixed => i128,
704 }
705
Alex Crichtona914a612018-04-04 07:48:44 -0700706 pub fn f32_unsuffixed(f: f32) -> Literal {
707 let mut s = f.to_string();
708 if !s.contains(".") {
709 s.push_str(".0");
Alex Crichton76a5cc82017-05-23 07:01:44 -0700710 }
Alex Crichtona914a612018-04-04 07:48:44 -0700711 Literal::_new(s)
712 }
713
714 pub fn f64_unsuffixed(f: f64) -> Literal {
715 let mut s = f.to_string();
716 if !s.contains(".") {
717 s.push_str(".0");
718 }
719 Literal::_new(s)
720 }
721
722 pub fn string(t: &str) -> Literal {
David Tolnay3d9d6ad2018-05-18 10:51:55 -0700723 let mut s = t
724 .chars()
Alex Crichtona914a612018-04-04 07:48:44 -0700725 .flat_map(|c| c.escape_default())
726 .collect::<String>();
727 s.push('"');
728 s.insert(0, '"');
729 Literal::_new(s)
730 }
731
732 pub fn character(t: char) -> Literal {
733 Literal::_new(format!("'{}'", t.escape_default().collect::<String>()))
Alex Crichton76a5cc82017-05-23 07:01:44 -0700734 }
735
Alex Crichton9c2fb0a2017-05-26 08:49:31 -0700736 pub fn byte_string(bytes: &[u8]) -> Literal {
Alex Crichton852d53d2017-05-19 19:25:08 -0700737 let mut escaped = "b\"".to_string();
738 for b in bytes {
739 match *b {
740 b'\0' => escaped.push_str(r"\0"),
741 b'\t' => escaped.push_str(r"\t"),
742 b'\n' => escaped.push_str(r"\n"),
743 b'\r' => escaped.push_str(r"\r"),
744 b'"' => escaped.push_str("\\\""),
745 b'\\' => escaped.push_str("\\\\"),
David Tolnayb28f38a2018-03-31 22:02:29 +0200746 b'\x20'...b'\x7E' => escaped.push(*b as char),
Alex Crichton852d53d2017-05-19 19:25:08 -0700747 _ => escaped.push_str(&format!("\\x{:02X}", b)),
748 }
749 }
750 escaped.push('"');
Alex Crichtonb2c94622018-04-04 07:36:41 -0700751 Literal::_new(escaped)
Alex Crichton76a5cc82017-05-23 07:01:44 -0700752 }
Alex Crichton9c2fb0a2017-05-26 08:49:31 -0700753
Alex Crichtonb2c94622018-04-04 07:36:41 -0700754 pub fn span(&self) -> Span {
755 self.span
Alex Crichton31316622017-05-26 12:54:47 -0700756 }
757
Alex Crichtonb2c94622018-04-04 07:36:41 -0700758 pub fn set_span(&mut self, span: Span) {
759 self.span = span;
Alex Crichton31316622017-05-26 12:54:47 -0700760 }
Alex Crichton852d53d2017-05-19 19:25:08 -0700761}
762
Alex Crichton44bffbc2017-05-19 17:51:59 -0700763impl fmt::Display for Literal {
764 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Alex Crichtonb2c94622018-04-04 07:36:41 -0700765 self.text.fmt(f)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700766 }
767}
768
David Tolnay034205f2018-04-22 16:45:28 -0700769impl fmt::Debug for Literal {
770 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
771 let mut debug = fmt.debug_struct("Literal");
772 debug.field("lit", &format_args!("{}", self.text));
773 #[cfg(procmacro2_semver_exempt)]
774 debug.field("span", &self.span);
775 debug.finish()
776 }
777}
778
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700779fn token_stream(mut input: Cursor) -> PResult<TokenStream> {
Alex Crichton1eb96a02018-04-04 13:07:35 -0700780 let mut trees = Vec::new();
781 loop {
782 let input_no_ws = skip_whitespace(input);
783 if input_no_ws.rest.len() == 0 {
David Tolnay48ea5042018-04-23 19:17:35 -0700784 break;
Alex Crichton1eb96a02018-04-04 13:07:35 -0700785 }
786 if let Ok((a, tokens)) = doc_comment(input_no_ws) {
787 input = a;
788 trees.extend(tokens);
David Tolnay48ea5042018-04-23 19:17:35 -0700789 continue;
Alex Crichton1eb96a02018-04-04 13:07:35 -0700790 }
791
792 let (a, tt) = match token_tree(input_no_ws) {
793 Ok(p) => p,
794 Err(_) => break,
795 };
796 trees.push(tt);
797 input = a;
798 }
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700799 Ok((input, TokenStream { inner: trees }))
Alex Crichton1eb96a02018-04-04 13:07:35 -0700800}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700801
David Tolnay1ebe3972018-01-02 20:14:20 -0800802#[cfg(not(procmacro2_semver_exempt))]
Alex Crichton1eb96a02018-04-04 13:07:35 -0700803fn spanned<'a, T>(
804 input: Cursor<'a>,
805 f: fn(Cursor<'a>) -> PResult<'a, T>,
806) -> PResult<'a, (T, ::Span)> {
807 let (a, b) = f(skip_whitespace(input))?;
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700808 Ok((a, ((b, ::Span::_new_stable(Span {})))))
David Tolnayddfca052017-12-31 10:41:24 -0500809}
810
David Tolnay1ebe3972018-01-02 20:14:20 -0800811#[cfg(procmacro2_semver_exempt)]
Alex Crichton1eb96a02018-04-04 13:07:35 -0700812fn spanned<'a, T>(
813 input: Cursor<'a>,
814 f: fn(Cursor<'a>) -> PResult<'a, T>,
815) -> PResult<'a, (T, ::Span)> {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500816 let input = skip_whitespace(input);
817 let lo = input.off;
Alex Crichton1eb96a02018-04-04 13:07:35 -0700818 let (a, b) = f(input)?;
819 let hi = a.off;
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700820 let span = ::Span::_new_stable(Span { lo: lo, hi: hi });
Alex Crichton1eb96a02018-04-04 13:07:35 -0700821 Ok((a, (b, span)))
822}
823
824fn token_tree(input: Cursor) -> PResult<TokenTree> {
825 let (rest, (mut tt, span)) = spanned(input, token_kind)?;
826 tt.set_span(span);
827 Ok((rest, tt))
Nika Layzellf8d5f212017-12-11 14:07:02 -0500828}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700829
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700830named!(token_kind -> TokenTree, alt!(
David Tolnayf14813f2018-09-08 17:14:07 -0700831 map!(group, |g| TokenTree::Group(::Group::_new_stable(g)))
Alex Crichton44bffbc2017-05-19 17:51:59 -0700832 |
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700833 map!(literal, |l| TokenTree::Literal(::Literal::_new_stable(l))) // must be before symbol
Alex Crichton44bffbc2017-05-19 17:51:59 -0700834 |
Alex Crichtonf3888432018-05-16 09:11:05 -0700835 map!(op, TokenTree::Punct)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700836 |
Alex Crichtonf3888432018-05-16 09:11:05 -0700837 symbol_leading_ws
Alex Crichton44bffbc2017-05-19 17:51:59 -0700838));
839
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700840named!(group -> Group, alt!(
Alex Crichton44bffbc2017-05-19 17:51:59 -0700841 delimited!(
842 punct!("("),
843 token_stream,
844 punct!(")")
David Tolnayf14813f2018-09-08 17:14:07 -0700845 ) => { |ts| Group::new(Delimiter::Parenthesis, ts) }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700846 |
847 delimited!(
848 punct!("["),
849 token_stream,
850 punct!("]")
David Tolnayf14813f2018-09-08 17:14:07 -0700851 ) => { |ts| Group::new(Delimiter::Bracket, ts) }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700852 |
853 delimited!(
854 punct!("{"),
855 token_stream,
856 punct!("}")
David Tolnayf14813f2018-09-08 17:14:07 -0700857 ) => { |ts| Group::new(Delimiter::Brace, ts) }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700858));
859
Alex Crichtonf3888432018-05-16 09:11:05 -0700860fn symbol_leading_ws(input: Cursor) -> PResult<TokenTree> {
861 symbol(skip_whitespace(input))
862}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700863
Alex Crichtonf3888432018-05-16 09:11:05 -0700864fn symbol(input: Cursor) -> PResult<TokenTree> {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700865 let mut chars = input.char_indices();
David Tolnaya202d502017-06-01 12:26:55 -0700866
Alex Crichtonf3888432018-05-16 09:11:05 -0700867 let raw = input.starts_with("r#");
David Tolnaya13d1422018-03-31 21:27:48 +0200868 if raw {
869 chars.next();
870 chars.next();
871 }
872
Alex Crichton44bffbc2017-05-19 17:51:59 -0700873 match chars.next() {
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000874 Some((_, ch)) if is_ident_start(ch) => {}
David Tolnay1218e122017-06-01 11:13:45 -0700875 _ => return Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -0700876 }
877
David Tolnay214c94c2017-06-01 12:42:56 -0700878 let mut end = input.len();
Alex Crichton44bffbc2017-05-19 17:51:59 -0700879 for (i, ch) in chars {
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000880 if !is_ident_continue(ch) {
David Tolnay214c94c2017-06-01 12:42:56 -0700881 end = i;
882 break;
Alex Crichton44bffbc2017-05-19 17:51:59 -0700883 }
884 }
885
David Tolnaya13d1422018-03-31 21:27:48 +0200886 let a = &input.rest[..end];
Alex Crichtonf3888432018-05-16 09:11:05 -0700887 if a == "r#_" {
David Tolnay214c94c2017-06-01 12:42:56 -0700888 Err(LexError)
889 } else {
Alex Crichtonf3888432018-05-16 09:11:05 -0700890 let ident = if raw {
891 ::Ident::_new_raw(&a[2..], ::Span::call_site())
892 } else {
893 ::Ident::new(a, ::Span::call_site())
894 };
895 Ok((input.advance(end), ident.into()))
David Tolnay214c94c2017-06-01 12:42:56 -0700896 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700897}
898
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700899fn literal(input: Cursor) -> PResult<Literal> {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700900 let input_no_ws = skip_whitespace(input);
901
902 match literal_nocapture(input_no_ws) {
David Tolnay1218e122017-06-01 11:13:45 -0700903 Ok((a, ())) => {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700904 let start = input.len() - input_no_ws.len();
905 let len = input_no_ws.len() - a.len();
906 let end = start + len;
David Tolnay3d9d6ad2018-05-18 10:51:55 -0700907 Ok((a, Literal::_new(input.rest[start..end].to_string())))
Alex Crichton44bffbc2017-05-19 17:51:59 -0700908 }
David Tolnay1218e122017-06-01 11:13:45 -0700909 Err(LexError) => Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -0700910 }
911}
912
913named!(literal_nocapture -> (), alt!(
914 string
915 |
916 byte_string
917 |
918 byte
919 |
920 character
921 |
922 float
923 |
924 int
Alex Crichton44bffbc2017-05-19 17:51:59 -0700925));
926
927named!(string -> (), alt!(
928 quoted_string
929 |
930 preceded!(
931 punct!("r"),
932 raw_string
933 ) => { |_| () }
934));
935
936named!(quoted_string -> (), delimited!(
937 punct!("\""),
938 cooked_string,
939 tag!("\"")
940));
941
Nika Layzellf8d5f212017-12-11 14:07:02 -0500942fn cooked_string(input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700943 let mut chars = input.char_indices().peekable();
944 while let Some((byte_offset, ch)) = chars.next() {
945 match ch {
946 '"' => {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500947 return Ok((input.advance(byte_offset), ()));
Alex Crichton44bffbc2017-05-19 17:51:59 -0700948 }
949 '\r' => {
950 if let Some((_, '\n')) = chars.next() {
951 // ...
952 } else {
953 break;
954 }
955 }
David Tolnayb28f38a2018-03-31 22:02:29 +0200956 '\\' => match chars.next() {
957 Some((_, 'x')) => {
958 if !backslash_x_char(&mut chars) {
959 break;
Alex Crichton44bffbc2017-05-19 17:51:59 -0700960 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700961 }
David Tolnayb28f38a2018-03-31 22:02:29 +0200962 Some((_, 'n')) | Some((_, 'r')) | Some((_, 't')) | Some((_, '\\'))
963 | Some((_, '\'')) | Some((_, '"')) | Some((_, '0')) => {}
964 Some((_, 'u')) => {
965 if !backslash_u(&mut chars) {
966 break;
967 }
968 }
969 Some((_, '\n')) | Some((_, '\r')) => {
970 while let Some(&(_, ch)) = chars.peek() {
971 if ch.is_whitespace() {
972 chars.next();
973 } else {
974 break;
975 }
976 }
977 }
978 _ => break,
979 },
Alex Crichton44bffbc2017-05-19 17:51:59 -0700980 _ch => {}
981 }
982 }
David Tolnay1218e122017-06-01 11:13:45 -0700983 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700984}
985
986named!(byte_string -> (), alt!(
987 delimited!(
988 punct!("b\""),
989 cooked_byte_string,
990 tag!("\"")
991 ) => { |_| () }
992 |
993 preceded!(
994 punct!("br"),
995 raw_string
996 ) => { |_| () }
997));
998
Nika Layzellf8d5f212017-12-11 14:07:02 -0500999fn cooked_byte_string(mut input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001000 let mut bytes = input.bytes().enumerate();
1001 'outer: while let Some((offset, b)) = bytes.next() {
1002 match b {
1003 b'"' => {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001004 return Ok((input.advance(offset), ()));
Alex Crichton44bffbc2017-05-19 17:51:59 -07001005 }
1006 b'\r' => {
1007 if let Some((_, b'\n')) = bytes.next() {
1008 // ...
1009 } else {
1010 break;
1011 }
1012 }
David Tolnayb28f38a2018-03-31 22:02:29 +02001013 b'\\' => match bytes.next() {
1014 Some((_, b'x')) => {
1015 if !backslash_x_byte(&mut bytes) {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001016 break;
1017 }
Alex Crichton44bffbc2017-05-19 17:51:59 -07001018 }
David Tolnayb28f38a2018-03-31 22:02:29 +02001019 Some((_, b'n')) | Some((_, b'r')) | Some((_, b't')) | Some((_, b'\\'))
1020 | Some((_, b'0')) | Some((_, b'\'')) | Some((_, b'"')) => {}
1021 Some((newline, b'\n')) | Some((newline, b'\r')) => {
1022 let rest = input.advance(newline + 1);
1023 for (offset, ch) in rest.char_indices() {
1024 if !ch.is_whitespace() {
1025 input = rest.advance(offset);
1026 bytes = input.bytes().enumerate();
1027 continue 'outer;
1028 }
1029 }
1030 break;
1031 }
1032 _ => break,
1033 },
Alex Crichton44bffbc2017-05-19 17:51:59 -07001034 b if b < 0x80 => {}
1035 _ => break,
1036 }
1037 }
David Tolnay1218e122017-06-01 11:13:45 -07001038 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001039}
1040
Nika Layzellf8d5f212017-12-11 14:07:02 -05001041fn raw_string(input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001042 let mut chars = input.char_indices();
1043 let mut n = 0;
1044 while let Some((byte_offset, ch)) = chars.next() {
1045 match ch {
1046 '"' => {
1047 n = byte_offset;
1048 break;
1049 }
1050 '#' => {}
David Tolnay1218e122017-06-01 11:13:45 -07001051 _ => return Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -07001052 }
1053 }
1054 for (byte_offset, ch) in chars {
1055 match ch {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001056 '"' if input.advance(byte_offset + 1).starts_with(&input.rest[..n]) => {
1057 let rest = input.advance(byte_offset + 1 + n);
David Tolnayb28f38a2018-03-31 22:02:29 +02001058 return Ok((rest, ()));
Alex Crichton44bffbc2017-05-19 17:51:59 -07001059 }
1060 '\r' => {}
1061 _ => {}
1062 }
1063 }
David Tolnay1218e122017-06-01 11:13:45 -07001064 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001065}
1066
1067named!(byte -> (), do_parse!(
1068 punct!("b") >>
1069 tag!("'") >>
1070 cooked_byte >>
1071 tag!("'") >>
1072 (())
1073));
1074
Nika Layzellf8d5f212017-12-11 14:07:02 -05001075fn cooked_byte(input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001076 let mut bytes = input.bytes().enumerate();
1077 let ok = match bytes.next().map(|(_, b)| b) {
David Tolnayb28f38a2018-03-31 22:02:29 +02001078 Some(b'\\') => match bytes.next().map(|(_, b)| b) {
1079 Some(b'x') => backslash_x_byte(&mut bytes),
1080 Some(b'n') | Some(b'r') | Some(b't') | Some(b'\\') | Some(b'0') | Some(b'\'')
1081 | Some(b'"') => true,
1082 _ => false,
1083 },
Alex Crichton44bffbc2017-05-19 17:51:59 -07001084 b => b.is_some(),
1085 };
1086 if ok {
1087 match bytes.next() {
Alex Crichton8c030332018-01-16 08:07:36 -08001088 Some((offset, _)) => {
1089 if input.chars().as_str().is_char_boundary(offset) {
1090 Ok((input.advance(offset), ()))
1091 } else {
1092 Err(LexError)
1093 }
1094 }
Nika Layzellf8d5f212017-12-11 14:07:02 -05001095 None => Ok((input.advance(input.len()), ())),
Alex Crichton44bffbc2017-05-19 17:51:59 -07001096 }
1097 } else {
David Tolnay1218e122017-06-01 11:13:45 -07001098 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001099 }
1100}
1101
1102named!(character -> (), do_parse!(
1103 punct!("'") >>
1104 cooked_char >>
1105 tag!("'") >>
1106 (())
1107));
1108
Nika Layzellf8d5f212017-12-11 14:07:02 -05001109fn cooked_char(input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001110 let mut chars = input.char_indices();
1111 let ok = match chars.next().map(|(_, ch)| ch) {
David Tolnayb28f38a2018-03-31 22:02:29 +02001112 Some('\\') => match chars.next().map(|(_, ch)| ch) {
1113 Some('x') => backslash_x_char(&mut chars),
1114 Some('u') => backslash_u(&mut chars),
1115 Some('n') | Some('r') | Some('t') | Some('\\') | Some('0') | Some('\'') | Some('"') => {
1116 true
Alex Crichton44bffbc2017-05-19 17:51:59 -07001117 }
David Tolnayb28f38a2018-03-31 22:02:29 +02001118 _ => false,
1119 },
Alex Crichton44bffbc2017-05-19 17:51:59 -07001120 ch => ch.is_some(),
1121 };
1122 if ok {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001123 match chars.next() {
1124 Some((idx, _)) => Ok((input.advance(idx), ())),
1125 None => Ok((input.advance(input.len()), ())),
1126 }
Alex Crichton44bffbc2017-05-19 17:51:59 -07001127 } else {
David Tolnay1218e122017-06-01 11:13:45 -07001128 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001129 }
1130}
1131
1132macro_rules! next_ch {
1133 ($chars:ident @ $pat:pat $(| $rest:pat)*) => {
1134 match $chars.next() {
1135 Some((_, ch)) => match ch {
1136 $pat $(| $rest)* => ch,
1137 _ => return false,
1138 },
1139 None => return false
1140 }
1141 };
1142}
1143
1144fn backslash_x_char<I>(chars: &mut I) -> bool
David Tolnayb28f38a2018-03-31 22:02:29 +02001145where
1146 I: Iterator<Item = (usize, char)>,
Alex Crichton44bffbc2017-05-19 17:51:59 -07001147{
1148 next_ch!(chars @ '0'...'7');
1149 next_ch!(chars @ '0'...'9' | 'a'...'f' | 'A'...'F');
1150 true
1151}
1152
1153fn backslash_x_byte<I>(chars: &mut I) -> bool
David Tolnayb28f38a2018-03-31 22:02:29 +02001154where
1155 I: Iterator<Item = (usize, u8)>,
Alex Crichton44bffbc2017-05-19 17:51:59 -07001156{
1157 next_ch!(chars @ b'0'...b'9' | b'a'...b'f' | b'A'...b'F');
1158 next_ch!(chars @ b'0'...b'9' | b'a'...b'f' | b'A'...b'F');
1159 true
1160}
1161
1162fn backslash_u<I>(chars: &mut I) -> bool
David Tolnayb28f38a2018-03-31 22:02:29 +02001163where
1164 I: Iterator<Item = (usize, char)>,
Alex Crichton44bffbc2017-05-19 17:51:59 -07001165{
1166 next_ch!(chars @ '{');
1167 next_ch!(chars @ '0'...'9' | 'a'...'f' | 'A'...'F');
David Tolnay8d109342017-12-25 18:24:45 -05001168 loop {
1169 let c = next_ch!(chars @ '0'...'9' | 'a'...'f' | 'A'...'F' | '_' | '}');
1170 if c == '}' {
1171 return true;
1172 }
Alex Crichton44bffbc2017-05-19 17:51:59 -07001173 }
Alex Crichton44bffbc2017-05-19 17:51:59 -07001174}
1175
Nika Layzellf8d5f212017-12-11 14:07:02 -05001176fn float(input: Cursor) -> PResult<()> {
David Tolnay744a6b82017-06-01 11:34:29 -07001177 let (rest, ()) = float_digits(input)?;
1178 for suffix in &["f32", "f64"] {
1179 if rest.starts_with(suffix) {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001180 return word_break(rest.advance(suffix.len()));
David Tolnay744a6b82017-06-01 11:34:29 -07001181 }
1182 }
1183 word_break(rest)
1184}
Alex Crichton44bffbc2017-05-19 17:51:59 -07001185
Nika Layzellf8d5f212017-12-11 14:07:02 -05001186fn float_digits(input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001187 let mut chars = input.chars().peekable();
1188 match chars.next() {
1189 Some(ch) if ch >= '0' && ch <= '9' => {}
David Tolnay1218e122017-06-01 11:13:45 -07001190 _ => return Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -07001191 }
1192
1193 let mut len = 1;
1194 let mut has_dot = false;
1195 let mut has_exp = false;
1196 while let Some(&ch) = chars.peek() {
1197 match ch {
1198 '0'...'9' | '_' => {
1199 chars.next();
1200 len += 1;
1201 }
1202 '.' => {
1203 if has_dot {
1204 break;
1205 }
1206 chars.next();
David Tolnayb28f38a2018-03-31 22:02:29 +02001207 if chars
1208 .peek()
1209 .map(|&ch| ch == '.' || UnicodeXID::is_xid_start(ch))
1210 .unwrap_or(false)
1211 {
David Tolnay1218e122017-06-01 11:13:45 -07001212 return Err(LexError);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001213 }
1214 len += 1;
1215 has_dot = true;
1216 }
1217 'e' | 'E' => {
1218 chars.next();
1219 len += 1;
1220 has_exp = true;
1221 break;
1222 }
1223 _ => break,
1224 }
1225 }
1226
Nika Layzellf8d5f212017-12-11 14:07:02 -05001227 let rest = input.advance(len);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001228 if !(has_dot || has_exp || rest.starts_with("f32") || rest.starts_with("f64")) {
David Tolnay1218e122017-06-01 11:13:45 -07001229 return Err(LexError);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001230 }
1231
1232 if has_exp {
1233 let mut has_exp_value = false;
1234 while let Some(&ch) = chars.peek() {
1235 match ch {
1236 '+' | '-' => {
1237 if has_exp_value {
1238 break;
1239 }
1240 chars.next();
1241 len += 1;
1242 }
1243 '0'...'9' => {
1244 chars.next();
1245 len += 1;
1246 has_exp_value = true;
1247 }
1248 '_' => {
1249 chars.next();
1250 len += 1;
1251 }
1252 _ => break,
1253 }
1254 }
1255 if !has_exp_value {
David Tolnay1218e122017-06-01 11:13:45 -07001256 return Err(LexError);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001257 }
1258 }
1259
Nika Layzellf8d5f212017-12-11 14:07:02 -05001260 Ok((input.advance(len), ()))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001261}
1262
Nika Layzellf8d5f212017-12-11 14:07:02 -05001263fn int(input: Cursor) -> PResult<()> {
David Tolnay744a6b82017-06-01 11:34:29 -07001264 let (rest, ()) = digits(input)?;
1265 for suffix in &[
David Tolnay48ea5042018-04-23 19:17:35 -07001266 "isize", "i8", "i16", "i32", "i64", "i128", "usize", "u8", "u16", "u32", "u64", "u128",
David Tolnay744a6b82017-06-01 11:34:29 -07001267 ] {
1268 if rest.starts_with(suffix) {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001269 return word_break(rest.advance(suffix.len()));
David Tolnay744a6b82017-06-01 11:34:29 -07001270 }
1271 }
1272 word_break(rest)
1273}
Alex Crichton44bffbc2017-05-19 17:51:59 -07001274
Nika Layzellf8d5f212017-12-11 14:07:02 -05001275fn digits(mut input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001276 let base = if input.starts_with("0x") {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001277 input = input.advance(2);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001278 16
1279 } else if input.starts_with("0o") {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001280 input = input.advance(2);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001281 8
1282 } else if input.starts_with("0b") {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001283 input = input.advance(2);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001284 2
1285 } else {
1286 10
1287 };
1288
Alex Crichton44bffbc2017-05-19 17:51:59 -07001289 let mut len = 0;
1290 let mut empty = true;
1291 for b in input.bytes() {
1292 let digit = match b {
1293 b'0'...b'9' => (b - b'0') as u64,
1294 b'a'...b'f' => 10 + (b - b'a') as u64,
1295 b'A'...b'F' => 10 + (b - b'A') as u64,
1296 b'_' => {
1297 if empty && base == 10 {
David Tolnay1218e122017-06-01 11:13:45 -07001298 return Err(LexError);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001299 }
1300 len += 1;
1301 continue;
1302 }
1303 _ => break,
1304 };
1305 if digit >= base {
David Tolnay1218e122017-06-01 11:13:45 -07001306 return Err(LexError);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001307 }
Alex Crichton44bffbc2017-05-19 17:51:59 -07001308 len += 1;
1309 empty = false;
1310 }
1311 if empty {
David Tolnay1218e122017-06-01 11:13:45 -07001312 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001313 } else {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001314 Ok((input.advance(len), ()))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001315 }
1316}
1317
Alex Crichtonf3888432018-05-16 09:11:05 -07001318fn op(input: Cursor) -> PResult<Punct> {
David Tolnayea75c5f2017-05-31 23:40:33 -07001319 let input = skip_whitespace(input);
1320 match op_char(input) {
Alex Crichtonf3888432018-05-16 09:11:05 -07001321 Ok((rest, '\'')) => {
1322 symbol(rest)?;
1323 Ok((rest, Punct::new('\'', Spacing::Joint)))
1324 }
David Tolnay1218e122017-06-01 11:13:45 -07001325 Ok((rest, ch)) => {
David Tolnayea75c5f2017-05-31 23:40:33 -07001326 let kind = match op_char(rest) {
Alex Crichton1a7f7622017-07-05 17:47:15 -07001327 Ok(_) => Spacing::Joint,
1328 Err(LexError) => Spacing::Alone,
David Tolnayea75c5f2017-05-31 23:40:33 -07001329 };
Alex Crichtonf3888432018-05-16 09:11:05 -07001330 Ok((rest, Punct::new(ch, kind)))
David Tolnayea75c5f2017-05-31 23:40:33 -07001331 }
David Tolnay1218e122017-06-01 11:13:45 -07001332 Err(LexError) => Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -07001333 }
1334}
1335
Nika Layzellf8d5f212017-12-11 14:07:02 -05001336fn op_char(input: Cursor) -> PResult<char> {
David Tolnay3a592ad2018-04-22 21:20:24 -07001337 if input.starts_with("//") || input.starts_with("/*") {
1338 // Do not accept `/` of a comment as an op.
1339 return Err(LexError);
1340 }
1341
David Tolnayea75c5f2017-05-31 23:40:33 -07001342 let mut chars = input.chars();
1343 let first = match chars.next() {
1344 Some(ch) => ch,
1345 None => {
David Tolnay1218e122017-06-01 11:13:45 -07001346 return Err(LexError);
David Tolnayea75c5f2017-05-31 23:40:33 -07001347 }
1348 };
Alex Crichtonf3888432018-05-16 09:11:05 -07001349 let recognized = "~!@#$%^&*-=+|;:,<.>/?'";
David Tolnayea75c5f2017-05-31 23:40:33 -07001350 if recognized.contains(first) {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001351 Ok((input.advance(first.len_utf8()), first))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001352 } else {
David Tolnay1218e122017-06-01 11:13:45 -07001353 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001354 }
1355}
1356
Alex Crichton1eb96a02018-04-04 13:07:35 -07001357fn doc_comment(input: Cursor) -> PResult<Vec<TokenTree>> {
1358 let mut trees = Vec::new();
1359 let (rest, ((comment, inner), span)) = spanned(input, doc_comment_contents)?;
Alex Crichtonf3888432018-05-16 09:11:05 -07001360 trees.push(TokenTree::Punct(Punct::new('#', Spacing::Alone)));
Alex Crichton1eb96a02018-04-04 13:07:35 -07001361 if inner {
Alex Crichtonf3888432018-05-16 09:11:05 -07001362 trees.push(Punct::new('!', Spacing::Alone).into());
Alex Crichton1eb96a02018-04-04 13:07:35 -07001363 }
1364 let mut stream = vec![
Alex Crichtonf3888432018-05-16 09:11:05 -07001365 TokenTree::Ident(::Ident::new("doc", span)),
1366 TokenTree::Punct(Punct::new('=', Spacing::Alone)),
Alex Crichton1eb96a02018-04-04 13:07:35 -07001367 TokenTree::Literal(::Literal::string(comment)),
1368 ];
1369 for tt in stream.iter_mut() {
1370 tt.set_span(span);
1371 }
David Tolnayf14813f2018-09-08 17:14:07 -07001372 let group = Group::new(Delimiter::Bracket, stream.into_iter().collect());
1373 trees.push(::Group::_new_stable(group).into());
Alex Crichton1eb96a02018-04-04 13:07:35 -07001374 for tt in trees.iter_mut() {
1375 tt.set_span(span);
1376 }
1377 Ok((rest, trees))
1378}
1379
1380named!(doc_comment_contents -> (&str, bool), alt!(
Alex Crichton44bffbc2017-05-19 17:51:59 -07001381 do_parse!(
1382 punct!("//!") >>
Alex Crichton1eb96a02018-04-04 13:07:35 -07001383 s: take_until_newline_or_eof!() >>
1384 ((s, true))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001385 )
1386 |
1387 do_parse!(
1388 option!(whitespace) >>
1389 peek!(tag!("/*!")) >>
Alex Crichton1eb96a02018-04-04 13:07:35 -07001390 s: block_comment >>
1391 ((s, true))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001392 )
1393 |
1394 do_parse!(
1395 punct!("///") >>
1396 not!(tag!("/")) >>
Alex Crichton1eb96a02018-04-04 13:07:35 -07001397 s: take_until_newline_or_eof!() >>
1398 ((s, false))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001399 )
1400 |
1401 do_parse!(
1402 option!(whitespace) >>
1403 peek!(tuple!(tag!("/**"), not!(tag!("*")))) >>
Alex Crichton1eb96a02018-04-04 13:07:35 -07001404 s: block_comment >>
1405 ((s, false))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001406 )
1407));