blob: 7f3cc4e48591bba8520016daab22e053129eb147 [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
David Tolnayfd8cdc82019-01-19 19:23:59 -0800417pub fn debug_span_field_if_nontrivial(debug: &mut fmt::DebugStruct, span: Span) {
418 if cfg!(procmacro2_semver_exempt) {
419 debug.field("span", &span);
420 }
421}
422
Alex Crichtonf3888432018-05-16 09:11:05 -0700423#[derive(Clone)]
David Tolnayf14813f2018-09-08 17:14:07 -0700424pub struct Group {
425 delimiter: Delimiter,
426 stream: TokenStream,
427 span: Span,
428}
429
430impl Group {
431 pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
432 Group {
433 delimiter: delimiter,
434 stream: stream,
435 span: Span::call_site(),
436 }
437 }
438
439 pub fn delimiter(&self) -> Delimiter {
440 self.delimiter
441 }
442
443 pub fn stream(&self) -> TokenStream {
444 self.stream.clone()
445 }
446
447 pub fn span(&self) -> Span {
448 self.span
449 }
450
451 pub fn span_open(&self) -> Span {
452 self.span
453 }
454
455 pub fn span_close(&self) -> Span {
456 self.span
457 }
458
459 pub fn set_span(&mut self, span: Span) {
460 self.span = span;
461 }
462}
463
464impl fmt::Display for Group {
465 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
466 let (left, right) = match self.delimiter {
467 Delimiter::Parenthesis => ("(", ")"),
468 Delimiter::Brace => ("{", "}"),
469 Delimiter::Bracket => ("[", "]"),
470 Delimiter::None => ("", ""),
471 };
472
473 f.write_str(left)?;
474 self.stream.fmt(f)?;
475 f.write_str(right)?;
476
477 Ok(())
478 }
479}
480
481impl fmt::Debug for Group {
482 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
483 let mut debug = fmt.debug_struct("Group");
484 debug.field("delimiter", &self.delimiter);
485 debug.field("stream", &self.stream);
486 #[cfg(procmacro2_semver_exempt)]
487 debug.field("span", &self.span);
488 debug.finish()
489 }
490}
491
492#[derive(Clone)]
Alex Crichtonf3888432018-05-16 09:11:05 -0700493pub struct Ident {
David Tolnayc2309ca2018-06-02 15:47:57 -0700494 sym: String,
Alex Crichtonb2c94622018-04-04 07:36:41 -0700495 span: Span,
Alex Crichtonf3888432018-05-16 09:11:05 -0700496 raw: bool,
David Tolnay041bcd42017-06-03 09:18:04 -0700497}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700498
Alex Crichtonf3888432018-05-16 09:11:05 -0700499impl Ident {
500 fn _new(string: &str, raw: bool, span: Span) -> Ident {
David Tolnay489c6422018-04-07 08:37:28 -0700501 validate_term(string);
502
Alex Crichtonf3888432018-05-16 09:11:05 -0700503 Ident {
David Tolnayc2309ca2018-06-02 15:47:57 -0700504 sym: string.to_owned(),
Alex Crichtona914a612018-04-04 07:48:44 -0700505 span: span,
Alex Crichtonf3888432018-05-16 09:11:05 -0700506 raw: raw,
David Tolnay041bcd42017-06-03 09:18:04 -0700507 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700508 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700509
Alex Crichtonf3888432018-05-16 09:11:05 -0700510 pub fn new(string: &str, span: Span) -> Ident {
511 Ident::_new(string, false, span)
512 }
513
514 pub fn new_raw(string: &str, span: Span) -> Ident {
515 Ident::_new(string, true, span)
516 }
517
Alex Crichtonb2c94622018-04-04 07:36:41 -0700518 pub fn span(&self) -> Span {
519 self.span
520 }
521
522 pub fn set_span(&mut self, span: Span) {
523 self.span = span;
524 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700525}
526
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000527#[inline]
528fn is_ident_start(c: char) -> bool {
David Tolnay03b43da2018-06-02 15:25:57 -0700529 ('a' <= c && c <= 'z')
530 || ('A' <= c && c <= 'Z')
531 || c == '_'
532 || (c > '\x7f' && UnicodeXID::is_xid_start(c))
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000533}
534
535#[inline]
536fn is_ident_continue(c: char) -> bool {
David Tolnay03b43da2018-06-02 15:25:57 -0700537 ('a' <= c && c <= 'z')
538 || ('A' <= c && c <= 'Z')
539 || c == '_'
540 || ('0' <= c && c <= '9')
541 || (c > '\x7f' && UnicodeXID::is_xid_continue(c))
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000542}
543
David Tolnay489c6422018-04-07 08:37:28 -0700544fn validate_term(string: &str) {
Alex Crichtonf3888432018-05-16 09:11:05 -0700545 let validate = string;
David Tolnay489c6422018-04-07 08:37:28 -0700546 if validate.is_empty() {
Alex Crichtonf3888432018-05-16 09:11:05 -0700547 panic!("Ident is not allowed to be empty; use Option<Ident>");
David Tolnay489c6422018-04-07 08:37:28 -0700548 }
549
550 if validate.bytes().all(|digit| digit >= b'0' && digit <= b'9') {
Alex Crichtonf3888432018-05-16 09:11:05 -0700551 panic!("Ident cannot be a number; use Literal instead");
David Tolnay489c6422018-04-07 08:37:28 -0700552 }
553
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000554 fn ident_ok(string: &str) -> bool {
David Tolnay489c6422018-04-07 08:37:28 -0700555 let mut chars = string.chars();
556 let first = chars.next().unwrap();
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000557 if !is_ident_start(first) {
David Tolnay489c6422018-04-07 08:37:28 -0700558 return false;
559 }
560 for ch in chars {
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000561 if !is_ident_continue(ch) {
David Tolnay489c6422018-04-07 08:37:28 -0700562 return false;
563 }
564 }
565 true
566 }
567
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000568 if !ident_ok(validate) {
Alex Crichtonf3888432018-05-16 09:11:05 -0700569 panic!("{:?} is not a valid Ident", string);
David Tolnay489c6422018-04-07 08:37:28 -0700570 }
571}
572
David Tolnayc0b0f2e2018-09-02 17:56:08 -0700573impl PartialEq for Ident {
574 fn eq(&self, other: &Ident) -> bool {
575 self.sym == other.sym && self.raw == other.raw
576 }
577}
578
579impl<T> PartialEq<T> for Ident
580where
581 T: ?Sized + AsRef<str>,
582{
583 fn eq(&self, other: &T) -> bool {
584 let other = other.as_ref();
585 if self.raw {
586 other.starts_with("r#") && self.sym == other[2..]
587 } else {
588 self.sym == other
589 }
590 }
591}
592
Alex Crichtonf3888432018-05-16 09:11:05 -0700593impl fmt::Display for Ident {
David Tolnay8ad3e3e2017-06-03 16:45:00 -0700594 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Alex Crichtonf3888432018-05-16 09:11:05 -0700595 if self.raw {
596 "r#".fmt(f)?;
597 }
David Tolnayc2309ca2018-06-02 15:47:57 -0700598 self.sym.fmt(f)
Alex Crichtonf3888432018-05-16 09:11:05 -0700599 }
600}
601
602impl fmt::Debug for Ident {
David Tolnayd8fcdb82018-06-02 15:43:53 -0700603 // Ident(proc_macro), Ident(r#union)
604 #[cfg(not(procmacro2_semver_exempt))]
605 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
606 let mut debug = f.debug_tuple("Ident");
607 debug.field(&format_args!("{}", self));
608 debug.finish()
609 }
610
611 // Ident {
612 // sym: proc_macro,
613 // span: bytes(128..138)
614 // }
615 #[cfg(procmacro2_semver_exempt)]
Alex Crichtonf3888432018-05-16 09:11:05 -0700616 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
617 let mut debug = f.debug_struct("Ident");
David Tolnayd8fcdb82018-06-02 15:43:53 -0700618 debug.field("sym", &format_args!("{}", self));
David Tolnay034205f2018-04-22 16:45:28 -0700619 debug.field("span", &self.span);
620 debug.finish()
David Tolnay8ad3e3e2017-06-03 16:45:00 -0700621 }
622}
623
David Tolnay034205f2018-04-22 16:45:28 -0700624#[derive(Clone)]
Alex Crichtonb2c94622018-04-04 07:36:41 -0700625pub struct Literal {
626 text: String,
627 span: Span,
628}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700629
Alex Crichtona914a612018-04-04 07:48:44 -0700630macro_rules! suffixed_numbers {
631 ($($name:ident => $kind:ident,)*) => ($(
632 pub fn $name(n: $kind) -> Literal {
633 Literal::_new(format!(concat!("{}", stringify!($kind)), n))
634 }
635 )*)
636}
637
638macro_rules! unsuffixed_numbers {
639 ($($name:ident => $kind:ident,)*) => ($(
640 pub fn $name(n: $kind) -> Literal {
641 Literal::_new(n.to_string())
642 }
643 )*)
644}
645
Alex Crichton852d53d2017-05-19 19:25:08 -0700646impl Literal {
Alex Crichtonb2c94622018-04-04 07:36:41 -0700647 fn _new(text: String) -> Literal {
648 Literal {
Alex Crichtona914a612018-04-04 07:48:44 -0700649 text: text,
Alex Crichtonb2c94622018-04-04 07:36:41 -0700650 span: Span::call_site(),
651 }
652 }
653
Alex Crichtona914a612018-04-04 07:48:44 -0700654 suffixed_numbers! {
655 u8_suffixed => u8,
656 u16_suffixed => u16,
657 u32_suffixed => u32,
658 u64_suffixed => u64,
659 usize_suffixed => usize,
660 i8_suffixed => i8,
661 i16_suffixed => i16,
662 i32_suffixed => i32,
663 i64_suffixed => i64,
664 isize_suffixed => isize,
665
666 f32_suffixed => f32,
667 f64_suffixed => f64,
668 }
669
Alex Crichton69385662018-11-08 06:30:04 -0800670 #[cfg(u128)]
671 suffixed_numbers! {
672 u128_suffixed => u128,
673 i128_suffixed => i128,
674 }
675
Alex Crichtona914a612018-04-04 07:48:44 -0700676 unsuffixed_numbers! {
677 u8_unsuffixed => u8,
678 u16_unsuffixed => u16,
679 u32_unsuffixed => u32,
680 u64_unsuffixed => u64,
681 usize_unsuffixed => usize,
682 i8_unsuffixed => i8,
683 i16_unsuffixed => i16,
684 i32_unsuffixed => i32,
685 i64_unsuffixed => i64,
686 isize_unsuffixed => isize,
687 }
688
Alex Crichton69385662018-11-08 06:30:04 -0800689 #[cfg(u128)]
690 unsuffixed_numbers! {
691 u128_unsuffixed => u128,
692 i128_unsuffixed => i128,
693 }
694
Alex Crichtona914a612018-04-04 07:48:44 -0700695 pub fn f32_unsuffixed(f: f32) -> Literal {
696 let mut s = f.to_string();
697 if !s.contains(".") {
698 s.push_str(".0");
Alex Crichton76a5cc82017-05-23 07:01:44 -0700699 }
Alex Crichtona914a612018-04-04 07:48:44 -0700700 Literal::_new(s)
701 }
702
703 pub fn f64_unsuffixed(f: f64) -> Literal {
704 let mut s = f.to_string();
705 if !s.contains(".") {
706 s.push_str(".0");
707 }
708 Literal::_new(s)
709 }
710
711 pub fn string(t: &str) -> Literal {
David Tolnay3d9d6ad2018-05-18 10:51:55 -0700712 let mut s = t
713 .chars()
Alex Crichtona914a612018-04-04 07:48:44 -0700714 .flat_map(|c| c.escape_default())
715 .collect::<String>();
716 s.push('"');
717 s.insert(0, '"');
718 Literal::_new(s)
719 }
720
721 pub fn character(t: char) -> Literal {
722 Literal::_new(format!("'{}'", t.escape_default().collect::<String>()))
Alex Crichton76a5cc82017-05-23 07:01:44 -0700723 }
724
Alex Crichton9c2fb0a2017-05-26 08:49:31 -0700725 pub fn byte_string(bytes: &[u8]) -> Literal {
Alex Crichton852d53d2017-05-19 19:25:08 -0700726 let mut escaped = "b\"".to_string();
727 for b in bytes {
728 match *b {
729 b'\0' => escaped.push_str(r"\0"),
730 b'\t' => escaped.push_str(r"\t"),
731 b'\n' => escaped.push_str(r"\n"),
732 b'\r' => escaped.push_str(r"\r"),
733 b'"' => escaped.push_str("\\\""),
734 b'\\' => escaped.push_str("\\\\"),
David Tolnayb28f38a2018-03-31 22:02:29 +0200735 b'\x20'...b'\x7E' => escaped.push(*b as char),
Alex Crichton852d53d2017-05-19 19:25:08 -0700736 _ => escaped.push_str(&format!("\\x{:02X}", b)),
737 }
738 }
739 escaped.push('"');
Alex Crichtonb2c94622018-04-04 07:36:41 -0700740 Literal::_new(escaped)
Alex Crichton76a5cc82017-05-23 07:01:44 -0700741 }
Alex Crichton9c2fb0a2017-05-26 08:49:31 -0700742
Alex Crichtonb2c94622018-04-04 07:36:41 -0700743 pub fn span(&self) -> Span {
744 self.span
Alex Crichton31316622017-05-26 12:54:47 -0700745 }
746
Alex Crichtonb2c94622018-04-04 07:36:41 -0700747 pub fn set_span(&mut self, span: Span) {
748 self.span = span;
Alex Crichton31316622017-05-26 12:54:47 -0700749 }
Alex Crichton852d53d2017-05-19 19:25:08 -0700750}
751
Alex Crichton44bffbc2017-05-19 17:51:59 -0700752impl fmt::Display for Literal {
753 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Alex Crichtonb2c94622018-04-04 07:36:41 -0700754 self.text.fmt(f)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700755 }
756}
757
David Tolnay034205f2018-04-22 16:45:28 -0700758impl fmt::Debug for Literal {
759 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
760 let mut debug = fmt.debug_struct("Literal");
761 debug.field("lit", &format_args!("{}", self.text));
762 #[cfg(procmacro2_semver_exempt)]
763 debug.field("span", &self.span);
764 debug.finish()
765 }
766}
767
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700768fn token_stream(mut input: Cursor) -> PResult<TokenStream> {
Alex Crichton1eb96a02018-04-04 13:07:35 -0700769 let mut trees = Vec::new();
770 loop {
771 let input_no_ws = skip_whitespace(input);
772 if input_no_ws.rest.len() == 0 {
David Tolnay48ea5042018-04-23 19:17:35 -0700773 break;
Alex Crichton1eb96a02018-04-04 13:07:35 -0700774 }
775 if let Ok((a, tokens)) = doc_comment(input_no_ws) {
776 input = a;
777 trees.extend(tokens);
David Tolnay48ea5042018-04-23 19:17:35 -0700778 continue;
Alex Crichton1eb96a02018-04-04 13:07:35 -0700779 }
780
781 let (a, tt) = match token_tree(input_no_ws) {
782 Ok(p) => p,
783 Err(_) => break,
784 };
785 trees.push(tt);
786 input = a;
787 }
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700788 Ok((input, TokenStream { inner: trees }))
Alex Crichton1eb96a02018-04-04 13:07:35 -0700789}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700790
David Tolnay1ebe3972018-01-02 20:14:20 -0800791#[cfg(not(procmacro2_semver_exempt))]
Alex Crichton1eb96a02018-04-04 13:07:35 -0700792fn spanned<'a, T>(
793 input: Cursor<'a>,
794 f: fn(Cursor<'a>) -> PResult<'a, T>,
795) -> PResult<'a, (T, ::Span)> {
796 let (a, b) = f(skip_whitespace(input))?;
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700797 Ok((a, ((b, ::Span::_new_stable(Span {})))))
David Tolnayddfca052017-12-31 10:41:24 -0500798}
799
David Tolnay1ebe3972018-01-02 20:14:20 -0800800#[cfg(procmacro2_semver_exempt)]
Alex Crichton1eb96a02018-04-04 13:07:35 -0700801fn spanned<'a, T>(
802 input: Cursor<'a>,
803 f: fn(Cursor<'a>) -> PResult<'a, T>,
804) -> PResult<'a, (T, ::Span)> {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500805 let input = skip_whitespace(input);
806 let lo = input.off;
Alex Crichton1eb96a02018-04-04 13:07:35 -0700807 let (a, b) = f(input)?;
808 let hi = a.off;
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700809 let span = ::Span::_new_stable(Span { lo: lo, hi: hi });
Alex Crichton1eb96a02018-04-04 13:07:35 -0700810 Ok((a, (b, span)))
811}
812
813fn token_tree(input: Cursor) -> PResult<TokenTree> {
814 let (rest, (mut tt, span)) = spanned(input, token_kind)?;
815 tt.set_span(span);
816 Ok((rest, tt))
Nika Layzellf8d5f212017-12-11 14:07:02 -0500817}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700818
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700819named!(token_kind -> TokenTree, alt!(
David Tolnayf14813f2018-09-08 17:14:07 -0700820 map!(group, |g| TokenTree::Group(::Group::_new_stable(g)))
Alex Crichton44bffbc2017-05-19 17:51:59 -0700821 |
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700822 map!(literal, |l| TokenTree::Literal(::Literal::_new_stable(l))) // must be before symbol
Alex Crichton44bffbc2017-05-19 17:51:59 -0700823 |
Alex Crichtonf3888432018-05-16 09:11:05 -0700824 map!(op, TokenTree::Punct)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700825 |
Alex Crichtonf3888432018-05-16 09:11:05 -0700826 symbol_leading_ws
Alex Crichton44bffbc2017-05-19 17:51:59 -0700827));
828
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700829named!(group -> Group, alt!(
Alex Crichton44bffbc2017-05-19 17:51:59 -0700830 delimited!(
831 punct!("("),
832 token_stream,
833 punct!(")")
David Tolnayf14813f2018-09-08 17:14:07 -0700834 ) => { |ts| Group::new(Delimiter::Parenthesis, 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::Bracket, ts) }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700841 |
842 delimited!(
843 punct!("{"),
844 token_stream,
845 punct!("}")
David Tolnayf14813f2018-09-08 17:14:07 -0700846 ) => { |ts| Group::new(Delimiter::Brace, ts) }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700847));
848
Alex Crichtonf3888432018-05-16 09:11:05 -0700849fn symbol_leading_ws(input: Cursor) -> PResult<TokenTree> {
850 symbol(skip_whitespace(input))
851}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700852
Alex Crichtonf3888432018-05-16 09:11:05 -0700853fn symbol(input: Cursor) -> PResult<TokenTree> {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700854 let mut chars = input.char_indices();
David Tolnaya202d502017-06-01 12:26:55 -0700855
Alex Crichtonf3888432018-05-16 09:11:05 -0700856 let raw = input.starts_with("r#");
David Tolnaya13d1422018-03-31 21:27:48 +0200857 if raw {
858 chars.next();
859 chars.next();
860 }
861
Alex Crichton44bffbc2017-05-19 17:51:59 -0700862 match chars.next() {
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000863 Some((_, ch)) if is_ident_start(ch) => {}
David Tolnay1218e122017-06-01 11:13:45 -0700864 _ => return Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -0700865 }
866
David Tolnay214c94c2017-06-01 12:42:56 -0700867 let mut end = input.len();
Alex Crichton44bffbc2017-05-19 17:51:59 -0700868 for (i, ch) in chars {
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000869 if !is_ident_continue(ch) {
David Tolnay214c94c2017-06-01 12:42:56 -0700870 end = i;
871 break;
Alex Crichton44bffbc2017-05-19 17:51:59 -0700872 }
873 }
874
David Tolnaya13d1422018-03-31 21:27:48 +0200875 let a = &input.rest[..end];
Alex Crichtonf3888432018-05-16 09:11:05 -0700876 if a == "r#_" {
David Tolnay214c94c2017-06-01 12:42:56 -0700877 Err(LexError)
878 } else {
Alex Crichtonf3888432018-05-16 09:11:05 -0700879 let ident = if raw {
880 ::Ident::_new_raw(&a[2..], ::Span::call_site())
881 } else {
882 ::Ident::new(a, ::Span::call_site())
883 };
884 Ok((input.advance(end), ident.into()))
David Tolnay214c94c2017-06-01 12:42:56 -0700885 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700886}
887
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700888fn literal(input: Cursor) -> PResult<Literal> {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700889 let input_no_ws = skip_whitespace(input);
890
891 match literal_nocapture(input_no_ws) {
David Tolnay1218e122017-06-01 11:13:45 -0700892 Ok((a, ())) => {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700893 let start = input.len() - input_no_ws.len();
894 let len = input_no_ws.len() - a.len();
895 let end = start + len;
David Tolnay3d9d6ad2018-05-18 10:51:55 -0700896 Ok((a, Literal::_new(input.rest[start..end].to_string())))
Alex Crichton44bffbc2017-05-19 17:51:59 -0700897 }
David Tolnay1218e122017-06-01 11:13:45 -0700898 Err(LexError) => Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -0700899 }
900}
901
902named!(literal_nocapture -> (), alt!(
903 string
904 |
905 byte_string
906 |
907 byte
908 |
909 character
910 |
911 float
912 |
913 int
Alex Crichton44bffbc2017-05-19 17:51:59 -0700914));
915
916named!(string -> (), alt!(
917 quoted_string
918 |
919 preceded!(
920 punct!("r"),
921 raw_string
922 ) => { |_| () }
923));
924
925named!(quoted_string -> (), delimited!(
926 punct!("\""),
927 cooked_string,
928 tag!("\"")
929));
930
Nika Layzellf8d5f212017-12-11 14:07:02 -0500931fn cooked_string(input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700932 let mut chars = input.char_indices().peekable();
933 while let Some((byte_offset, ch)) = chars.next() {
934 match ch {
935 '"' => {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500936 return Ok((input.advance(byte_offset), ()));
Alex Crichton44bffbc2017-05-19 17:51:59 -0700937 }
938 '\r' => {
939 if let Some((_, '\n')) = chars.next() {
940 // ...
941 } else {
942 break;
943 }
944 }
David Tolnayb28f38a2018-03-31 22:02:29 +0200945 '\\' => match chars.next() {
946 Some((_, 'x')) => {
947 if !backslash_x_char(&mut chars) {
948 break;
Alex Crichton44bffbc2017-05-19 17:51:59 -0700949 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700950 }
David Tolnayb28f38a2018-03-31 22:02:29 +0200951 Some((_, 'n')) | Some((_, 'r')) | Some((_, 't')) | Some((_, '\\'))
952 | Some((_, '\'')) | Some((_, '"')) | Some((_, '0')) => {}
953 Some((_, 'u')) => {
954 if !backslash_u(&mut chars) {
955 break;
956 }
957 }
958 Some((_, '\n')) | Some((_, '\r')) => {
959 while let Some(&(_, ch)) = chars.peek() {
960 if ch.is_whitespace() {
961 chars.next();
962 } else {
963 break;
964 }
965 }
966 }
967 _ => break,
968 },
Alex Crichton44bffbc2017-05-19 17:51:59 -0700969 _ch => {}
970 }
971 }
David Tolnay1218e122017-06-01 11:13:45 -0700972 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700973}
974
975named!(byte_string -> (), alt!(
976 delimited!(
977 punct!("b\""),
978 cooked_byte_string,
979 tag!("\"")
980 ) => { |_| () }
981 |
982 preceded!(
983 punct!("br"),
984 raw_string
985 ) => { |_| () }
986));
987
Nika Layzellf8d5f212017-12-11 14:07:02 -0500988fn cooked_byte_string(mut input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700989 let mut bytes = input.bytes().enumerate();
990 'outer: while let Some((offset, b)) = bytes.next() {
991 match b {
992 b'"' => {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500993 return Ok((input.advance(offset), ()));
Alex Crichton44bffbc2017-05-19 17:51:59 -0700994 }
995 b'\r' => {
996 if let Some((_, b'\n')) = bytes.next() {
997 // ...
998 } else {
999 break;
1000 }
1001 }
David Tolnayb28f38a2018-03-31 22:02:29 +02001002 b'\\' => match bytes.next() {
1003 Some((_, b'x')) => {
1004 if !backslash_x_byte(&mut bytes) {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001005 break;
1006 }
Alex Crichton44bffbc2017-05-19 17:51:59 -07001007 }
David Tolnayb28f38a2018-03-31 22:02:29 +02001008 Some((_, b'n')) | Some((_, b'r')) | Some((_, b't')) | Some((_, b'\\'))
1009 | Some((_, b'0')) | Some((_, b'\'')) | Some((_, b'"')) => {}
1010 Some((newline, b'\n')) | Some((newline, b'\r')) => {
1011 let rest = input.advance(newline + 1);
1012 for (offset, ch) in rest.char_indices() {
1013 if !ch.is_whitespace() {
1014 input = rest.advance(offset);
1015 bytes = input.bytes().enumerate();
1016 continue 'outer;
1017 }
1018 }
1019 break;
1020 }
1021 _ => break,
1022 },
Alex Crichton44bffbc2017-05-19 17:51:59 -07001023 b if b < 0x80 => {}
1024 _ => break,
1025 }
1026 }
David Tolnay1218e122017-06-01 11:13:45 -07001027 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001028}
1029
Nika Layzellf8d5f212017-12-11 14:07:02 -05001030fn raw_string(input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001031 let mut chars = input.char_indices();
1032 let mut n = 0;
1033 while let Some((byte_offset, ch)) = chars.next() {
1034 match ch {
1035 '"' => {
1036 n = byte_offset;
1037 break;
1038 }
1039 '#' => {}
David Tolnay1218e122017-06-01 11:13:45 -07001040 _ => return Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -07001041 }
1042 }
1043 for (byte_offset, ch) in chars {
1044 match ch {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001045 '"' if input.advance(byte_offset + 1).starts_with(&input.rest[..n]) => {
1046 let rest = input.advance(byte_offset + 1 + n);
David Tolnayb28f38a2018-03-31 22:02:29 +02001047 return Ok((rest, ()));
Alex Crichton44bffbc2017-05-19 17:51:59 -07001048 }
1049 '\r' => {}
1050 _ => {}
1051 }
1052 }
David Tolnay1218e122017-06-01 11:13:45 -07001053 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001054}
1055
1056named!(byte -> (), do_parse!(
1057 punct!("b") >>
1058 tag!("'") >>
1059 cooked_byte >>
1060 tag!("'") >>
1061 (())
1062));
1063
Nika Layzellf8d5f212017-12-11 14:07:02 -05001064fn cooked_byte(input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001065 let mut bytes = input.bytes().enumerate();
1066 let ok = match bytes.next().map(|(_, b)| b) {
David Tolnayb28f38a2018-03-31 22:02:29 +02001067 Some(b'\\') => match bytes.next().map(|(_, b)| b) {
1068 Some(b'x') => backslash_x_byte(&mut bytes),
1069 Some(b'n') | Some(b'r') | Some(b't') | Some(b'\\') | Some(b'0') | Some(b'\'')
1070 | Some(b'"') => true,
1071 _ => false,
1072 },
Alex Crichton44bffbc2017-05-19 17:51:59 -07001073 b => b.is_some(),
1074 };
1075 if ok {
1076 match bytes.next() {
Alex Crichton8c030332018-01-16 08:07:36 -08001077 Some((offset, _)) => {
1078 if input.chars().as_str().is_char_boundary(offset) {
1079 Ok((input.advance(offset), ()))
1080 } else {
1081 Err(LexError)
1082 }
1083 }
Nika Layzellf8d5f212017-12-11 14:07:02 -05001084 None => Ok((input.advance(input.len()), ())),
Alex Crichton44bffbc2017-05-19 17:51:59 -07001085 }
1086 } else {
David Tolnay1218e122017-06-01 11:13:45 -07001087 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001088 }
1089}
1090
1091named!(character -> (), do_parse!(
1092 punct!("'") >>
1093 cooked_char >>
1094 tag!("'") >>
1095 (())
1096));
1097
Nika Layzellf8d5f212017-12-11 14:07:02 -05001098fn cooked_char(input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001099 let mut chars = input.char_indices();
1100 let ok = match chars.next().map(|(_, ch)| ch) {
David Tolnayb28f38a2018-03-31 22:02:29 +02001101 Some('\\') => match chars.next().map(|(_, ch)| ch) {
1102 Some('x') => backslash_x_char(&mut chars),
1103 Some('u') => backslash_u(&mut chars),
1104 Some('n') | Some('r') | Some('t') | Some('\\') | Some('0') | Some('\'') | Some('"') => {
1105 true
Alex Crichton44bffbc2017-05-19 17:51:59 -07001106 }
David Tolnayb28f38a2018-03-31 22:02:29 +02001107 _ => false,
1108 },
Alex Crichton44bffbc2017-05-19 17:51:59 -07001109 ch => ch.is_some(),
1110 };
1111 if ok {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001112 match chars.next() {
1113 Some((idx, _)) => Ok((input.advance(idx), ())),
1114 None => Ok((input.advance(input.len()), ())),
1115 }
Alex Crichton44bffbc2017-05-19 17:51:59 -07001116 } else {
David Tolnay1218e122017-06-01 11:13:45 -07001117 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001118 }
1119}
1120
1121macro_rules! next_ch {
1122 ($chars:ident @ $pat:pat $(| $rest:pat)*) => {
1123 match $chars.next() {
1124 Some((_, ch)) => match ch {
1125 $pat $(| $rest)* => ch,
1126 _ => return false,
1127 },
1128 None => return false
1129 }
1130 };
1131}
1132
1133fn backslash_x_char<I>(chars: &mut I) -> bool
David Tolnayb28f38a2018-03-31 22:02:29 +02001134where
1135 I: Iterator<Item = (usize, char)>,
Alex Crichton44bffbc2017-05-19 17:51:59 -07001136{
1137 next_ch!(chars @ '0'...'7');
1138 next_ch!(chars @ '0'...'9' | 'a'...'f' | 'A'...'F');
1139 true
1140}
1141
1142fn backslash_x_byte<I>(chars: &mut I) -> bool
David Tolnayb28f38a2018-03-31 22:02:29 +02001143where
1144 I: Iterator<Item = (usize, u8)>,
Alex Crichton44bffbc2017-05-19 17:51:59 -07001145{
1146 next_ch!(chars @ b'0'...b'9' | b'a'...b'f' | b'A'...b'F');
1147 next_ch!(chars @ b'0'...b'9' | b'a'...b'f' | b'A'...b'F');
1148 true
1149}
1150
1151fn backslash_u<I>(chars: &mut I) -> bool
David Tolnayb28f38a2018-03-31 22:02:29 +02001152where
1153 I: Iterator<Item = (usize, char)>,
Alex Crichton44bffbc2017-05-19 17:51:59 -07001154{
1155 next_ch!(chars @ '{');
1156 next_ch!(chars @ '0'...'9' | 'a'...'f' | 'A'...'F');
David Tolnay8d109342017-12-25 18:24:45 -05001157 loop {
1158 let c = next_ch!(chars @ '0'...'9' | 'a'...'f' | 'A'...'F' | '_' | '}');
1159 if c == '}' {
1160 return true;
1161 }
Alex Crichton44bffbc2017-05-19 17:51:59 -07001162 }
Alex Crichton44bffbc2017-05-19 17:51:59 -07001163}
1164
Nika Layzellf8d5f212017-12-11 14:07:02 -05001165fn float(input: Cursor) -> PResult<()> {
David Tolnay744a6b82017-06-01 11:34:29 -07001166 let (rest, ()) = float_digits(input)?;
1167 for suffix in &["f32", "f64"] {
1168 if rest.starts_with(suffix) {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001169 return word_break(rest.advance(suffix.len()));
David Tolnay744a6b82017-06-01 11:34:29 -07001170 }
1171 }
1172 word_break(rest)
1173}
Alex Crichton44bffbc2017-05-19 17:51:59 -07001174
Nika Layzellf8d5f212017-12-11 14:07:02 -05001175fn float_digits(input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001176 let mut chars = input.chars().peekable();
1177 match chars.next() {
1178 Some(ch) if ch >= '0' && ch <= '9' => {}
David Tolnay1218e122017-06-01 11:13:45 -07001179 _ => return Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -07001180 }
1181
1182 let mut len = 1;
1183 let mut has_dot = false;
1184 let mut has_exp = false;
1185 while let Some(&ch) = chars.peek() {
1186 match ch {
1187 '0'...'9' | '_' => {
1188 chars.next();
1189 len += 1;
1190 }
1191 '.' => {
1192 if has_dot {
1193 break;
1194 }
1195 chars.next();
David Tolnayb28f38a2018-03-31 22:02:29 +02001196 if chars
1197 .peek()
1198 .map(|&ch| ch == '.' || UnicodeXID::is_xid_start(ch))
1199 .unwrap_or(false)
1200 {
David Tolnay1218e122017-06-01 11:13:45 -07001201 return Err(LexError);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001202 }
1203 len += 1;
1204 has_dot = true;
1205 }
1206 'e' | 'E' => {
1207 chars.next();
1208 len += 1;
1209 has_exp = true;
1210 break;
1211 }
1212 _ => break,
1213 }
1214 }
1215
Nika Layzellf8d5f212017-12-11 14:07:02 -05001216 let rest = input.advance(len);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001217 if !(has_dot || has_exp || rest.starts_with("f32") || rest.starts_with("f64")) {
David Tolnay1218e122017-06-01 11:13:45 -07001218 return Err(LexError);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001219 }
1220
1221 if has_exp {
1222 let mut has_exp_value = false;
1223 while let Some(&ch) = chars.peek() {
1224 match ch {
1225 '+' | '-' => {
1226 if has_exp_value {
1227 break;
1228 }
1229 chars.next();
1230 len += 1;
1231 }
1232 '0'...'9' => {
1233 chars.next();
1234 len += 1;
1235 has_exp_value = true;
1236 }
1237 '_' => {
1238 chars.next();
1239 len += 1;
1240 }
1241 _ => break,
1242 }
1243 }
1244 if !has_exp_value {
David Tolnay1218e122017-06-01 11:13:45 -07001245 return Err(LexError);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001246 }
1247 }
1248
Nika Layzellf8d5f212017-12-11 14:07:02 -05001249 Ok((input.advance(len), ()))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001250}
1251
Nika Layzellf8d5f212017-12-11 14:07:02 -05001252fn int(input: Cursor) -> PResult<()> {
David Tolnay744a6b82017-06-01 11:34:29 -07001253 let (rest, ()) = digits(input)?;
1254 for suffix in &[
David Tolnay48ea5042018-04-23 19:17:35 -07001255 "isize", "i8", "i16", "i32", "i64", "i128", "usize", "u8", "u16", "u32", "u64", "u128",
David Tolnay744a6b82017-06-01 11:34:29 -07001256 ] {
1257 if rest.starts_with(suffix) {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001258 return word_break(rest.advance(suffix.len()));
David Tolnay744a6b82017-06-01 11:34:29 -07001259 }
1260 }
1261 word_break(rest)
1262}
Alex Crichton44bffbc2017-05-19 17:51:59 -07001263
Nika Layzellf8d5f212017-12-11 14:07:02 -05001264fn digits(mut input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001265 let base = if input.starts_with("0x") {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001266 input = input.advance(2);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001267 16
1268 } else if input.starts_with("0o") {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001269 input = input.advance(2);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001270 8
1271 } else if input.starts_with("0b") {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001272 input = input.advance(2);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001273 2
1274 } else {
1275 10
1276 };
1277
Alex Crichton44bffbc2017-05-19 17:51:59 -07001278 let mut len = 0;
1279 let mut empty = true;
1280 for b in input.bytes() {
1281 let digit = match b {
1282 b'0'...b'9' => (b - b'0') as u64,
1283 b'a'...b'f' => 10 + (b - b'a') as u64,
1284 b'A'...b'F' => 10 + (b - b'A') as u64,
1285 b'_' => {
1286 if empty && base == 10 {
David Tolnay1218e122017-06-01 11:13:45 -07001287 return Err(LexError);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001288 }
1289 len += 1;
1290 continue;
1291 }
1292 _ => break,
1293 };
1294 if digit >= base {
David Tolnay1218e122017-06-01 11:13:45 -07001295 return Err(LexError);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001296 }
Alex Crichton44bffbc2017-05-19 17:51:59 -07001297 len += 1;
1298 empty = false;
1299 }
1300 if empty {
David Tolnay1218e122017-06-01 11:13:45 -07001301 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001302 } else {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001303 Ok((input.advance(len), ()))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001304 }
1305}
1306
Alex Crichtonf3888432018-05-16 09:11:05 -07001307fn op(input: Cursor) -> PResult<Punct> {
David Tolnayea75c5f2017-05-31 23:40:33 -07001308 let input = skip_whitespace(input);
1309 match op_char(input) {
Alex Crichtonf3888432018-05-16 09:11:05 -07001310 Ok((rest, '\'')) => {
1311 symbol(rest)?;
1312 Ok((rest, Punct::new('\'', Spacing::Joint)))
1313 }
David Tolnay1218e122017-06-01 11:13:45 -07001314 Ok((rest, ch)) => {
David Tolnayea75c5f2017-05-31 23:40:33 -07001315 let kind = match op_char(rest) {
Alex Crichton1a7f7622017-07-05 17:47:15 -07001316 Ok(_) => Spacing::Joint,
1317 Err(LexError) => Spacing::Alone,
David Tolnayea75c5f2017-05-31 23:40:33 -07001318 };
Alex Crichtonf3888432018-05-16 09:11:05 -07001319 Ok((rest, Punct::new(ch, kind)))
David Tolnayea75c5f2017-05-31 23:40:33 -07001320 }
David Tolnay1218e122017-06-01 11:13:45 -07001321 Err(LexError) => Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -07001322 }
1323}
1324
Nika Layzellf8d5f212017-12-11 14:07:02 -05001325fn op_char(input: Cursor) -> PResult<char> {
David Tolnay3a592ad2018-04-22 21:20:24 -07001326 if input.starts_with("//") || input.starts_with("/*") {
1327 // Do not accept `/` of a comment as an op.
1328 return Err(LexError);
1329 }
1330
David Tolnayea75c5f2017-05-31 23:40:33 -07001331 let mut chars = input.chars();
1332 let first = match chars.next() {
1333 Some(ch) => ch,
1334 None => {
David Tolnay1218e122017-06-01 11:13:45 -07001335 return Err(LexError);
David Tolnayea75c5f2017-05-31 23:40:33 -07001336 }
1337 };
Alex Crichtonf3888432018-05-16 09:11:05 -07001338 let recognized = "~!@#$%^&*-=+|;:,<.>/?'";
David Tolnayea75c5f2017-05-31 23:40:33 -07001339 if recognized.contains(first) {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001340 Ok((input.advance(first.len_utf8()), first))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001341 } else {
David Tolnay1218e122017-06-01 11:13:45 -07001342 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001343 }
1344}
1345
Alex Crichton1eb96a02018-04-04 13:07:35 -07001346fn doc_comment(input: Cursor) -> PResult<Vec<TokenTree>> {
1347 let mut trees = Vec::new();
1348 let (rest, ((comment, inner), span)) = spanned(input, doc_comment_contents)?;
Alex Crichtonf3888432018-05-16 09:11:05 -07001349 trees.push(TokenTree::Punct(Punct::new('#', Spacing::Alone)));
Alex Crichton1eb96a02018-04-04 13:07:35 -07001350 if inner {
Alex Crichtonf3888432018-05-16 09:11:05 -07001351 trees.push(Punct::new('!', Spacing::Alone).into());
Alex Crichton1eb96a02018-04-04 13:07:35 -07001352 }
1353 let mut stream = vec![
Alex Crichtonf3888432018-05-16 09:11:05 -07001354 TokenTree::Ident(::Ident::new("doc", span)),
1355 TokenTree::Punct(Punct::new('=', Spacing::Alone)),
Alex Crichton1eb96a02018-04-04 13:07:35 -07001356 TokenTree::Literal(::Literal::string(comment)),
1357 ];
1358 for tt in stream.iter_mut() {
1359 tt.set_span(span);
1360 }
David Tolnayf14813f2018-09-08 17:14:07 -07001361 let group = Group::new(Delimiter::Bracket, stream.into_iter().collect());
1362 trees.push(::Group::_new_stable(group).into());
Alex Crichton1eb96a02018-04-04 13:07:35 -07001363 for tt in trees.iter_mut() {
1364 tt.set_span(span);
1365 }
1366 Ok((rest, trees))
1367}
1368
1369named!(doc_comment_contents -> (&str, bool), alt!(
Alex Crichton44bffbc2017-05-19 17:51:59 -07001370 do_parse!(
1371 punct!("//!") >>
Alex Crichton1eb96a02018-04-04 13:07:35 -07001372 s: take_until_newline_or_eof!() >>
1373 ((s, true))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001374 )
1375 |
1376 do_parse!(
1377 option!(whitespace) >>
1378 peek!(tag!("/*!")) >>
Alex Crichton1eb96a02018-04-04 13:07:35 -07001379 s: block_comment >>
1380 ((s, true))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001381 )
1382 |
1383 do_parse!(
1384 punct!("///") >>
1385 not!(tag!("/")) >>
Alex Crichton1eb96a02018-04-04 13:07:35 -07001386 s: take_until_newline_or_eof!() >>
1387 ((s, false))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001388 )
1389 |
1390 do_parse!(
1391 option!(whitespace) >>
1392 peek!(tuple!(tag!("/**"), not!(tag!("*")))) >>
Alex Crichton1eb96a02018-04-04 13:07:35 -07001393 s: block_comment >>
1394 ((s, false))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001395 )
1396));