blob: 6c06fc49cd3e543f7aae4fc6aaaf2bcd2d62d42a [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
681 unsuffixed_numbers! {
682 u8_unsuffixed => u8,
683 u16_unsuffixed => u16,
684 u32_unsuffixed => u32,
685 u64_unsuffixed => u64,
686 usize_unsuffixed => usize,
687 i8_unsuffixed => i8,
688 i16_unsuffixed => i16,
689 i32_unsuffixed => i32,
690 i64_unsuffixed => i64,
691 isize_unsuffixed => isize,
692 }
693
694 pub fn f32_unsuffixed(f: f32) -> Literal {
695 let mut s = f.to_string();
696 if !s.contains(".") {
697 s.push_str(".0");
Alex Crichton76a5cc82017-05-23 07:01:44 -0700698 }
Alex Crichtona914a612018-04-04 07:48:44 -0700699 Literal::_new(s)
700 }
701
702 pub fn f64_unsuffixed(f: f64) -> Literal {
703 let mut s = f.to_string();
704 if !s.contains(".") {
705 s.push_str(".0");
706 }
707 Literal::_new(s)
708 }
709
710 pub fn string(t: &str) -> Literal {
David Tolnay3d9d6ad2018-05-18 10:51:55 -0700711 let mut s = t
712 .chars()
Alex Crichtona914a612018-04-04 07:48:44 -0700713 .flat_map(|c| c.escape_default())
714 .collect::<String>();
715 s.push('"');
716 s.insert(0, '"');
717 Literal::_new(s)
718 }
719
720 pub fn character(t: char) -> Literal {
721 Literal::_new(format!("'{}'", t.escape_default().collect::<String>()))
Alex Crichton76a5cc82017-05-23 07:01:44 -0700722 }
723
Alex Crichton9c2fb0a2017-05-26 08:49:31 -0700724 pub fn byte_string(bytes: &[u8]) -> Literal {
Alex Crichton852d53d2017-05-19 19:25:08 -0700725 let mut escaped = "b\"".to_string();
726 for b in bytes {
727 match *b {
728 b'\0' => escaped.push_str(r"\0"),
729 b'\t' => escaped.push_str(r"\t"),
730 b'\n' => escaped.push_str(r"\n"),
731 b'\r' => escaped.push_str(r"\r"),
732 b'"' => escaped.push_str("\\\""),
733 b'\\' => escaped.push_str("\\\\"),
David Tolnayb28f38a2018-03-31 22:02:29 +0200734 b'\x20'...b'\x7E' => escaped.push(*b as char),
Alex Crichton852d53d2017-05-19 19:25:08 -0700735 _ => escaped.push_str(&format!("\\x{:02X}", b)),
736 }
737 }
738 escaped.push('"');
Alex Crichtonb2c94622018-04-04 07:36:41 -0700739 Literal::_new(escaped)
Alex Crichton76a5cc82017-05-23 07:01:44 -0700740 }
Alex Crichton9c2fb0a2017-05-26 08:49:31 -0700741
Alex Crichtonb2c94622018-04-04 07:36:41 -0700742 pub fn span(&self) -> Span {
743 self.span
Alex Crichton31316622017-05-26 12:54:47 -0700744 }
745
Alex Crichtonb2c94622018-04-04 07:36:41 -0700746 pub fn set_span(&mut self, span: Span) {
747 self.span = span;
Alex Crichton31316622017-05-26 12:54:47 -0700748 }
Alex Crichton852d53d2017-05-19 19:25:08 -0700749}
750
Alex Crichton44bffbc2017-05-19 17:51:59 -0700751impl fmt::Display for Literal {
752 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Alex Crichtonb2c94622018-04-04 07:36:41 -0700753 self.text.fmt(f)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700754 }
755}
756
David Tolnay034205f2018-04-22 16:45:28 -0700757impl fmt::Debug for Literal {
758 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
759 let mut debug = fmt.debug_struct("Literal");
760 debug.field("lit", &format_args!("{}", self.text));
761 #[cfg(procmacro2_semver_exempt)]
762 debug.field("span", &self.span);
763 debug.finish()
764 }
765}
766
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700767fn token_stream(mut input: Cursor) -> PResult<TokenStream> {
Alex Crichton1eb96a02018-04-04 13:07:35 -0700768 let mut trees = Vec::new();
769 loop {
770 let input_no_ws = skip_whitespace(input);
771 if input_no_ws.rest.len() == 0 {
David Tolnay48ea5042018-04-23 19:17:35 -0700772 break;
Alex Crichton1eb96a02018-04-04 13:07:35 -0700773 }
774 if let Ok((a, tokens)) = doc_comment(input_no_ws) {
775 input = a;
776 trees.extend(tokens);
David Tolnay48ea5042018-04-23 19:17:35 -0700777 continue;
Alex Crichton1eb96a02018-04-04 13:07:35 -0700778 }
779
780 let (a, tt) = match token_tree(input_no_ws) {
781 Ok(p) => p,
782 Err(_) => break,
783 };
784 trees.push(tt);
785 input = a;
786 }
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700787 Ok((input, TokenStream { inner: trees }))
Alex Crichton1eb96a02018-04-04 13:07:35 -0700788}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700789
David Tolnay1ebe3972018-01-02 20:14:20 -0800790#[cfg(not(procmacro2_semver_exempt))]
Alex Crichton1eb96a02018-04-04 13:07:35 -0700791fn spanned<'a, T>(
792 input: Cursor<'a>,
793 f: fn(Cursor<'a>) -> PResult<'a, T>,
794) -> PResult<'a, (T, ::Span)> {
795 let (a, b) = f(skip_whitespace(input))?;
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700796 Ok((a, ((b, ::Span::_new_stable(Span {})))))
David Tolnayddfca052017-12-31 10:41:24 -0500797}
798
David Tolnay1ebe3972018-01-02 20:14:20 -0800799#[cfg(procmacro2_semver_exempt)]
Alex Crichton1eb96a02018-04-04 13:07:35 -0700800fn spanned<'a, T>(
801 input: Cursor<'a>,
802 f: fn(Cursor<'a>) -> PResult<'a, T>,
803) -> PResult<'a, (T, ::Span)> {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500804 let input = skip_whitespace(input);
805 let lo = input.off;
Alex Crichton1eb96a02018-04-04 13:07:35 -0700806 let (a, b) = f(input)?;
807 let hi = a.off;
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700808 let span = ::Span::_new_stable(Span { lo: lo, hi: hi });
Alex Crichton1eb96a02018-04-04 13:07:35 -0700809 Ok((a, (b, span)))
810}
811
812fn token_tree(input: Cursor) -> PResult<TokenTree> {
813 let (rest, (mut tt, span)) = spanned(input, token_kind)?;
814 tt.set_span(span);
815 Ok((rest, tt))
Nika Layzellf8d5f212017-12-11 14:07:02 -0500816}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700817
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700818named!(token_kind -> TokenTree, alt!(
David Tolnayf14813f2018-09-08 17:14:07 -0700819 map!(group, |g| TokenTree::Group(::Group::_new_stable(g)))
Alex Crichton44bffbc2017-05-19 17:51:59 -0700820 |
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700821 map!(literal, |l| TokenTree::Literal(::Literal::_new_stable(l))) // must be before symbol
Alex Crichton44bffbc2017-05-19 17:51:59 -0700822 |
Alex Crichtonf3888432018-05-16 09:11:05 -0700823 map!(op, TokenTree::Punct)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700824 |
Alex Crichtonf3888432018-05-16 09:11:05 -0700825 symbol_leading_ws
Alex Crichton44bffbc2017-05-19 17:51:59 -0700826));
827
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700828named!(group -> Group, alt!(
Alex Crichton44bffbc2017-05-19 17:51:59 -0700829 delimited!(
830 punct!("("),
831 token_stream,
832 punct!(")")
David Tolnayf14813f2018-09-08 17:14:07 -0700833 ) => { |ts| Group::new(Delimiter::Parenthesis, ts) }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700834 |
835 delimited!(
836 punct!("["),
837 token_stream,
838 punct!("]")
David Tolnayf14813f2018-09-08 17:14:07 -0700839 ) => { |ts| Group::new(Delimiter::Bracket, ts) }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700840 |
841 delimited!(
842 punct!("{"),
843 token_stream,
844 punct!("}")
David Tolnayf14813f2018-09-08 17:14:07 -0700845 ) => { |ts| Group::new(Delimiter::Brace, ts) }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700846));
847
Alex Crichtonf3888432018-05-16 09:11:05 -0700848fn symbol_leading_ws(input: Cursor) -> PResult<TokenTree> {
849 symbol(skip_whitespace(input))
850}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700851
Alex Crichtonf3888432018-05-16 09:11:05 -0700852fn symbol(input: Cursor) -> PResult<TokenTree> {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700853 let mut chars = input.char_indices();
David Tolnaya202d502017-06-01 12:26:55 -0700854
Alex Crichtonf3888432018-05-16 09:11:05 -0700855 let raw = input.starts_with("r#");
David Tolnaya13d1422018-03-31 21:27:48 +0200856 if raw {
857 chars.next();
858 chars.next();
859 }
860
Alex Crichton44bffbc2017-05-19 17:51:59 -0700861 match chars.next() {
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000862 Some((_, ch)) if is_ident_start(ch) => {}
David Tolnay1218e122017-06-01 11:13:45 -0700863 _ => return Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -0700864 }
865
David Tolnay214c94c2017-06-01 12:42:56 -0700866 let mut end = input.len();
Alex Crichton44bffbc2017-05-19 17:51:59 -0700867 for (i, ch) in chars {
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000868 if !is_ident_continue(ch) {
David Tolnay214c94c2017-06-01 12:42:56 -0700869 end = i;
870 break;
Alex Crichton44bffbc2017-05-19 17:51:59 -0700871 }
872 }
873
David Tolnaya13d1422018-03-31 21:27:48 +0200874 let a = &input.rest[..end];
Alex Crichtonf3888432018-05-16 09:11:05 -0700875 if a == "r#_" {
David Tolnay214c94c2017-06-01 12:42:56 -0700876 Err(LexError)
877 } else {
Alex Crichtonf3888432018-05-16 09:11:05 -0700878 let ident = if raw {
879 ::Ident::_new_raw(&a[2..], ::Span::call_site())
880 } else {
881 ::Ident::new(a, ::Span::call_site())
882 };
883 Ok((input.advance(end), ident.into()))
David Tolnay214c94c2017-06-01 12:42:56 -0700884 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700885}
886
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700887fn literal(input: Cursor) -> PResult<Literal> {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700888 let input_no_ws = skip_whitespace(input);
889
890 match literal_nocapture(input_no_ws) {
David Tolnay1218e122017-06-01 11:13:45 -0700891 Ok((a, ())) => {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700892 let start = input.len() - input_no_ws.len();
893 let len = input_no_ws.len() - a.len();
894 let end = start + len;
David Tolnay3d9d6ad2018-05-18 10:51:55 -0700895 Ok((a, Literal::_new(input.rest[start..end].to_string())))
Alex Crichton44bffbc2017-05-19 17:51:59 -0700896 }
David Tolnay1218e122017-06-01 11:13:45 -0700897 Err(LexError) => Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -0700898 }
899}
900
901named!(literal_nocapture -> (), alt!(
902 string
903 |
904 byte_string
905 |
906 byte
907 |
908 character
909 |
910 float
911 |
912 int
Alex Crichton44bffbc2017-05-19 17:51:59 -0700913));
914
915named!(string -> (), alt!(
916 quoted_string
917 |
918 preceded!(
919 punct!("r"),
920 raw_string
921 ) => { |_| () }
922));
923
924named!(quoted_string -> (), delimited!(
925 punct!("\""),
926 cooked_string,
927 tag!("\"")
928));
929
Nika Layzellf8d5f212017-12-11 14:07:02 -0500930fn cooked_string(input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700931 let mut chars = input.char_indices().peekable();
932 while let Some((byte_offset, ch)) = chars.next() {
933 match ch {
934 '"' => {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500935 return Ok((input.advance(byte_offset), ()));
Alex Crichton44bffbc2017-05-19 17:51:59 -0700936 }
937 '\r' => {
938 if let Some((_, '\n')) = chars.next() {
939 // ...
940 } else {
941 break;
942 }
943 }
David Tolnayb28f38a2018-03-31 22:02:29 +0200944 '\\' => match chars.next() {
945 Some((_, 'x')) => {
946 if !backslash_x_char(&mut chars) {
947 break;
Alex Crichton44bffbc2017-05-19 17:51:59 -0700948 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700949 }
David Tolnayb28f38a2018-03-31 22:02:29 +0200950 Some((_, 'n')) | Some((_, 'r')) | Some((_, 't')) | Some((_, '\\'))
951 | Some((_, '\'')) | Some((_, '"')) | Some((_, '0')) => {}
952 Some((_, 'u')) => {
953 if !backslash_u(&mut chars) {
954 break;
955 }
956 }
957 Some((_, '\n')) | Some((_, '\r')) => {
958 while let Some(&(_, ch)) = chars.peek() {
959 if ch.is_whitespace() {
960 chars.next();
961 } else {
962 break;
963 }
964 }
965 }
966 _ => break,
967 },
Alex Crichton44bffbc2017-05-19 17:51:59 -0700968 _ch => {}
969 }
970 }
David Tolnay1218e122017-06-01 11:13:45 -0700971 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700972}
973
974named!(byte_string -> (), alt!(
975 delimited!(
976 punct!("b\""),
977 cooked_byte_string,
978 tag!("\"")
979 ) => { |_| () }
980 |
981 preceded!(
982 punct!("br"),
983 raw_string
984 ) => { |_| () }
985));
986
Nika Layzellf8d5f212017-12-11 14:07:02 -0500987fn cooked_byte_string(mut input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700988 let mut bytes = input.bytes().enumerate();
989 'outer: while let Some((offset, b)) = bytes.next() {
990 match b {
991 b'"' => {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500992 return Ok((input.advance(offset), ()));
Alex Crichton44bffbc2017-05-19 17:51:59 -0700993 }
994 b'\r' => {
995 if let Some((_, b'\n')) = bytes.next() {
996 // ...
997 } else {
998 break;
999 }
1000 }
David Tolnayb28f38a2018-03-31 22:02:29 +02001001 b'\\' => match bytes.next() {
1002 Some((_, b'x')) => {
1003 if !backslash_x_byte(&mut bytes) {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001004 break;
1005 }
Alex Crichton44bffbc2017-05-19 17:51:59 -07001006 }
David Tolnayb28f38a2018-03-31 22:02:29 +02001007 Some((_, b'n')) | Some((_, b'r')) | Some((_, b't')) | Some((_, b'\\'))
1008 | Some((_, b'0')) | Some((_, b'\'')) | Some((_, b'"')) => {}
1009 Some((newline, b'\n')) | Some((newline, b'\r')) => {
1010 let rest = input.advance(newline + 1);
1011 for (offset, ch) in rest.char_indices() {
1012 if !ch.is_whitespace() {
1013 input = rest.advance(offset);
1014 bytes = input.bytes().enumerate();
1015 continue 'outer;
1016 }
1017 }
1018 break;
1019 }
1020 _ => break,
1021 },
Alex Crichton44bffbc2017-05-19 17:51:59 -07001022 b if b < 0x80 => {}
1023 _ => break,
1024 }
1025 }
David Tolnay1218e122017-06-01 11:13:45 -07001026 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001027}
1028
Nika Layzellf8d5f212017-12-11 14:07:02 -05001029fn raw_string(input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001030 let mut chars = input.char_indices();
1031 let mut n = 0;
1032 while let Some((byte_offset, ch)) = chars.next() {
1033 match ch {
1034 '"' => {
1035 n = byte_offset;
1036 break;
1037 }
1038 '#' => {}
David Tolnay1218e122017-06-01 11:13:45 -07001039 _ => return Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -07001040 }
1041 }
1042 for (byte_offset, ch) in chars {
1043 match ch {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001044 '"' if input.advance(byte_offset + 1).starts_with(&input.rest[..n]) => {
1045 let rest = input.advance(byte_offset + 1 + n);
David Tolnayb28f38a2018-03-31 22:02:29 +02001046 return Ok((rest, ()));
Alex Crichton44bffbc2017-05-19 17:51:59 -07001047 }
1048 '\r' => {}
1049 _ => {}
1050 }
1051 }
David Tolnay1218e122017-06-01 11:13:45 -07001052 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001053}
1054
1055named!(byte -> (), do_parse!(
1056 punct!("b") >>
1057 tag!("'") >>
1058 cooked_byte >>
1059 tag!("'") >>
1060 (())
1061));
1062
Nika Layzellf8d5f212017-12-11 14:07:02 -05001063fn cooked_byte(input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001064 let mut bytes = input.bytes().enumerate();
1065 let ok = match bytes.next().map(|(_, b)| b) {
David Tolnayb28f38a2018-03-31 22:02:29 +02001066 Some(b'\\') => match bytes.next().map(|(_, b)| b) {
1067 Some(b'x') => backslash_x_byte(&mut bytes),
1068 Some(b'n') | Some(b'r') | Some(b't') | Some(b'\\') | Some(b'0') | Some(b'\'')
1069 | Some(b'"') => true,
1070 _ => false,
1071 },
Alex Crichton44bffbc2017-05-19 17:51:59 -07001072 b => b.is_some(),
1073 };
1074 if ok {
1075 match bytes.next() {
Alex Crichton8c030332018-01-16 08:07:36 -08001076 Some((offset, _)) => {
1077 if input.chars().as_str().is_char_boundary(offset) {
1078 Ok((input.advance(offset), ()))
1079 } else {
1080 Err(LexError)
1081 }
1082 }
Nika Layzellf8d5f212017-12-11 14:07:02 -05001083 None => Ok((input.advance(input.len()), ())),
Alex Crichton44bffbc2017-05-19 17:51:59 -07001084 }
1085 } else {
David Tolnay1218e122017-06-01 11:13:45 -07001086 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001087 }
1088}
1089
1090named!(character -> (), do_parse!(
1091 punct!("'") >>
1092 cooked_char >>
1093 tag!("'") >>
1094 (())
1095));
1096
Nika Layzellf8d5f212017-12-11 14:07:02 -05001097fn cooked_char(input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001098 let mut chars = input.char_indices();
1099 let ok = match chars.next().map(|(_, ch)| ch) {
David Tolnayb28f38a2018-03-31 22:02:29 +02001100 Some('\\') => match chars.next().map(|(_, ch)| ch) {
1101 Some('x') => backslash_x_char(&mut chars),
1102 Some('u') => backslash_u(&mut chars),
1103 Some('n') | Some('r') | Some('t') | Some('\\') | Some('0') | Some('\'') | Some('"') => {
1104 true
Alex Crichton44bffbc2017-05-19 17:51:59 -07001105 }
David Tolnayb28f38a2018-03-31 22:02:29 +02001106 _ => false,
1107 },
Alex Crichton44bffbc2017-05-19 17:51:59 -07001108 ch => ch.is_some(),
1109 };
1110 if ok {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001111 match chars.next() {
1112 Some((idx, _)) => Ok((input.advance(idx), ())),
1113 None => Ok((input.advance(input.len()), ())),
1114 }
Alex Crichton44bffbc2017-05-19 17:51:59 -07001115 } else {
David Tolnay1218e122017-06-01 11:13:45 -07001116 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001117 }
1118}
1119
1120macro_rules! next_ch {
1121 ($chars:ident @ $pat:pat $(| $rest:pat)*) => {
1122 match $chars.next() {
1123 Some((_, ch)) => match ch {
1124 $pat $(| $rest)* => ch,
1125 _ => return false,
1126 },
1127 None => return false
1128 }
1129 };
1130}
1131
1132fn backslash_x_char<I>(chars: &mut I) -> bool
David Tolnayb28f38a2018-03-31 22:02:29 +02001133where
1134 I: Iterator<Item = (usize, char)>,
Alex Crichton44bffbc2017-05-19 17:51:59 -07001135{
1136 next_ch!(chars @ '0'...'7');
1137 next_ch!(chars @ '0'...'9' | 'a'...'f' | 'A'...'F');
1138 true
1139}
1140
1141fn backslash_x_byte<I>(chars: &mut I) -> bool
David Tolnayb28f38a2018-03-31 22:02:29 +02001142where
1143 I: Iterator<Item = (usize, u8)>,
Alex Crichton44bffbc2017-05-19 17:51:59 -07001144{
1145 next_ch!(chars @ b'0'...b'9' | b'a'...b'f' | b'A'...b'F');
1146 next_ch!(chars @ b'0'...b'9' | b'a'...b'f' | b'A'...b'F');
1147 true
1148}
1149
1150fn backslash_u<I>(chars: &mut I) -> bool
David Tolnayb28f38a2018-03-31 22:02:29 +02001151where
1152 I: Iterator<Item = (usize, char)>,
Alex Crichton44bffbc2017-05-19 17:51:59 -07001153{
1154 next_ch!(chars @ '{');
1155 next_ch!(chars @ '0'...'9' | 'a'...'f' | 'A'...'F');
David Tolnay8d109342017-12-25 18:24:45 -05001156 loop {
1157 let c = next_ch!(chars @ '0'...'9' | 'a'...'f' | 'A'...'F' | '_' | '}');
1158 if c == '}' {
1159 return true;
1160 }
Alex Crichton44bffbc2017-05-19 17:51:59 -07001161 }
Alex Crichton44bffbc2017-05-19 17:51:59 -07001162}
1163
Nika Layzellf8d5f212017-12-11 14:07:02 -05001164fn float(input: Cursor) -> PResult<()> {
David Tolnay744a6b82017-06-01 11:34:29 -07001165 let (rest, ()) = float_digits(input)?;
1166 for suffix in &["f32", "f64"] {
1167 if rest.starts_with(suffix) {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001168 return word_break(rest.advance(suffix.len()));
David Tolnay744a6b82017-06-01 11:34:29 -07001169 }
1170 }
1171 word_break(rest)
1172}
Alex Crichton44bffbc2017-05-19 17:51:59 -07001173
Nika Layzellf8d5f212017-12-11 14:07:02 -05001174fn float_digits(input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001175 let mut chars = input.chars().peekable();
1176 match chars.next() {
1177 Some(ch) if ch >= '0' && ch <= '9' => {}
David Tolnay1218e122017-06-01 11:13:45 -07001178 _ => return Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -07001179 }
1180
1181 let mut len = 1;
1182 let mut has_dot = false;
1183 let mut has_exp = false;
1184 while let Some(&ch) = chars.peek() {
1185 match ch {
1186 '0'...'9' | '_' => {
1187 chars.next();
1188 len += 1;
1189 }
1190 '.' => {
1191 if has_dot {
1192 break;
1193 }
1194 chars.next();
David Tolnayb28f38a2018-03-31 22:02:29 +02001195 if chars
1196 .peek()
1197 .map(|&ch| ch == '.' || UnicodeXID::is_xid_start(ch))
1198 .unwrap_or(false)
1199 {
David Tolnay1218e122017-06-01 11:13:45 -07001200 return Err(LexError);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001201 }
1202 len += 1;
1203 has_dot = true;
1204 }
1205 'e' | 'E' => {
1206 chars.next();
1207 len += 1;
1208 has_exp = true;
1209 break;
1210 }
1211 _ => break,
1212 }
1213 }
1214
Nika Layzellf8d5f212017-12-11 14:07:02 -05001215 let rest = input.advance(len);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001216 if !(has_dot || has_exp || rest.starts_with("f32") || rest.starts_with("f64")) {
David Tolnay1218e122017-06-01 11:13:45 -07001217 return Err(LexError);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001218 }
1219
1220 if has_exp {
1221 let mut has_exp_value = false;
1222 while let Some(&ch) = chars.peek() {
1223 match ch {
1224 '+' | '-' => {
1225 if has_exp_value {
1226 break;
1227 }
1228 chars.next();
1229 len += 1;
1230 }
1231 '0'...'9' => {
1232 chars.next();
1233 len += 1;
1234 has_exp_value = true;
1235 }
1236 '_' => {
1237 chars.next();
1238 len += 1;
1239 }
1240 _ => break,
1241 }
1242 }
1243 if !has_exp_value {
David Tolnay1218e122017-06-01 11:13:45 -07001244 return Err(LexError);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001245 }
1246 }
1247
Nika Layzellf8d5f212017-12-11 14:07:02 -05001248 Ok((input.advance(len), ()))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001249}
1250
Nika Layzellf8d5f212017-12-11 14:07:02 -05001251fn int(input: Cursor) -> PResult<()> {
David Tolnay744a6b82017-06-01 11:34:29 -07001252 let (rest, ()) = digits(input)?;
1253 for suffix in &[
David Tolnay48ea5042018-04-23 19:17:35 -07001254 "isize", "i8", "i16", "i32", "i64", "i128", "usize", "u8", "u16", "u32", "u64", "u128",
David Tolnay744a6b82017-06-01 11:34:29 -07001255 ] {
1256 if rest.starts_with(suffix) {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001257 return word_break(rest.advance(suffix.len()));
David Tolnay744a6b82017-06-01 11:34:29 -07001258 }
1259 }
1260 word_break(rest)
1261}
Alex Crichton44bffbc2017-05-19 17:51:59 -07001262
Nika Layzellf8d5f212017-12-11 14:07:02 -05001263fn digits(mut input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001264 let base = if input.starts_with("0x") {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001265 input = input.advance(2);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001266 16
1267 } else if input.starts_with("0o") {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001268 input = input.advance(2);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001269 8
1270 } else if input.starts_with("0b") {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001271 input = input.advance(2);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001272 2
1273 } else {
1274 10
1275 };
1276
Alex Crichton44bffbc2017-05-19 17:51:59 -07001277 let mut len = 0;
1278 let mut empty = true;
1279 for b in input.bytes() {
1280 let digit = match b {
1281 b'0'...b'9' => (b - b'0') as u64,
1282 b'a'...b'f' => 10 + (b - b'a') as u64,
1283 b'A'...b'F' => 10 + (b - b'A') as u64,
1284 b'_' => {
1285 if empty && base == 10 {
David Tolnay1218e122017-06-01 11:13:45 -07001286 return Err(LexError);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001287 }
1288 len += 1;
1289 continue;
1290 }
1291 _ => break,
1292 };
1293 if digit >= base {
David Tolnay1218e122017-06-01 11:13:45 -07001294 return Err(LexError);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001295 }
Alex Crichton44bffbc2017-05-19 17:51:59 -07001296 len += 1;
1297 empty = false;
1298 }
1299 if empty {
David Tolnay1218e122017-06-01 11:13:45 -07001300 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001301 } else {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001302 Ok((input.advance(len), ()))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001303 }
1304}
1305
Alex Crichtonf3888432018-05-16 09:11:05 -07001306fn op(input: Cursor) -> PResult<Punct> {
David Tolnayea75c5f2017-05-31 23:40:33 -07001307 let input = skip_whitespace(input);
1308 match op_char(input) {
Alex Crichtonf3888432018-05-16 09:11:05 -07001309 Ok((rest, '\'')) => {
1310 symbol(rest)?;
1311 Ok((rest, Punct::new('\'', Spacing::Joint)))
1312 }
David Tolnay1218e122017-06-01 11:13:45 -07001313 Ok((rest, ch)) => {
David Tolnayea75c5f2017-05-31 23:40:33 -07001314 let kind = match op_char(rest) {
Alex Crichton1a7f7622017-07-05 17:47:15 -07001315 Ok(_) => Spacing::Joint,
1316 Err(LexError) => Spacing::Alone,
David Tolnayea75c5f2017-05-31 23:40:33 -07001317 };
Alex Crichtonf3888432018-05-16 09:11:05 -07001318 Ok((rest, Punct::new(ch, kind)))
David Tolnayea75c5f2017-05-31 23:40:33 -07001319 }
David Tolnay1218e122017-06-01 11:13:45 -07001320 Err(LexError) => Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -07001321 }
1322}
1323
Nika Layzellf8d5f212017-12-11 14:07:02 -05001324fn op_char(input: Cursor) -> PResult<char> {
David Tolnay3a592ad2018-04-22 21:20:24 -07001325 if input.starts_with("//") || input.starts_with("/*") {
1326 // Do not accept `/` of a comment as an op.
1327 return Err(LexError);
1328 }
1329
David Tolnayea75c5f2017-05-31 23:40:33 -07001330 let mut chars = input.chars();
1331 let first = match chars.next() {
1332 Some(ch) => ch,
1333 None => {
David Tolnay1218e122017-06-01 11:13:45 -07001334 return Err(LexError);
David Tolnayea75c5f2017-05-31 23:40:33 -07001335 }
1336 };
Alex Crichtonf3888432018-05-16 09:11:05 -07001337 let recognized = "~!@#$%^&*-=+|;:,<.>/?'";
David Tolnayea75c5f2017-05-31 23:40:33 -07001338 if recognized.contains(first) {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001339 Ok((input.advance(first.len_utf8()), first))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001340 } else {
David Tolnay1218e122017-06-01 11:13:45 -07001341 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001342 }
1343}
1344
Alex Crichton1eb96a02018-04-04 13:07:35 -07001345fn doc_comment(input: Cursor) -> PResult<Vec<TokenTree>> {
1346 let mut trees = Vec::new();
1347 let (rest, ((comment, inner), span)) = spanned(input, doc_comment_contents)?;
Alex Crichtonf3888432018-05-16 09:11:05 -07001348 trees.push(TokenTree::Punct(Punct::new('#', Spacing::Alone)));
Alex Crichton1eb96a02018-04-04 13:07:35 -07001349 if inner {
Alex Crichtonf3888432018-05-16 09:11:05 -07001350 trees.push(Punct::new('!', Spacing::Alone).into());
Alex Crichton1eb96a02018-04-04 13:07:35 -07001351 }
1352 let mut stream = vec![
Alex Crichtonf3888432018-05-16 09:11:05 -07001353 TokenTree::Ident(::Ident::new("doc", span)),
1354 TokenTree::Punct(Punct::new('=', Spacing::Alone)),
Alex Crichton1eb96a02018-04-04 13:07:35 -07001355 TokenTree::Literal(::Literal::string(comment)),
1356 ];
1357 for tt in stream.iter_mut() {
1358 tt.set_span(span);
1359 }
David Tolnayf14813f2018-09-08 17:14:07 -07001360 let group = Group::new(Delimiter::Bracket, stream.into_iter().collect());
1361 trees.push(::Group::_new_stable(group).into());
Alex Crichton1eb96a02018-04-04 13:07:35 -07001362 for tt in trees.iter_mut() {
1363 tt.set_span(span);
1364 }
1365 Ok((rest, trees))
1366}
1367
1368named!(doc_comment_contents -> (&str, bool), alt!(
Alex Crichton44bffbc2017-05-19 17:51:59 -07001369 do_parse!(
1370 punct!("//!") >>
Alex Crichton1eb96a02018-04-04 13:07:35 -07001371 s: take_until_newline_or_eof!() >>
1372 ((s, true))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001373 )
1374 |
1375 do_parse!(
1376 option!(whitespace) >>
1377 peek!(tag!("/*!")) >>
Alex Crichton1eb96a02018-04-04 13:07:35 -07001378 s: block_comment >>
1379 ((s, true))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001380 )
1381 |
1382 do_parse!(
1383 punct!("///") >>
1384 not!(tag!("/")) >>
Alex Crichton1eb96a02018-04-04 13:07:35 -07001385 s: take_until_newline_or_eof!() >>
1386 ((s, false))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001387 )
1388 |
1389 do_parse!(
1390 option!(whitespace) >>
1391 peek!(tuple!(tag!("/**"), not!(tag!("*")))) >>
Alex Crichton1eb96a02018-04-04 13:07:35 -07001392 s: block_comment >>
1393 ((s, false))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001394 )
1395));