blob: baeed69af6c8684a16da5dd0ccfc62f7e7ead5b6 [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;
David Tolnay9cd3b4c2018-11-11 16:47:32 -08009#[cfg(procmacro2_semver_exempt)]
10use std::path::Path;
11use std::path::PathBuf;
Alex Crichton44bffbc2017-05-19 17:51:59 -070012use std::str::FromStr;
13use std::vec;
14
David Tolnayb28f38a2018-03-31 22:02:29 +020015use strnom::{block_comment, skip_whitespace, whitespace, word_break, Cursor, PResult};
David Tolnayb1032662017-05-31 15:52:28 -070016use unicode_xid::UnicodeXID;
Alex Crichton44bffbc2017-05-19 17:51:59 -070017
David Tolnayf14813f2018-09-08 17:14:07 -070018use {Delimiter, Punct, Spacing, TokenTree};
Alex Crichton44bffbc2017-05-19 17:51:59 -070019
David Tolnay034205f2018-04-22 16:45:28 -070020#[derive(Clone)]
Alex Crichton44bffbc2017-05-19 17:51:59 -070021pub struct TokenStream {
22 inner: Vec<TokenTree>,
23}
24
25#[derive(Debug)]
26pub struct LexError;
27
28impl TokenStream {
David Tolnayc3bb4592018-05-28 20:09:44 -070029 pub fn new() -> TokenStream {
Alex Crichton44bffbc2017-05-19 17:51:59 -070030 TokenStream { inner: Vec::new() }
31 }
32
33 pub fn is_empty(&self) -> bool {
34 self.inner.len() == 0
35 }
36}
37
David Tolnay1ebe3972018-01-02 20:14:20 -080038#[cfg(procmacro2_semver_exempt)]
Nika Layzella9dbc182017-12-30 14:50:13 -050039fn get_cursor(src: &str) -> Cursor {
40 // Create a dummy file & add it to the codemap
41 CODEMAP.with(|cm| {
42 let mut cm = cm.borrow_mut();
43 let name = format!("<parsed string {}>", cm.files.len());
44 let span = cm.add_file(&name, src);
45 Cursor {
46 rest: src,
47 off: span.lo,
48 }
49 })
50}
51
David Tolnay1ebe3972018-01-02 20:14:20 -080052#[cfg(not(procmacro2_semver_exempt))]
Nika Layzella9dbc182017-12-30 14:50:13 -050053fn get_cursor(src: &str) -> Cursor {
David Tolnayb28f38a2018-03-31 22:02:29 +020054 Cursor { rest: src }
Nika Layzella9dbc182017-12-30 14:50:13 -050055}
56
Alex Crichton44bffbc2017-05-19 17:51:59 -070057impl FromStr for TokenStream {
58 type Err = LexError;
59
60 fn from_str(src: &str) -> Result<TokenStream, LexError> {
Nika Layzellf8d5f212017-12-11 14:07:02 -050061 // Create a dummy file & add it to the codemap
Nika Layzella9dbc182017-12-30 14:50:13 -050062 let cursor = get_cursor(src);
Nika Layzellf8d5f212017-12-11 14:07:02 -050063
64 match token_stream(cursor) {
David Tolnay1218e122017-06-01 11:13:45 -070065 Ok((input, output)) => {
Alex Crichton44bffbc2017-05-19 17:51:59 -070066 if skip_whitespace(input).len() != 0 {
67 Err(LexError)
68 } else {
Alex Crichton30a4e9e2018-04-27 17:02:19 -070069 Ok(output)
Alex Crichton44bffbc2017-05-19 17:51:59 -070070 }
71 }
David Tolnay1218e122017-06-01 11:13:45 -070072 Err(LexError) => Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -070073 }
74 }
75}
76
77impl fmt::Display for TokenStream {
78 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
79 let mut joint = false;
80 for (i, tt) in self.inner.iter().enumerate() {
81 if i != 0 && !joint {
82 write!(f, " ")?;
83 }
84 joint = false;
Alex Crichtonaf5bad42018-03-27 14:45:10 -070085 match *tt {
86 TokenTree::Group(ref tt) => {
87 let (start, end) = match tt.delimiter() {
Alex Crichton44bffbc2017-05-19 17:51:59 -070088 Delimiter::Parenthesis => ("(", ")"),
89 Delimiter::Brace => ("{", "}"),
90 Delimiter::Bracket => ("[", "]"),
91 Delimiter::None => ("", ""),
92 };
Alex Crichton30a4e9e2018-04-27 17:02:19 -070093 if tt.stream().into_iter().next().is_none() {
Alex Crichton852d53d2017-05-19 19:25:08 -070094 write!(f, "{} {}", start, end)?
95 } else {
Alex Crichtonaf5bad42018-03-27 14:45:10 -070096 write!(f, "{} {} {}", start, tt.stream(), end)?
Alex Crichton852d53d2017-05-19 19:25:08 -070097 }
Alex Crichton44bffbc2017-05-19 17:51:59 -070098 }
Alex Crichtonf3888432018-05-16 09:11:05 -070099 TokenTree::Ident(ref tt) => write!(f, "{}", tt)?,
100 TokenTree::Punct(ref tt) => {
101 write!(f, "{}", tt.as_char())?;
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700102 match tt.spacing() {
Alex Crichton1a7f7622017-07-05 17:47:15 -0700103 Spacing::Alone => {}
104 Spacing::Joint => joint = true,
Alex Crichton44bffbc2017-05-19 17:51:59 -0700105 }
106 }
Alex Crichtonb2c94622018-04-04 07:36:41 -0700107 TokenTree::Literal(ref tt) => write!(f, "{}", tt)?,
Alex Crichton44bffbc2017-05-19 17:51:59 -0700108 }
109 }
110
111 Ok(())
112 }
113}
114
David Tolnay034205f2018-04-22 16:45:28 -0700115impl fmt::Debug for TokenStream {
116 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
117 f.write_str("TokenStream ")?;
118 f.debug_list().entries(self.clone()).finish()
119 }
120}
121
Alex Crichton53548482018-08-11 21:54:05 -0700122#[cfg(use_proc_macro)]
Alex Crichton0e8e7f42018-02-22 06:15:13 -0800123impl From<::proc_macro::TokenStream> for TokenStream {
124 fn from(inner: ::proc_macro::TokenStream) -> TokenStream {
David Tolnayb28f38a2018-03-31 22:02:29 +0200125 inner
126 .to_string()
127 .parse()
128 .expect("compiler token stream parse failed")
Alex Crichton44bffbc2017-05-19 17:51:59 -0700129 }
130}
131
Alex Crichton53548482018-08-11 21:54:05 -0700132#[cfg(use_proc_macro)]
Alex Crichton0e8e7f42018-02-22 06:15:13 -0800133impl From<TokenStream> for ::proc_macro::TokenStream {
134 fn from(inner: TokenStream) -> ::proc_macro::TokenStream {
David Tolnayb28f38a2018-03-31 22:02:29 +0200135 inner
136 .to_string()
137 .parse()
138 .expect("failed to parse to compiler tokens")
Alex Crichton44bffbc2017-05-19 17:51:59 -0700139 }
140}
141
Alex Crichton44bffbc2017-05-19 17:51:59 -0700142impl From<TokenTree> for TokenStream {
143 fn from(tree: TokenTree) -> TokenStream {
144 TokenStream { inner: vec![tree] }
145 }
146}
147
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700148impl iter::FromIterator<TokenTree> for TokenStream {
David Tolnayb28f38a2018-03-31 22:02:29 +0200149 fn from_iter<I: IntoIterator<Item = TokenTree>>(streams: I) -> Self {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700150 let mut v = Vec::new();
151
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700152 for token in streams.into_iter() {
153 v.push(token);
Alex Crichton44bffbc2017-05-19 17:51:59 -0700154 }
155
156 TokenStream { inner: v }
157 }
158}
159
Alex Crichton53b00672018-09-06 17:16:10 -0700160impl iter::FromIterator<TokenStream> for TokenStream {
161 fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
162 let mut v = Vec::new();
163
164 for stream in streams.into_iter() {
165 v.extend(stream.inner);
166 }
167
168 TokenStream { inner: v }
169 }
170}
171
Alex Crichtonf3888432018-05-16 09:11:05 -0700172impl Extend<TokenTree> for TokenStream {
173 fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, streams: I) {
174 self.inner.extend(streams);
175 }
176}
177
David Tolnay5c58c532018-08-13 11:33:51 -0700178impl Extend<TokenStream> for TokenStream {
179 fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
180 self.inner
181 .extend(streams.into_iter().flat_map(|stream| stream));
182 }
183}
184
Alex Crichton1a7f7622017-07-05 17:47:15 -0700185pub type TokenTreeIter = vec::IntoIter<TokenTree>;
Alex Crichton44bffbc2017-05-19 17:51:59 -0700186
187impl IntoIterator for TokenStream {
188 type Item = TokenTree;
Alex Crichton1a7f7622017-07-05 17:47:15 -0700189 type IntoIter = TokenTreeIter;
Alex Crichton44bffbc2017-05-19 17:51:59 -0700190
Alex Crichton1a7f7622017-07-05 17:47:15 -0700191 fn into_iter(self) -> TokenTreeIter {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700192 self.inner.into_iter()
193 }
194}
195
Nika Layzellf8d5f212017-12-11 14:07:02 -0500196#[derive(Clone, PartialEq, Eq)]
197pub struct SourceFile {
David Tolnay9cd3b4c2018-11-11 16:47:32 -0800198 path: PathBuf,
Nika Layzellf8d5f212017-12-11 14:07:02 -0500199}
200
201impl SourceFile {
202 /// Get the path to this source file as a string.
David Tolnay9cd3b4c2018-11-11 16:47:32 -0800203 pub fn path(&self) -> PathBuf {
204 self.path.clone()
Nika Layzellf8d5f212017-12-11 14:07:02 -0500205 }
206
207 pub fn is_real(&self) -> bool {
208 // XXX(nika): Support real files in the future?
209 false
210 }
211}
212
Nika Layzellf8d5f212017-12-11 14:07:02 -0500213impl fmt::Debug for SourceFile {
214 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
215 f.debug_struct("SourceFile")
Nika Layzellb35a9a32017-12-30 14:34:35 -0500216 .field("path", &self.path())
Nika Layzellf8d5f212017-12-11 14:07:02 -0500217 .field("is_real", &self.is_real())
218 .finish()
219 }
220}
221
222#[derive(Clone, Copy, Debug, PartialEq, Eq)]
223pub struct LineColumn {
224 pub line: usize,
225 pub column: usize,
226}
227
David Tolnay1ebe3972018-01-02 20:14:20 -0800228#[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500229thread_local! {
230 static CODEMAP: RefCell<Codemap> = RefCell::new(Codemap {
231 // NOTE: We start with a single dummy file which all call_site() and
232 // def_site() spans reference.
233 files: vec![FileInfo {
234 name: "<unspecified>".to_owned(),
235 span: Span { lo: 0, hi: 0 },
236 lines: vec![0],
237 }],
238 });
239}
240
David Tolnay1ebe3972018-01-02 20:14:20 -0800241#[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500242struct FileInfo {
243 name: String,
244 span: Span,
245 lines: Vec<usize>,
246}
247
David Tolnay1ebe3972018-01-02 20:14:20 -0800248#[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500249impl FileInfo {
250 fn offset_line_column(&self, offset: usize) -> LineColumn {
David Tolnayb28f38a2018-03-31 22:02:29 +0200251 assert!(self.span_within(Span {
252 lo: offset as u32,
253 hi: offset as u32
254 }));
Nika Layzellf8d5f212017-12-11 14:07:02 -0500255 let offset = offset - self.span.lo as usize;
256 match self.lines.binary_search(&offset) {
257 Ok(found) => LineColumn {
258 line: found + 1,
David Tolnayb28f38a2018-03-31 22:02:29 +0200259 column: 0,
Nika Layzellf8d5f212017-12-11 14:07:02 -0500260 },
261 Err(idx) => LineColumn {
262 line: idx,
David Tolnayb28f38a2018-03-31 22:02:29 +0200263 column: offset - self.lines[idx - 1],
Nika Layzellf8d5f212017-12-11 14:07:02 -0500264 },
265 }
266 }
267
268 fn span_within(&self, span: Span) -> bool {
269 span.lo >= self.span.lo && span.hi <= self.span.hi
270 }
271}
272
Alex Crichtona914a612018-04-04 07:48:44 -0700273/// Computesthe offsets of each line in the given source string.
David Tolnay1ebe3972018-01-02 20:14:20 -0800274#[cfg(procmacro2_semver_exempt)]
Nika Layzella0a7c3d2017-12-30 14:52:39 -0500275fn lines_offsets(s: &str) -> Vec<usize> {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500276 let mut lines = vec![0];
277 let mut prev = 0;
Nika Layzella0a7c3d2017-12-30 14:52:39 -0500278 while let Some(len) = s[prev..].find('\n') {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500279 prev += len + 1;
280 lines.push(prev);
281 }
282 lines
283}
284
David Tolnay1ebe3972018-01-02 20:14:20 -0800285#[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500286struct Codemap {
287 files: Vec<FileInfo>,
288}
289
David Tolnay1ebe3972018-01-02 20:14:20 -0800290#[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500291impl Codemap {
292 fn next_start_pos(&self) -> u32 {
293 // Add 1 so there's always space between files.
294 //
295 // We'll always have at least 1 file, as we initialize our files list
296 // with a dummy file.
297 self.files.last().unwrap().span.hi + 1
298 }
299
300 fn add_file(&mut self, name: &str, src: &str) -> Span {
Nika Layzella0a7c3d2017-12-30 14:52:39 -0500301 let lines = lines_offsets(src);
Nika Layzellf8d5f212017-12-11 14:07:02 -0500302 let lo = self.next_start_pos();
303 // XXX(nika): Shouild we bother doing a checked cast or checked add here?
David Tolnayb28f38a2018-03-31 22:02:29 +0200304 let span = Span {
305 lo: lo,
306 hi: lo + (src.len() as u32),
307 };
Nika Layzellf8d5f212017-12-11 14:07:02 -0500308
309 self.files.push(FileInfo {
310 name: name.to_owned(),
311 span: span,
312 lines: lines,
313 });
314
315 span
316 }
317
318 fn fileinfo(&self, span: Span) -> &FileInfo {
319 for file in &self.files {
320 if file.span_within(span) {
321 return file;
322 }
323 }
324 panic!("Invalid span with no related FileInfo!");
325 }
326}
327
David Tolnay034205f2018-04-22 16:45:28 -0700328#[derive(Clone, Copy, PartialEq, Eq)]
David Tolnayddfca052017-12-31 10:41:24 -0500329pub struct Span {
David Tolnay1ebe3972018-01-02 20:14:20 -0800330 #[cfg(procmacro2_semver_exempt)]
David Tolnayddfca052017-12-31 10:41:24 -0500331 lo: u32,
David Tolnay1ebe3972018-01-02 20:14:20 -0800332 #[cfg(procmacro2_semver_exempt)]
David Tolnayddfca052017-12-31 10:41:24 -0500333 hi: u32,
334}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700335
336impl Span {
David Tolnay1ebe3972018-01-02 20:14:20 -0800337 #[cfg(not(procmacro2_semver_exempt))]
Alex Crichton44bffbc2017-05-19 17:51:59 -0700338 pub fn call_site() -> Span {
David Tolnay79105e52017-12-31 11:03:04 -0500339 Span {}
340 }
341
David Tolnay1ebe3972018-01-02 20:14:20 -0800342 #[cfg(procmacro2_semver_exempt)]
David Tolnay79105e52017-12-31 11:03:04 -0500343 pub fn call_site() -> Span {
344 Span { lo: 0, hi: 0 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700345 }
Alex Crichtone6085b72017-11-21 07:24:25 -0800346
347 pub fn def_site() -> Span {
David Tolnay79105e52017-12-31 11:03:04 -0500348 Span::call_site()
Nika Layzellf8d5f212017-12-11 14:07:02 -0500349 }
350
David Tolnay4e8e3972018-01-05 18:10:22 -0800351 pub fn resolved_at(&self, _other: Span) -> Span {
352 // Stable spans consist only of line/column information, so
353 // `resolved_at` and `located_at` only select which span the
354 // caller wants line/column information from.
355 *self
356 }
357
358 pub fn located_at(&self, other: Span) -> Span {
359 other
360 }
361
David Tolnay1ebe3972018-01-02 20:14:20 -0800362 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500363 pub fn source_file(&self) -> SourceFile {
364 CODEMAP.with(|cm| {
365 let cm = cm.borrow();
366 let fi = cm.fileinfo(*self);
367 SourceFile {
David Tolnay9cd3b4c2018-11-11 16:47:32 -0800368 path: Path::new(&fi.name).to_owned(),
Nika Layzellf8d5f212017-12-11 14:07:02 -0500369 }
370 })
371 }
372
David Tolnay1ebe3972018-01-02 20:14:20 -0800373 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500374 pub fn start(&self) -> LineColumn {
375 CODEMAP.with(|cm| {
376 let cm = cm.borrow();
377 let fi = cm.fileinfo(*self);
378 fi.offset_line_column(self.lo as usize)
379 })
380 }
381
David Tolnay1ebe3972018-01-02 20:14:20 -0800382 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500383 pub fn end(&self) -> LineColumn {
384 CODEMAP.with(|cm| {
385 let cm = cm.borrow();
386 let fi = cm.fileinfo(*self);
387 fi.offset_line_column(self.hi as usize)
388 })
389 }
390
David Tolnay1ebe3972018-01-02 20:14:20 -0800391 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500392 pub fn join(&self, other: Span) -> Option<Span> {
393 CODEMAP.with(|cm| {
394 let cm = cm.borrow();
395 // If `other` is not within the same FileInfo as us, return None.
396 if !cm.fileinfo(*self).span_within(other) {
397 return None;
398 }
399 Some(Span {
400 lo: cmp::min(self.lo, other.lo),
401 hi: cmp::max(self.hi, other.hi),
402 })
403 })
Alex Crichtone6085b72017-11-21 07:24:25 -0800404 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700405}
406
David Tolnay034205f2018-04-22 16:45:28 -0700407impl fmt::Debug for Span {
408 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
409 #[cfg(procmacro2_semver_exempt)]
410 return write!(f, "bytes({}..{})", self.lo, self.hi);
411
412 #[cfg(not(procmacro2_semver_exempt))]
413 write!(f, "Span")
414 }
415}
416
Alex Crichtonf3888432018-05-16 09:11:05 -0700417#[derive(Clone)]
David Tolnayf14813f2018-09-08 17:14:07 -0700418pub struct Group {
419 delimiter: Delimiter,
420 stream: TokenStream,
421 span: Span,
422}
423
424impl Group {
425 pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
426 Group {
427 delimiter: delimiter,
428 stream: stream,
429 span: Span::call_site(),
430 }
431 }
432
433 pub fn delimiter(&self) -> Delimiter {
434 self.delimiter
435 }
436
437 pub fn stream(&self) -> TokenStream {
438 self.stream.clone()
439 }
440
441 pub fn span(&self) -> Span {
442 self.span
443 }
444
445 pub fn span_open(&self) -> Span {
446 self.span
447 }
448
449 pub fn span_close(&self) -> Span {
450 self.span
451 }
452
453 pub fn set_span(&mut self, span: Span) {
454 self.span = span;
455 }
456}
457
458impl fmt::Display for Group {
459 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
460 let (left, right) = match self.delimiter {
461 Delimiter::Parenthesis => ("(", ")"),
462 Delimiter::Brace => ("{", "}"),
463 Delimiter::Bracket => ("[", "]"),
464 Delimiter::None => ("", ""),
465 };
466
467 f.write_str(left)?;
468 self.stream.fmt(f)?;
469 f.write_str(right)?;
470
471 Ok(())
472 }
473}
474
475impl fmt::Debug for Group {
476 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
477 let mut debug = fmt.debug_struct("Group");
478 debug.field("delimiter", &self.delimiter);
479 debug.field("stream", &self.stream);
480 #[cfg(procmacro2_semver_exempt)]
481 debug.field("span", &self.span);
482 debug.finish()
483 }
484}
485
486#[derive(Clone)]
Alex Crichtonf3888432018-05-16 09:11:05 -0700487pub struct Ident {
David Tolnayc2309ca2018-06-02 15:47:57 -0700488 sym: String,
Alex Crichtonb2c94622018-04-04 07:36:41 -0700489 span: Span,
Alex Crichtonf3888432018-05-16 09:11:05 -0700490 raw: bool,
David Tolnay041bcd42017-06-03 09:18:04 -0700491}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700492
Alex Crichtonf3888432018-05-16 09:11:05 -0700493impl Ident {
494 fn _new(string: &str, raw: bool, span: Span) -> Ident {
David Tolnay489c6422018-04-07 08:37:28 -0700495 validate_term(string);
496
Alex Crichtonf3888432018-05-16 09:11:05 -0700497 Ident {
David Tolnayc2309ca2018-06-02 15:47:57 -0700498 sym: string.to_owned(),
Alex Crichtona914a612018-04-04 07:48:44 -0700499 span: span,
Alex Crichtonf3888432018-05-16 09:11:05 -0700500 raw: raw,
David Tolnay041bcd42017-06-03 09:18:04 -0700501 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700502 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700503
Alex Crichtonf3888432018-05-16 09:11:05 -0700504 pub fn new(string: &str, span: Span) -> Ident {
505 Ident::_new(string, false, span)
506 }
507
508 pub fn new_raw(string: &str, span: Span) -> Ident {
509 Ident::_new(string, true, span)
510 }
511
Alex Crichtonb2c94622018-04-04 07:36:41 -0700512 pub fn span(&self) -> Span {
513 self.span
514 }
515
516 pub fn set_span(&mut self, span: Span) {
517 self.span = span;
518 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700519}
520
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000521#[inline]
522fn is_ident_start(c: char) -> bool {
David Tolnay03b43da2018-06-02 15:25:57 -0700523 ('a' <= c && c <= 'z')
524 || ('A' <= c && c <= 'Z')
525 || c == '_'
526 || (c > '\x7f' && UnicodeXID::is_xid_start(c))
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000527}
528
529#[inline]
530fn is_ident_continue(c: char) -> bool {
David Tolnay03b43da2018-06-02 15:25:57 -0700531 ('a' <= c && c <= 'z')
532 || ('A' <= c && c <= 'Z')
533 || c == '_'
534 || ('0' <= c && c <= '9')
535 || (c > '\x7f' && UnicodeXID::is_xid_continue(c))
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000536}
537
David Tolnay489c6422018-04-07 08:37:28 -0700538fn validate_term(string: &str) {
Alex Crichtonf3888432018-05-16 09:11:05 -0700539 let validate = string;
David Tolnay489c6422018-04-07 08:37:28 -0700540 if validate.is_empty() {
Alex Crichtonf3888432018-05-16 09:11:05 -0700541 panic!("Ident is not allowed to be empty; use Option<Ident>");
David Tolnay489c6422018-04-07 08:37:28 -0700542 }
543
544 if validate.bytes().all(|digit| digit >= b'0' && digit <= b'9') {
Alex Crichtonf3888432018-05-16 09:11:05 -0700545 panic!("Ident cannot be a number; use Literal instead");
David Tolnay489c6422018-04-07 08:37:28 -0700546 }
547
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000548 fn ident_ok(string: &str) -> bool {
David Tolnay489c6422018-04-07 08:37:28 -0700549 let mut chars = string.chars();
550 let first = chars.next().unwrap();
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000551 if !is_ident_start(first) {
David Tolnay489c6422018-04-07 08:37:28 -0700552 return false;
553 }
554 for ch in chars {
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000555 if !is_ident_continue(ch) {
David Tolnay489c6422018-04-07 08:37:28 -0700556 return false;
557 }
558 }
559 true
560 }
561
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000562 if !ident_ok(validate) {
Alex Crichtonf3888432018-05-16 09:11:05 -0700563 panic!("{:?} is not a valid Ident", string);
David Tolnay489c6422018-04-07 08:37:28 -0700564 }
565}
566
David Tolnayc0b0f2e2018-09-02 17:56:08 -0700567impl PartialEq for Ident {
568 fn eq(&self, other: &Ident) -> bool {
569 self.sym == other.sym && self.raw == other.raw
570 }
571}
572
573impl<T> PartialEq<T> for Ident
574where
575 T: ?Sized + AsRef<str>,
576{
577 fn eq(&self, other: &T) -> bool {
578 let other = other.as_ref();
579 if self.raw {
580 other.starts_with("r#") && self.sym == other[2..]
581 } else {
582 self.sym == other
583 }
584 }
585}
586
Alex Crichtonf3888432018-05-16 09:11:05 -0700587impl fmt::Display for Ident {
David Tolnay8ad3e3e2017-06-03 16:45:00 -0700588 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Alex Crichtonf3888432018-05-16 09:11:05 -0700589 if self.raw {
590 "r#".fmt(f)?;
591 }
David Tolnayc2309ca2018-06-02 15:47:57 -0700592 self.sym.fmt(f)
Alex Crichtonf3888432018-05-16 09:11:05 -0700593 }
594}
595
596impl fmt::Debug for Ident {
David Tolnayd8fcdb82018-06-02 15:43:53 -0700597 // Ident(proc_macro), Ident(r#union)
598 #[cfg(not(procmacro2_semver_exempt))]
599 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
600 let mut debug = f.debug_tuple("Ident");
601 debug.field(&format_args!("{}", self));
602 debug.finish()
603 }
604
605 // Ident {
606 // sym: proc_macro,
607 // span: bytes(128..138)
608 // }
609 #[cfg(procmacro2_semver_exempt)]
Alex Crichtonf3888432018-05-16 09:11:05 -0700610 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
611 let mut debug = f.debug_struct("Ident");
David Tolnayd8fcdb82018-06-02 15:43:53 -0700612 debug.field("sym", &format_args!("{}", self));
David Tolnay034205f2018-04-22 16:45:28 -0700613 debug.field("span", &self.span);
614 debug.finish()
David Tolnay8ad3e3e2017-06-03 16:45:00 -0700615 }
616}
617
David Tolnay034205f2018-04-22 16:45:28 -0700618#[derive(Clone)]
Alex Crichtonb2c94622018-04-04 07:36:41 -0700619pub struct Literal {
620 text: String,
621 span: Span,
622}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700623
Alex Crichtona914a612018-04-04 07:48:44 -0700624macro_rules! suffixed_numbers {
625 ($($name:ident => $kind:ident,)*) => ($(
626 pub fn $name(n: $kind) -> Literal {
627 Literal::_new(format!(concat!("{}", stringify!($kind)), n))
628 }
629 )*)
630}
631
632macro_rules! unsuffixed_numbers {
633 ($($name:ident => $kind:ident,)*) => ($(
634 pub fn $name(n: $kind) -> Literal {
635 Literal::_new(n.to_string())
636 }
637 )*)
638}
639
Alex Crichton852d53d2017-05-19 19:25:08 -0700640impl Literal {
Alex Crichtonb2c94622018-04-04 07:36:41 -0700641 fn _new(text: String) -> Literal {
642 Literal {
Alex Crichtona914a612018-04-04 07:48:44 -0700643 text: text,
Alex Crichtonb2c94622018-04-04 07:36:41 -0700644 span: Span::call_site(),
645 }
646 }
647
Alex Crichtona914a612018-04-04 07:48:44 -0700648 suffixed_numbers! {
649 u8_suffixed => u8,
650 u16_suffixed => u16,
651 u32_suffixed => u32,
652 u64_suffixed => u64,
653 usize_suffixed => usize,
654 i8_suffixed => i8,
655 i16_suffixed => i16,
656 i32_suffixed => i32,
657 i64_suffixed => i64,
658 isize_suffixed => isize,
659
660 f32_suffixed => f32,
661 f64_suffixed => f64,
662 }
663
Alex Crichton69385662018-11-08 06:30:04 -0800664 #[cfg(u128)]
665 suffixed_numbers! {
666 u128_suffixed => u128,
667 i128_suffixed => i128,
668 }
669
Alex Crichtona914a612018-04-04 07:48:44 -0700670 unsuffixed_numbers! {
671 u8_unsuffixed => u8,
672 u16_unsuffixed => u16,
673 u32_unsuffixed => u32,
674 u64_unsuffixed => u64,
675 usize_unsuffixed => usize,
676 i8_unsuffixed => i8,
677 i16_unsuffixed => i16,
678 i32_unsuffixed => i32,
679 i64_unsuffixed => i64,
680 isize_unsuffixed => isize,
681 }
682
Alex Crichton69385662018-11-08 06:30:04 -0800683 #[cfg(u128)]
684 unsuffixed_numbers! {
685 u128_unsuffixed => u128,
686 i128_unsuffixed => i128,
687 }
688
Alex Crichtona914a612018-04-04 07:48:44 -0700689 pub fn f32_unsuffixed(f: f32) -> Literal {
690 let mut s = f.to_string();
691 if !s.contains(".") {
692 s.push_str(".0");
Alex Crichton76a5cc82017-05-23 07:01:44 -0700693 }
Alex Crichtona914a612018-04-04 07:48:44 -0700694 Literal::_new(s)
695 }
696
697 pub fn f64_unsuffixed(f: f64) -> Literal {
698 let mut s = f.to_string();
699 if !s.contains(".") {
700 s.push_str(".0");
701 }
702 Literal::_new(s)
703 }
704
705 pub fn string(t: &str) -> Literal {
David Tolnay3d9d6ad2018-05-18 10:51:55 -0700706 let mut s = t
707 .chars()
Alex Crichtona914a612018-04-04 07:48:44 -0700708 .flat_map(|c| c.escape_default())
709 .collect::<String>();
710 s.push('"');
711 s.insert(0, '"');
712 Literal::_new(s)
713 }
714
715 pub fn character(t: char) -> Literal {
716 Literal::_new(format!("'{}'", t.escape_default().collect::<String>()))
Alex Crichton76a5cc82017-05-23 07:01:44 -0700717 }
718
Alex Crichton9c2fb0a2017-05-26 08:49:31 -0700719 pub fn byte_string(bytes: &[u8]) -> Literal {
Alex Crichton852d53d2017-05-19 19:25:08 -0700720 let mut escaped = "b\"".to_string();
721 for b in bytes {
722 match *b {
723 b'\0' => escaped.push_str(r"\0"),
724 b'\t' => escaped.push_str(r"\t"),
725 b'\n' => escaped.push_str(r"\n"),
726 b'\r' => escaped.push_str(r"\r"),
727 b'"' => escaped.push_str("\\\""),
728 b'\\' => escaped.push_str("\\\\"),
David Tolnayb28f38a2018-03-31 22:02:29 +0200729 b'\x20'...b'\x7E' => escaped.push(*b as char),
Alex Crichton852d53d2017-05-19 19:25:08 -0700730 _ => escaped.push_str(&format!("\\x{:02X}", b)),
731 }
732 }
733 escaped.push('"');
Alex Crichtonb2c94622018-04-04 07:36:41 -0700734 Literal::_new(escaped)
Alex Crichton76a5cc82017-05-23 07:01:44 -0700735 }
Alex Crichton9c2fb0a2017-05-26 08:49:31 -0700736
Alex Crichtonb2c94622018-04-04 07:36:41 -0700737 pub fn span(&self) -> Span {
738 self.span
Alex Crichton31316622017-05-26 12:54:47 -0700739 }
740
Alex Crichtonb2c94622018-04-04 07:36:41 -0700741 pub fn set_span(&mut self, span: Span) {
742 self.span = span;
Alex Crichton31316622017-05-26 12:54:47 -0700743 }
Alex Crichton852d53d2017-05-19 19:25:08 -0700744}
745
Alex Crichton44bffbc2017-05-19 17:51:59 -0700746impl fmt::Display for Literal {
747 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Alex Crichtonb2c94622018-04-04 07:36:41 -0700748 self.text.fmt(f)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700749 }
750}
751
David Tolnay034205f2018-04-22 16:45:28 -0700752impl fmt::Debug for Literal {
753 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
754 let mut debug = fmt.debug_struct("Literal");
755 debug.field("lit", &format_args!("{}", self.text));
756 #[cfg(procmacro2_semver_exempt)]
757 debug.field("span", &self.span);
758 debug.finish()
759 }
760}
761
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700762fn token_stream(mut input: Cursor) -> PResult<TokenStream> {
Alex Crichton1eb96a02018-04-04 13:07:35 -0700763 let mut trees = Vec::new();
764 loop {
765 let input_no_ws = skip_whitespace(input);
766 if input_no_ws.rest.len() == 0 {
David Tolnay48ea5042018-04-23 19:17:35 -0700767 break;
Alex Crichton1eb96a02018-04-04 13:07:35 -0700768 }
769 if let Ok((a, tokens)) = doc_comment(input_no_ws) {
770 input = a;
771 trees.extend(tokens);
David Tolnay48ea5042018-04-23 19:17:35 -0700772 continue;
Alex Crichton1eb96a02018-04-04 13:07:35 -0700773 }
774
775 let (a, tt) = match token_tree(input_no_ws) {
776 Ok(p) => p,
777 Err(_) => break,
778 };
779 trees.push(tt);
780 input = a;
781 }
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700782 Ok((input, TokenStream { inner: trees }))
Alex Crichton1eb96a02018-04-04 13:07:35 -0700783}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700784
David Tolnay1ebe3972018-01-02 20:14:20 -0800785#[cfg(not(procmacro2_semver_exempt))]
Alex Crichton1eb96a02018-04-04 13:07:35 -0700786fn spanned<'a, T>(
787 input: Cursor<'a>,
788 f: fn(Cursor<'a>) -> PResult<'a, T>,
789) -> PResult<'a, (T, ::Span)> {
790 let (a, b) = f(skip_whitespace(input))?;
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700791 Ok((a, ((b, ::Span::_new_stable(Span {})))))
David Tolnayddfca052017-12-31 10:41:24 -0500792}
793
David Tolnay1ebe3972018-01-02 20:14:20 -0800794#[cfg(procmacro2_semver_exempt)]
Alex Crichton1eb96a02018-04-04 13:07:35 -0700795fn spanned<'a, T>(
796 input: Cursor<'a>,
797 f: fn(Cursor<'a>) -> PResult<'a, T>,
798) -> PResult<'a, (T, ::Span)> {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500799 let input = skip_whitespace(input);
800 let lo = input.off;
Alex Crichton1eb96a02018-04-04 13:07:35 -0700801 let (a, b) = f(input)?;
802 let hi = a.off;
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700803 let span = ::Span::_new_stable(Span { lo: lo, hi: hi });
Alex Crichton1eb96a02018-04-04 13:07:35 -0700804 Ok((a, (b, span)))
805}
806
807fn token_tree(input: Cursor) -> PResult<TokenTree> {
808 let (rest, (mut tt, span)) = spanned(input, token_kind)?;
809 tt.set_span(span);
810 Ok((rest, tt))
Nika Layzellf8d5f212017-12-11 14:07:02 -0500811}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700812
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700813named!(token_kind -> TokenTree, alt!(
David Tolnayf14813f2018-09-08 17:14:07 -0700814 map!(group, |g| TokenTree::Group(::Group::_new_stable(g)))
Alex Crichton44bffbc2017-05-19 17:51:59 -0700815 |
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700816 map!(literal, |l| TokenTree::Literal(::Literal::_new_stable(l))) // must be before symbol
Alex Crichton44bffbc2017-05-19 17:51:59 -0700817 |
Alex Crichtonf3888432018-05-16 09:11:05 -0700818 map!(op, TokenTree::Punct)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700819 |
Alex Crichtonf3888432018-05-16 09:11:05 -0700820 symbol_leading_ws
Alex Crichton44bffbc2017-05-19 17:51:59 -0700821));
822
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700823named!(group -> Group, alt!(
Alex Crichton44bffbc2017-05-19 17:51:59 -0700824 delimited!(
825 punct!("("),
826 token_stream,
827 punct!(")")
David Tolnayf14813f2018-09-08 17:14:07 -0700828 ) => { |ts| Group::new(Delimiter::Parenthesis, ts) }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700829 |
830 delimited!(
831 punct!("["),
832 token_stream,
833 punct!("]")
David Tolnayf14813f2018-09-08 17:14:07 -0700834 ) => { |ts| Group::new(Delimiter::Bracket, ts) }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700835 |
836 delimited!(
837 punct!("{"),
838 token_stream,
839 punct!("}")
David Tolnayf14813f2018-09-08 17:14:07 -0700840 ) => { |ts| Group::new(Delimiter::Brace, ts) }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700841));
842
Alex Crichtonf3888432018-05-16 09:11:05 -0700843fn symbol_leading_ws(input: Cursor) -> PResult<TokenTree> {
844 symbol(skip_whitespace(input))
845}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700846
Alex Crichtonf3888432018-05-16 09:11:05 -0700847fn symbol(input: Cursor) -> PResult<TokenTree> {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700848 let mut chars = input.char_indices();
David Tolnaya202d502017-06-01 12:26:55 -0700849
Alex Crichtonf3888432018-05-16 09:11:05 -0700850 let raw = input.starts_with("r#");
David Tolnaya13d1422018-03-31 21:27:48 +0200851 if raw {
852 chars.next();
853 chars.next();
854 }
855
Alex Crichton44bffbc2017-05-19 17:51:59 -0700856 match chars.next() {
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000857 Some((_, ch)) if is_ident_start(ch) => {}
David Tolnay1218e122017-06-01 11:13:45 -0700858 _ => return Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -0700859 }
860
David Tolnay214c94c2017-06-01 12:42:56 -0700861 let mut end = input.len();
Alex Crichton44bffbc2017-05-19 17:51:59 -0700862 for (i, ch) in chars {
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000863 if !is_ident_continue(ch) {
David Tolnay214c94c2017-06-01 12:42:56 -0700864 end = i;
865 break;
Alex Crichton44bffbc2017-05-19 17:51:59 -0700866 }
867 }
868
David Tolnaya13d1422018-03-31 21:27:48 +0200869 let a = &input.rest[..end];
Alex Crichtonf3888432018-05-16 09:11:05 -0700870 if a == "r#_" {
David Tolnay214c94c2017-06-01 12:42:56 -0700871 Err(LexError)
872 } else {
Alex Crichtonf3888432018-05-16 09:11:05 -0700873 let ident = if raw {
874 ::Ident::_new_raw(&a[2..], ::Span::call_site())
875 } else {
876 ::Ident::new(a, ::Span::call_site())
877 };
878 Ok((input.advance(end), ident.into()))
David Tolnay214c94c2017-06-01 12:42:56 -0700879 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700880}
881
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700882fn literal(input: Cursor) -> PResult<Literal> {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700883 let input_no_ws = skip_whitespace(input);
884
885 match literal_nocapture(input_no_ws) {
David Tolnay1218e122017-06-01 11:13:45 -0700886 Ok((a, ())) => {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700887 let start = input.len() - input_no_ws.len();
888 let len = input_no_ws.len() - a.len();
889 let end = start + len;
David Tolnay3d9d6ad2018-05-18 10:51:55 -0700890 Ok((a, Literal::_new(input.rest[start..end].to_string())))
Alex Crichton44bffbc2017-05-19 17:51:59 -0700891 }
David Tolnay1218e122017-06-01 11:13:45 -0700892 Err(LexError) => Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -0700893 }
894}
895
896named!(literal_nocapture -> (), alt!(
897 string
898 |
899 byte_string
900 |
901 byte
902 |
903 character
904 |
905 float
906 |
907 int
Alex Crichton44bffbc2017-05-19 17:51:59 -0700908));
909
910named!(string -> (), alt!(
911 quoted_string
912 |
913 preceded!(
914 punct!("r"),
915 raw_string
916 ) => { |_| () }
917));
918
919named!(quoted_string -> (), delimited!(
920 punct!("\""),
921 cooked_string,
922 tag!("\"")
923));
924
Nika Layzellf8d5f212017-12-11 14:07:02 -0500925fn cooked_string(input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700926 let mut chars = input.char_indices().peekable();
927 while let Some((byte_offset, ch)) = chars.next() {
928 match ch {
929 '"' => {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500930 return Ok((input.advance(byte_offset), ()));
Alex Crichton44bffbc2017-05-19 17:51:59 -0700931 }
932 '\r' => {
933 if let Some((_, '\n')) = chars.next() {
934 // ...
935 } else {
936 break;
937 }
938 }
David Tolnayb28f38a2018-03-31 22:02:29 +0200939 '\\' => match chars.next() {
940 Some((_, 'x')) => {
941 if !backslash_x_char(&mut chars) {
942 break;
Alex Crichton44bffbc2017-05-19 17:51:59 -0700943 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700944 }
David Tolnayb28f38a2018-03-31 22:02:29 +0200945 Some((_, 'n')) | Some((_, 'r')) | Some((_, 't')) | Some((_, '\\'))
946 | Some((_, '\'')) | Some((_, '"')) | Some((_, '0')) => {}
947 Some((_, 'u')) => {
948 if !backslash_u(&mut chars) {
949 break;
950 }
951 }
952 Some((_, '\n')) | Some((_, '\r')) => {
953 while let Some(&(_, ch)) = chars.peek() {
954 if ch.is_whitespace() {
955 chars.next();
956 } else {
957 break;
958 }
959 }
960 }
961 _ => break,
962 },
Alex Crichton44bffbc2017-05-19 17:51:59 -0700963 _ch => {}
964 }
965 }
David Tolnay1218e122017-06-01 11:13:45 -0700966 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700967}
968
969named!(byte_string -> (), alt!(
970 delimited!(
971 punct!("b\""),
972 cooked_byte_string,
973 tag!("\"")
974 ) => { |_| () }
975 |
976 preceded!(
977 punct!("br"),
978 raw_string
979 ) => { |_| () }
980));
981
Nika Layzellf8d5f212017-12-11 14:07:02 -0500982fn cooked_byte_string(mut input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700983 let mut bytes = input.bytes().enumerate();
984 'outer: while let Some((offset, b)) = bytes.next() {
985 match b {
986 b'"' => {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500987 return Ok((input.advance(offset), ()));
Alex Crichton44bffbc2017-05-19 17:51:59 -0700988 }
989 b'\r' => {
990 if let Some((_, b'\n')) = bytes.next() {
991 // ...
992 } else {
993 break;
994 }
995 }
David Tolnayb28f38a2018-03-31 22:02:29 +0200996 b'\\' => match bytes.next() {
997 Some((_, b'x')) => {
998 if !backslash_x_byte(&mut bytes) {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700999 break;
1000 }
Alex Crichton44bffbc2017-05-19 17:51:59 -07001001 }
David Tolnayb28f38a2018-03-31 22:02:29 +02001002 Some((_, b'n')) | Some((_, b'r')) | Some((_, b't')) | Some((_, b'\\'))
1003 | Some((_, b'0')) | Some((_, b'\'')) | Some((_, b'"')) => {}
1004 Some((newline, b'\n')) | Some((newline, b'\r')) => {
1005 let rest = input.advance(newline + 1);
1006 for (offset, ch) in rest.char_indices() {
1007 if !ch.is_whitespace() {
1008 input = rest.advance(offset);
1009 bytes = input.bytes().enumerate();
1010 continue 'outer;
1011 }
1012 }
1013 break;
1014 }
1015 _ => break,
1016 },
Alex Crichton44bffbc2017-05-19 17:51:59 -07001017 b if b < 0x80 => {}
1018 _ => break,
1019 }
1020 }
David Tolnay1218e122017-06-01 11:13:45 -07001021 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001022}
1023
Nika Layzellf8d5f212017-12-11 14:07:02 -05001024fn raw_string(input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001025 let mut chars = input.char_indices();
1026 let mut n = 0;
1027 while let Some((byte_offset, ch)) = chars.next() {
1028 match ch {
1029 '"' => {
1030 n = byte_offset;
1031 break;
1032 }
1033 '#' => {}
David Tolnay1218e122017-06-01 11:13:45 -07001034 _ => return Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -07001035 }
1036 }
1037 for (byte_offset, ch) in chars {
1038 match ch {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001039 '"' if input.advance(byte_offset + 1).starts_with(&input.rest[..n]) => {
1040 let rest = input.advance(byte_offset + 1 + n);
David Tolnayb28f38a2018-03-31 22:02:29 +02001041 return Ok((rest, ()));
Alex Crichton44bffbc2017-05-19 17:51:59 -07001042 }
1043 '\r' => {}
1044 _ => {}
1045 }
1046 }
David Tolnay1218e122017-06-01 11:13:45 -07001047 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001048}
1049
1050named!(byte -> (), do_parse!(
1051 punct!("b") >>
1052 tag!("'") >>
1053 cooked_byte >>
1054 tag!("'") >>
1055 (())
1056));
1057
Nika Layzellf8d5f212017-12-11 14:07:02 -05001058fn cooked_byte(input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001059 let mut bytes = input.bytes().enumerate();
1060 let ok = match bytes.next().map(|(_, b)| b) {
David Tolnayb28f38a2018-03-31 22:02:29 +02001061 Some(b'\\') => match bytes.next().map(|(_, b)| b) {
1062 Some(b'x') => backslash_x_byte(&mut bytes),
1063 Some(b'n') | Some(b'r') | Some(b't') | Some(b'\\') | Some(b'0') | Some(b'\'')
1064 | Some(b'"') => true,
1065 _ => false,
1066 },
Alex Crichton44bffbc2017-05-19 17:51:59 -07001067 b => b.is_some(),
1068 };
1069 if ok {
1070 match bytes.next() {
Alex Crichton8c030332018-01-16 08:07:36 -08001071 Some((offset, _)) => {
1072 if input.chars().as_str().is_char_boundary(offset) {
1073 Ok((input.advance(offset), ()))
1074 } else {
1075 Err(LexError)
1076 }
1077 }
Nika Layzellf8d5f212017-12-11 14:07:02 -05001078 None => Ok((input.advance(input.len()), ())),
Alex Crichton44bffbc2017-05-19 17:51:59 -07001079 }
1080 } else {
David Tolnay1218e122017-06-01 11:13:45 -07001081 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001082 }
1083}
1084
1085named!(character -> (), do_parse!(
1086 punct!("'") >>
1087 cooked_char >>
1088 tag!("'") >>
1089 (())
1090));
1091
Nika Layzellf8d5f212017-12-11 14:07:02 -05001092fn cooked_char(input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001093 let mut chars = input.char_indices();
1094 let ok = match chars.next().map(|(_, ch)| ch) {
David Tolnayb28f38a2018-03-31 22:02:29 +02001095 Some('\\') => match chars.next().map(|(_, ch)| ch) {
1096 Some('x') => backslash_x_char(&mut chars),
1097 Some('u') => backslash_u(&mut chars),
1098 Some('n') | Some('r') | Some('t') | Some('\\') | Some('0') | Some('\'') | Some('"') => {
1099 true
Alex Crichton44bffbc2017-05-19 17:51:59 -07001100 }
David Tolnayb28f38a2018-03-31 22:02:29 +02001101 _ => false,
1102 },
Alex Crichton44bffbc2017-05-19 17:51:59 -07001103 ch => ch.is_some(),
1104 };
1105 if ok {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001106 match chars.next() {
1107 Some((idx, _)) => Ok((input.advance(idx), ())),
1108 None => Ok((input.advance(input.len()), ())),
1109 }
Alex Crichton44bffbc2017-05-19 17:51:59 -07001110 } else {
David Tolnay1218e122017-06-01 11:13:45 -07001111 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001112 }
1113}
1114
1115macro_rules! next_ch {
1116 ($chars:ident @ $pat:pat $(| $rest:pat)*) => {
1117 match $chars.next() {
1118 Some((_, ch)) => match ch {
1119 $pat $(| $rest)* => ch,
1120 _ => return false,
1121 },
1122 None => return false
1123 }
1124 };
1125}
1126
1127fn backslash_x_char<I>(chars: &mut I) -> bool
David Tolnayb28f38a2018-03-31 22:02:29 +02001128where
1129 I: Iterator<Item = (usize, char)>,
Alex Crichton44bffbc2017-05-19 17:51:59 -07001130{
1131 next_ch!(chars @ '0'...'7');
1132 next_ch!(chars @ '0'...'9' | 'a'...'f' | 'A'...'F');
1133 true
1134}
1135
1136fn backslash_x_byte<I>(chars: &mut I) -> bool
David Tolnayb28f38a2018-03-31 22:02:29 +02001137where
1138 I: Iterator<Item = (usize, u8)>,
Alex Crichton44bffbc2017-05-19 17:51:59 -07001139{
1140 next_ch!(chars @ b'0'...b'9' | b'a'...b'f' | b'A'...b'F');
1141 next_ch!(chars @ b'0'...b'9' | b'a'...b'f' | b'A'...b'F');
1142 true
1143}
1144
1145fn backslash_u<I>(chars: &mut I) -> bool
David Tolnayb28f38a2018-03-31 22:02:29 +02001146where
1147 I: Iterator<Item = (usize, char)>,
Alex Crichton44bffbc2017-05-19 17:51:59 -07001148{
1149 next_ch!(chars @ '{');
1150 next_ch!(chars @ '0'...'9' | 'a'...'f' | 'A'...'F');
David Tolnay8d109342017-12-25 18:24:45 -05001151 loop {
1152 let c = next_ch!(chars @ '0'...'9' | 'a'...'f' | 'A'...'F' | '_' | '}');
1153 if c == '}' {
1154 return true;
1155 }
Alex Crichton44bffbc2017-05-19 17:51:59 -07001156 }
Alex Crichton44bffbc2017-05-19 17:51:59 -07001157}
1158
Nika Layzellf8d5f212017-12-11 14:07:02 -05001159fn float(input: Cursor) -> PResult<()> {
David Tolnay744a6b82017-06-01 11:34:29 -07001160 let (rest, ()) = float_digits(input)?;
1161 for suffix in &["f32", "f64"] {
1162 if rest.starts_with(suffix) {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001163 return word_break(rest.advance(suffix.len()));
David Tolnay744a6b82017-06-01 11:34:29 -07001164 }
1165 }
1166 word_break(rest)
1167}
Alex Crichton44bffbc2017-05-19 17:51:59 -07001168
Nika Layzellf8d5f212017-12-11 14:07:02 -05001169fn float_digits(input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001170 let mut chars = input.chars().peekable();
1171 match chars.next() {
1172 Some(ch) if ch >= '0' && ch <= '9' => {}
David Tolnay1218e122017-06-01 11:13:45 -07001173 _ => return Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -07001174 }
1175
1176 let mut len = 1;
1177 let mut has_dot = false;
1178 let mut has_exp = false;
1179 while let Some(&ch) = chars.peek() {
1180 match ch {
1181 '0'...'9' | '_' => {
1182 chars.next();
1183 len += 1;
1184 }
1185 '.' => {
1186 if has_dot {
1187 break;
1188 }
1189 chars.next();
David Tolnayb28f38a2018-03-31 22:02:29 +02001190 if chars
1191 .peek()
1192 .map(|&ch| ch == '.' || UnicodeXID::is_xid_start(ch))
1193 .unwrap_or(false)
1194 {
David Tolnay1218e122017-06-01 11:13:45 -07001195 return Err(LexError);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001196 }
1197 len += 1;
1198 has_dot = true;
1199 }
1200 'e' | 'E' => {
1201 chars.next();
1202 len += 1;
1203 has_exp = true;
1204 break;
1205 }
1206 _ => break,
1207 }
1208 }
1209
Nika Layzellf8d5f212017-12-11 14:07:02 -05001210 let rest = input.advance(len);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001211 if !(has_dot || has_exp || rest.starts_with("f32") || rest.starts_with("f64")) {
David Tolnay1218e122017-06-01 11:13:45 -07001212 return Err(LexError);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001213 }
1214
1215 if has_exp {
1216 let mut has_exp_value = false;
1217 while let Some(&ch) = chars.peek() {
1218 match ch {
1219 '+' | '-' => {
1220 if has_exp_value {
1221 break;
1222 }
1223 chars.next();
1224 len += 1;
1225 }
1226 '0'...'9' => {
1227 chars.next();
1228 len += 1;
1229 has_exp_value = true;
1230 }
1231 '_' => {
1232 chars.next();
1233 len += 1;
1234 }
1235 _ => break,
1236 }
1237 }
1238 if !has_exp_value {
David Tolnay1218e122017-06-01 11:13:45 -07001239 return Err(LexError);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001240 }
1241 }
1242
Nika Layzellf8d5f212017-12-11 14:07:02 -05001243 Ok((input.advance(len), ()))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001244}
1245
Nika Layzellf8d5f212017-12-11 14:07:02 -05001246fn int(input: Cursor) -> PResult<()> {
David Tolnay744a6b82017-06-01 11:34:29 -07001247 let (rest, ()) = digits(input)?;
1248 for suffix in &[
David Tolnay48ea5042018-04-23 19:17:35 -07001249 "isize", "i8", "i16", "i32", "i64", "i128", "usize", "u8", "u16", "u32", "u64", "u128",
David Tolnay744a6b82017-06-01 11:34:29 -07001250 ] {
1251 if rest.starts_with(suffix) {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001252 return word_break(rest.advance(suffix.len()));
David Tolnay744a6b82017-06-01 11:34:29 -07001253 }
1254 }
1255 word_break(rest)
1256}
Alex Crichton44bffbc2017-05-19 17:51:59 -07001257
Nika Layzellf8d5f212017-12-11 14:07:02 -05001258fn digits(mut input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001259 let base = if input.starts_with("0x") {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001260 input = input.advance(2);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001261 16
1262 } else if input.starts_with("0o") {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001263 input = input.advance(2);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001264 8
1265 } else if input.starts_with("0b") {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001266 input = input.advance(2);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001267 2
1268 } else {
1269 10
1270 };
1271
Alex Crichton44bffbc2017-05-19 17:51:59 -07001272 let mut len = 0;
1273 let mut empty = true;
1274 for b in input.bytes() {
1275 let digit = match b {
1276 b'0'...b'9' => (b - b'0') as u64,
1277 b'a'...b'f' => 10 + (b - b'a') as u64,
1278 b'A'...b'F' => 10 + (b - b'A') as u64,
1279 b'_' => {
1280 if empty && base == 10 {
David Tolnay1218e122017-06-01 11:13:45 -07001281 return Err(LexError);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001282 }
1283 len += 1;
1284 continue;
1285 }
1286 _ => break,
1287 };
1288 if digit >= base {
David Tolnay1218e122017-06-01 11:13:45 -07001289 return Err(LexError);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001290 }
Alex Crichton44bffbc2017-05-19 17:51:59 -07001291 len += 1;
1292 empty = false;
1293 }
1294 if empty {
David Tolnay1218e122017-06-01 11:13:45 -07001295 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001296 } else {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001297 Ok((input.advance(len), ()))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001298 }
1299}
1300
Alex Crichtonf3888432018-05-16 09:11:05 -07001301fn op(input: Cursor) -> PResult<Punct> {
David Tolnayea75c5f2017-05-31 23:40:33 -07001302 let input = skip_whitespace(input);
1303 match op_char(input) {
Alex Crichtonf3888432018-05-16 09:11:05 -07001304 Ok((rest, '\'')) => {
1305 symbol(rest)?;
1306 Ok((rest, Punct::new('\'', Spacing::Joint)))
1307 }
David Tolnay1218e122017-06-01 11:13:45 -07001308 Ok((rest, ch)) => {
David Tolnayea75c5f2017-05-31 23:40:33 -07001309 let kind = match op_char(rest) {
Alex Crichton1a7f7622017-07-05 17:47:15 -07001310 Ok(_) => Spacing::Joint,
1311 Err(LexError) => Spacing::Alone,
David Tolnayea75c5f2017-05-31 23:40:33 -07001312 };
Alex Crichtonf3888432018-05-16 09:11:05 -07001313 Ok((rest, Punct::new(ch, kind)))
David Tolnayea75c5f2017-05-31 23:40:33 -07001314 }
David Tolnay1218e122017-06-01 11:13:45 -07001315 Err(LexError) => Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -07001316 }
1317}
1318
Nika Layzellf8d5f212017-12-11 14:07:02 -05001319fn op_char(input: Cursor) -> PResult<char> {
David Tolnay3a592ad2018-04-22 21:20:24 -07001320 if input.starts_with("//") || input.starts_with("/*") {
1321 // Do not accept `/` of a comment as an op.
1322 return Err(LexError);
1323 }
1324
David Tolnayea75c5f2017-05-31 23:40:33 -07001325 let mut chars = input.chars();
1326 let first = match chars.next() {
1327 Some(ch) => ch,
1328 None => {
David Tolnay1218e122017-06-01 11:13:45 -07001329 return Err(LexError);
David Tolnayea75c5f2017-05-31 23:40:33 -07001330 }
1331 };
Alex Crichtonf3888432018-05-16 09:11:05 -07001332 let recognized = "~!@#$%^&*-=+|;:,<.>/?'";
David Tolnayea75c5f2017-05-31 23:40:33 -07001333 if recognized.contains(first) {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001334 Ok((input.advance(first.len_utf8()), first))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001335 } else {
David Tolnay1218e122017-06-01 11:13:45 -07001336 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001337 }
1338}
1339
Alex Crichton1eb96a02018-04-04 13:07:35 -07001340fn doc_comment(input: Cursor) -> PResult<Vec<TokenTree>> {
1341 let mut trees = Vec::new();
1342 let (rest, ((comment, inner), span)) = spanned(input, doc_comment_contents)?;
Alex Crichtonf3888432018-05-16 09:11:05 -07001343 trees.push(TokenTree::Punct(Punct::new('#', Spacing::Alone)));
Alex Crichton1eb96a02018-04-04 13:07:35 -07001344 if inner {
Alex Crichtonf3888432018-05-16 09:11:05 -07001345 trees.push(Punct::new('!', Spacing::Alone).into());
Alex Crichton1eb96a02018-04-04 13:07:35 -07001346 }
1347 let mut stream = vec![
Alex Crichtonf3888432018-05-16 09:11:05 -07001348 TokenTree::Ident(::Ident::new("doc", span)),
1349 TokenTree::Punct(Punct::new('=', Spacing::Alone)),
Alex Crichton1eb96a02018-04-04 13:07:35 -07001350 TokenTree::Literal(::Literal::string(comment)),
1351 ];
1352 for tt in stream.iter_mut() {
1353 tt.set_span(span);
1354 }
David Tolnayf14813f2018-09-08 17:14:07 -07001355 let group = Group::new(Delimiter::Bracket, stream.into_iter().collect());
1356 trees.push(::Group::_new_stable(group).into());
Alex Crichton1eb96a02018-04-04 13:07:35 -07001357 for tt in trees.iter_mut() {
1358 tt.set_span(span);
1359 }
1360 Ok((rest, trees))
1361}
1362
1363named!(doc_comment_contents -> (&str, bool), alt!(
Alex Crichton44bffbc2017-05-19 17:51:59 -07001364 do_parse!(
1365 punct!("//!") >>
Alex Crichton1eb96a02018-04-04 13:07:35 -07001366 s: take_until_newline_or_eof!() >>
1367 ((s, true))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001368 )
1369 |
1370 do_parse!(
1371 option!(whitespace) >>
1372 peek!(tag!("/*!")) >>
Alex Crichton1eb96a02018-04-04 13:07:35 -07001373 s: block_comment >>
1374 ((s, true))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001375 )
1376 |
1377 do_parse!(
1378 punct!("///") >>
1379 not!(tag!("/")) >>
Alex Crichton1eb96a02018-04-04 13:07:35 -07001380 s: take_until_newline_or_eof!() >>
1381 ((s, false))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001382 )
1383 |
1384 do_parse!(
1385 option!(whitespace) >>
1386 peek!(tuple!(tag!("/**"), not!(tag!("*")))) >>
Alex Crichton1eb96a02018-04-04 13:07:35 -07001387 s: block_comment >>
1388 ((s, false))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001389 )
1390));