blob: 34df695fc7736929853147e775c25e8b58081352 [file] [log] [blame]
Alex Crichtona914a612018-04-04 07:48:44 -07001#![cfg_attr(not(procmacro2_semver_exempt), allow(dead_code))]
Alex Crichtonaf5bad42018-03-27 14:45:10 -07002
David Tolnayc2309ca2018-06-02 15:47:57 -07003#[cfg(procmacro2_semver_exempt)]
Alex Crichton44bffbc2017-05-19 17:51:59 -07004use std::cell::RefCell;
David Tolnay1ebe3972018-01-02 20:14:20 -08005#[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -05006use std::cmp;
Alex Crichton44bffbc2017-05-19 17:51:59 -07007use std::fmt;
8use std::iter;
Alex Crichton44bffbc2017-05-19 17:51:59 -07009use std::str::FromStr;
10use std::vec;
11
David Tolnayb28f38a2018-03-31 22:02:29 +020012use strnom::{block_comment, skip_whitespace, whitespace, word_break, Cursor, PResult};
David Tolnayb1032662017-05-31 15:52:28 -070013use unicode_xid::UnicodeXID;
Alex Crichton44bffbc2017-05-19 17:51:59 -070014
Alex Crichtonf3888432018-05-16 09:11:05 -070015use {Delimiter, Group, Punct, Spacing, TokenTree};
Alex Crichton44bffbc2017-05-19 17:51:59 -070016
David Tolnay034205f2018-04-22 16:45:28 -070017#[derive(Clone)]
Alex Crichton44bffbc2017-05-19 17:51:59 -070018pub struct TokenStream {
19 inner: Vec<TokenTree>,
20}
21
22#[derive(Debug)]
23pub struct LexError;
24
25impl TokenStream {
David Tolnayc3bb4592018-05-28 20:09:44 -070026 pub fn new() -> TokenStream {
Alex Crichton44bffbc2017-05-19 17:51:59 -070027 TokenStream { inner: Vec::new() }
28 }
29
30 pub fn is_empty(&self) -> bool {
31 self.inner.len() == 0
32 }
33}
34
David Tolnay1ebe3972018-01-02 20:14:20 -080035#[cfg(procmacro2_semver_exempt)]
Nika Layzella9dbc182017-12-30 14:50:13 -050036fn get_cursor(src: &str) -> Cursor {
37 // Create a dummy file & add it to the codemap
38 CODEMAP.with(|cm| {
39 let mut cm = cm.borrow_mut();
40 let name = format!("<parsed string {}>", cm.files.len());
41 let span = cm.add_file(&name, src);
42 Cursor {
43 rest: src,
44 off: span.lo,
45 }
46 })
47}
48
David Tolnay1ebe3972018-01-02 20:14:20 -080049#[cfg(not(procmacro2_semver_exempt))]
Nika Layzella9dbc182017-12-30 14:50:13 -050050fn get_cursor(src: &str) -> Cursor {
David Tolnayb28f38a2018-03-31 22:02:29 +020051 Cursor { rest: src }
Nika Layzella9dbc182017-12-30 14:50:13 -050052}
53
Alex Crichton44bffbc2017-05-19 17:51:59 -070054impl FromStr for TokenStream {
55 type Err = LexError;
56
57 fn from_str(src: &str) -> Result<TokenStream, LexError> {
Nika Layzellf8d5f212017-12-11 14:07:02 -050058 // Create a dummy file & add it to the codemap
Nika Layzella9dbc182017-12-30 14:50:13 -050059 let cursor = get_cursor(src);
Nika Layzellf8d5f212017-12-11 14:07:02 -050060
61 match token_stream(cursor) {
David Tolnay1218e122017-06-01 11:13:45 -070062 Ok((input, output)) => {
Alex Crichton44bffbc2017-05-19 17:51:59 -070063 if skip_whitespace(input).len() != 0 {
64 Err(LexError)
65 } else {
Alex Crichton30a4e9e2018-04-27 17:02:19 -070066 Ok(output)
Alex Crichton44bffbc2017-05-19 17:51:59 -070067 }
68 }
David Tolnay1218e122017-06-01 11:13:45 -070069 Err(LexError) => Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -070070 }
71 }
72}
73
74impl fmt::Display for TokenStream {
75 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
76 let mut joint = false;
77 for (i, tt) in self.inner.iter().enumerate() {
78 if i != 0 && !joint {
79 write!(f, " ")?;
80 }
81 joint = false;
Alex Crichtonaf5bad42018-03-27 14:45:10 -070082 match *tt {
83 TokenTree::Group(ref tt) => {
84 let (start, end) = match tt.delimiter() {
Alex Crichton44bffbc2017-05-19 17:51:59 -070085 Delimiter::Parenthesis => ("(", ")"),
86 Delimiter::Brace => ("{", "}"),
87 Delimiter::Bracket => ("[", "]"),
88 Delimiter::None => ("", ""),
89 };
Alex Crichton30a4e9e2018-04-27 17:02:19 -070090 if tt.stream().into_iter().next().is_none() {
Alex Crichton852d53d2017-05-19 19:25:08 -070091 write!(f, "{} {}", start, end)?
92 } else {
Alex Crichtonaf5bad42018-03-27 14:45:10 -070093 write!(f, "{} {} {}", start, tt.stream(), end)?
Alex Crichton852d53d2017-05-19 19:25:08 -070094 }
Alex Crichton44bffbc2017-05-19 17:51:59 -070095 }
Alex Crichtonf3888432018-05-16 09:11:05 -070096 TokenTree::Ident(ref tt) => write!(f, "{}", tt)?,
97 TokenTree::Punct(ref tt) => {
98 write!(f, "{}", tt.as_char())?;
Alex Crichtonaf5bad42018-03-27 14:45:10 -070099 match tt.spacing() {
Alex Crichton1a7f7622017-07-05 17:47:15 -0700100 Spacing::Alone => {}
101 Spacing::Joint => joint = true,
Alex Crichton44bffbc2017-05-19 17:51:59 -0700102 }
103 }
Alex Crichtonb2c94622018-04-04 07:36:41 -0700104 TokenTree::Literal(ref tt) => write!(f, "{}", tt)?,
Alex Crichton44bffbc2017-05-19 17:51:59 -0700105 }
106 }
107
108 Ok(())
109 }
110}
111
David Tolnay034205f2018-04-22 16:45:28 -0700112impl fmt::Debug for TokenStream {
113 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
114 f.write_str("TokenStream ")?;
115 f.debug_list().entries(self.clone()).finish()
116 }
117}
118
Alex Crichton53548482018-08-11 21:54:05 -0700119#[cfg(use_proc_macro)]
Alex Crichton0e8e7f42018-02-22 06:15:13 -0800120impl From<::proc_macro::TokenStream> for TokenStream {
121 fn from(inner: ::proc_macro::TokenStream) -> TokenStream {
David Tolnayb28f38a2018-03-31 22:02:29 +0200122 inner
123 .to_string()
124 .parse()
125 .expect("compiler token stream parse failed")
Alex Crichton44bffbc2017-05-19 17:51:59 -0700126 }
127}
128
Alex Crichton53548482018-08-11 21:54:05 -0700129#[cfg(use_proc_macro)]
Alex Crichton0e8e7f42018-02-22 06:15:13 -0800130impl From<TokenStream> for ::proc_macro::TokenStream {
131 fn from(inner: TokenStream) -> ::proc_macro::TokenStream {
David Tolnayb28f38a2018-03-31 22:02:29 +0200132 inner
133 .to_string()
134 .parse()
135 .expect("failed to parse to compiler tokens")
Alex Crichton44bffbc2017-05-19 17:51:59 -0700136 }
137}
138
Alex Crichton44bffbc2017-05-19 17:51:59 -0700139impl From<TokenTree> for TokenStream {
140 fn from(tree: TokenTree) -> TokenStream {
141 TokenStream { inner: vec![tree] }
142 }
143}
144
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700145impl iter::FromIterator<TokenTree> for TokenStream {
David Tolnayb28f38a2018-03-31 22:02:29 +0200146 fn from_iter<I: IntoIterator<Item = TokenTree>>(streams: I) -> Self {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700147 let mut v = Vec::new();
148
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700149 for token in streams.into_iter() {
150 v.push(token);
Alex Crichton44bffbc2017-05-19 17:51:59 -0700151 }
152
153 TokenStream { inner: v }
154 }
155}
156
Alex Crichton53b00672018-09-06 17:16:10 -0700157impl iter::FromIterator<TokenStream> for TokenStream {
158 fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
159 let mut v = Vec::new();
160
161 for stream in streams.into_iter() {
162 v.extend(stream.inner);
163 }
164
165 TokenStream { inner: v }
166 }
167}
168
Alex Crichtonf3888432018-05-16 09:11:05 -0700169impl Extend<TokenTree> for TokenStream {
170 fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, streams: I) {
171 self.inner.extend(streams);
172 }
173}
174
David Tolnay5c58c532018-08-13 11:33:51 -0700175impl Extend<TokenStream> for TokenStream {
176 fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
177 self.inner
178 .extend(streams.into_iter().flat_map(|stream| stream));
179 }
180}
181
Alex Crichton1a7f7622017-07-05 17:47:15 -0700182pub type TokenTreeIter = vec::IntoIter<TokenTree>;
Alex Crichton44bffbc2017-05-19 17:51:59 -0700183
184impl IntoIterator for TokenStream {
185 type Item = TokenTree;
Alex Crichton1a7f7622017-07-05 17:47:15 -0700186 type IntoIter = TokenTreeIter;
Alex Crichton44bffbc2017-05-19 17:51:59 -0700187
Alex Crichton1a7f7622017-07-05 17:47:15 -0700188 fn into_iter(self) -> TokenTreeIter {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700189 self.inner.into_iter()
190 }
191}
192
Nika Layzellb35a9a32017-12-30 14:34:35 -0500193#[derive(Clone, PartialEq, Eq, Debug)]
194pub struct FileName(String);
195
Alex Crichtonf3888432018-05-16 09:11:05 -0700196#[allow(dead_code)]
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700197pub fn file_name(s: String) -> FileName {
198 FileName(s)
199}
200
Nika Layzellb35a9a32017-12-30 14:34:35 -0500201impl fmt::Display for FileName {
202 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
203 self.0.fmt(f)
204 }
205}
206
Nika Layzellf8d5f212017-12-11 14:07:02 -0500207#[derive(Clone, PartialEq, Eq)]
208pub struct SourceFile {
Nika Layzellb35a9a32017-12-30 14:34:35 -0500209 name: FileName,
Nika Layzellf8d5f212017-12-11 14:07:02 -0500210}
211
212impl SourceFile {
213 /// Get the path to this source file as a string.
Nika Layzellb35a9a32017-12-30 14:34:35 -0500214 pub fn path(&self) -> &FileName {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500215 &self.name
216 }
217
218 pub fn is_real(&self) -> bool {
219 // XXX(nika): Support real files in the future?
220 false
221 }
222}
223
Nika Layzellb35a9a32017-12-30 14:34:35 -0500224impl AsRef<FileName> for SourceFile {
225 fn as_ref(&self) -> &FileName {
226 self.path()
Nika Layzellf8d5f212017-12-11 14:07:02 -0500227 }
228}
229
230impl fmt::Debug for SourceFile {
231 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
232 f.debug_struct("SourceFile")
Nika Layzellb35a9a32017-12-30 14:34:35 -0500233 .field("path", &self.path())
Nika Layzellf8d5f212017-12-11 14:07:02 -0500234 .field("is_real", &self.is_real())
235 .finish()
236 }
237}
238
239#[derive(Clone, Copy, Debug, PartialEq, Eq)]
240pub struct LineColumn {
241 pub line: usize,
242 pub column: usize,
243}
244
David Tolnay1ebe3972018-01-02 20:14:20 -0800245#[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500246thread_local! {
247 static CODEMAP: RefCell<Codemap> = RefCell::new(Codemap {
248 // NOTE: We start with a single dummy file which all call_site() and
249 // def_site() spans reference.
250 files: vec![FileInfo {
251 name: "<unspecified>".to_owned(),
252 span: Span { lo: 0, hi: 0 },
253 lines: vec![0],
254 }],
255 });
256}
257
David Tolnay1ebe3972018-01-02 20:14:20 -0800258#[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500259struct FileInfo {
260 name: String,
261 span: Span,
262 lines: Vec<usize>,
263}
264
David Tolnay1ebe3972018-01-02 20:14:20 -0800265#[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500266impl FileInfo {
267 fn offset_line_column(&self, offset: usize) -> LineColumn {
David Tolnayb28f38a2018-03-31 22:02:29 +0200268 assert!(self.span_within(Span {
269 lo: offset as u32,
270 hi: offset as u32
271 }));
Nika Layzellf8d5f212017-12-11 14:07:02 -0500272 let offset = offset - self.span.lo as usize;
273 match self.lines.binary_search(&offset) {
274 Ok(found) => LineColumn {
275 line: found + 1,
David Tolnayb28f38a2018-03-31 22:02:29 +0200276 column: 0,
Nika Layzellf8d5f212017-12-11 14:07:02 -0500277 },
278 Err(idx) => LineColumn {
279 line: idx,
David Tolnayb28f38a2018-03-31 22:02:29 +0200280 column: offset - self.lines[idx - 1],
Nika Layzellf8d5f212017-12-11 14:07:02 -0500281 },
282 }
283 }
284
285 fn span_within(&self, span: Span) -> bool {
286 span.lo >= self.span.lo && span.hi <= self.span.hi
287 }
288}
289
Alex Crichtona914a612018-04-04 07:48:44 -0700290/// Computesthe offsets of each line in the given source string.
David Tolnay1ebe3972018-01-02 20:14:20 -0800291#[cfg(procmacro2_semver_exempt)]
Nika Layzella0a7c3d2017-12-30 14:52:39 -0500292fn lines_offsets(s: &str) -> Vec<usize> {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500293 let mut lines = vec![0];
294 let mut prev = 0;
Nika Layzella0a7c3d2017-12-30 14:52:39 -0500295 while let Some(len) = s[prev..].find('\n') {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500296 prev += len + 1;
297 lines.push(prev);
298 }
299 lines
300}
301
David Tolnay1ebe3972018-01-02 20:14:20 -0800302#[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500303struct Codemap {
304 files: Vec<FileInfo>,
305}
306
David Tolnay1ebe3972018-01-02 20:14:20 -0800307#[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500308impl Codemap {
309 fn next_start_pos(&self) -> u32 {
310 // Add 1 so there's always space between files.
311 //
312 // We'll always have at least 1 file, as we initialize our files list
313 // with a dummy file.
314 self.files.last().unwrap().span.hi + 1
315 }
316
317 fn add_file(&mut self, name: &str, src: &str) -> Span {
Nika Layzella0a7c3d2017-12-30 14:52:39 -0500318 let lines = lines_offsets(src);
Nika Layzellf8d5f212017-12-11 14:07:02 -0500319 let lo = self.next_start_pos();
320 // XXX(nika): Shouild we bother doing a checked cast or checked add here?
David Tolnayb28f38a2018-03-31 22:02:29 +0200321 let span = Span {
322 lo: lo,
323 hi: lo + (src.len() as u32),
324 };
Nika Layzellf8d5f212017-12-11 14:07:02 -0500325
326 self.files.push(FileInfo {
327 name: name.to_owned(),
328 span: span,
329 lines: lines,
330 });
331
332 span
333 }
334
335 fn fileinfo(&self, span: Span) -> &FileInfo {
336 for file in &self.files {
337 if file.span_within(span) {
338 return file;
339 }
340 }
341 panic!("Invalid span with no related FileInfo!");
342 }
343}
344
David Tolnay034205f2018-04-22 16:45:28 -0700345#[derive(Clone, Copy, PartialEq, Eq)]
David Tolnayddfca052017-12-31 10:41:24 -0500346pub struct Span {
David Tolnay1ebe3972018-01-02 20:14:20 -0800347 #[cfg(procmacro2_semver_exempt)]
David Tolnayddfca052017-12-31 10:41:24 -0500348 lo: u32,
David Tolnay1ebe3972018-01-02 20:14:20 -0800349 #[cfg(procmacro2_semver_exempt)]
David Tolnayddfca052017-12-31 10:41:24 -0500350 hi: u32,
351}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700352
353impl Span {
David Tolnay1ebe3972018-01-02 20:14:20 -0800354 #[cfg(not(procmacro2_semver_exempt))]
Alex Crichton44bffbc2017-05-19 17:51:59 -0700355 pub fn call_site() -> Span {
David Tolnay79105e52017-12-31 11:03:04 -0500356 Span {}
357 }
358
David Tolnay1ebe3972018-01-02 20:14:20 -0800359 #[cfg(procmacro2_semver_exempt)]
David Tolnay79105e52017-12-31 11:03:04 -0500360 pub fn call_site() -> Span {
361 Span { lo: 0, hi: 0 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700362 }
Alex Crichtone6085b72017-11-21 07:24:25 -0800363
364 pub fn def_site() -> Span {
David Tolnay79105e52017-12-31 11:03:04 -0500365 Span::call_site()
Nika Layzellf8d5f212017-12-11 14:07:02 -0500366 }
367
David Tolnay4e8e3972018-01-05 18:10:22 -0800368 pub fn resolved_at(&self, _other: Span) -> Span {
369 // Stable spans consist only of line/column information, so
370 // `resolved_at` and `located_at` only select which span the
371 // caller wants line/column information from.
372 *self
373 }
374
375 pub fn located_at(&self, other: Span) -> Span {
376 other
377 }
378
David Tolnay1ebe3972018-01-02 20:14:20 -0800379 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500380 pub fn source_file(&self) -> SourceFile {
381 CODEMAP.with(|cm| {
382 let cm = cm.borrow();
383 let fi = cm.fileinfo(*self);
384 SourceFile {
Nika Layzellb35a9a32017-12-30 14:34:35 -0500385 name: FileName(fi.name.clone()),
Nika Layzellf8d5f212017-12-11 14:07:02 -0500386 }
387 })
388 }
389
David Tolnay1ebe3972018-01-02 20:14:20 -0800390 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500391 pub fn start(&self) -> LineColumn {
392 CODEMAP.with(|cm| {
393 let cm = cm.borrow();
394 let fi = cm.fileinfo(*self);
395 fi.offset_line_column(self.lo as usize)
396 })
397 }
398
David Tolnay1ebe3972018-01-02 20:14:20 -0800399 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500400 pub fn end(&self) -> LineColumn {
401 CODEMAP.with(|cm| {
402 let cm = cm.borrow();
403 let fi = cm.fileinfo(*self);
404 fi.offset_line_column(self.hi as usize)
405 })
406 }
407
David Tolnay1ebe3972018-01-02 20:14:20 -0800408 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500409 pub fn join(&self, other: Span) -> Option<Span> {
410 CODEMAP.with(|cm| {
411 let cm = cm.borrow();
412 // If `other` is not within the same FileInfo as us, return None.
413 if !cm.fileinfo(*self).span_within(other) {
414 return None;
415 }
416 Some(Span {
417 lo: cmp::min(self.lo, other.lo),
418 hi: cmp::max(self.hi, other.hi),
419 })
420 })
Alex Crichtone6085b72017-11-21 07:24:25 -0800421 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700422}
423
David Tolnay034205f2018-04-22 16:45:28 -0700424impl fmt::Debug for Span {
425 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
426 #[cfg(procmacro2_semver_exempt)]
427 return write!(f, "bytes({}..{})", self.lo, self.hi);
428
429 #[cfg(not(procmacro2_semver_exempt))]
430 write!(f, "Span")
431 }
432}
433
Alex Crichtonf3888432018-05-16 09:11:05 -0700434#[derive(Clone)]
435pub struct Ident {
David Tolnayc2309ca2018-06-02 15:47:57 -0700436 sym: String,
Alex Crichtonb2c94622018-04-04 07:36:41 -0700437 span: Span,
Alex Crichtonf3888432018-05-16 09:11:05 -0700438 raw: bool,
David Tolnay041bcd42017-06-03 09:18:04 -0700439}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700440
Alex Crichtonf3888432018-05-16 09:11:05 -0700441impl Ident {
442 fn _new(string: &str, raw: bool, span: Span) -> Ident {
David Tolnay489c6422018-04-07 08:37:28 -0700443 validate_term(string);
444
Alex Crichtonf3888432018-05-16 09:11:05 -0700445 Ident {
David Tolnayc2309ca2018-06-02 15:47:57 -0700446 sym: string.to_owned(),
Alex Crichtona914a612018-04-04 07:48:44 -0700447 span: span,
Alex Crichtonf3888432018-05-16 09:11:05 -0700448 raw: raw,
David Tolnay041bcd42017-06-03 09:18:04 -0700449 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700450 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700451
Alex Crichtonf3888432018-05-16 09:11:05 -0700452 pub fn new(string: &str, span: Span) -> Ident {
453 Ident::_new(string, false, span)
454 }
455
456 pub fn new_raw(string: &str, span: Span) -> Ident {
457 Ident::_new(string, true, span)
458 }
459
Alex Crichtonb2c94622018-04-04 07:36:41 -0700460 pub fn span(&self) -> Span {
461 self.span
462 }
463
464 pub fn set_span(&mut self, span: Span) {
465 self.span = span;
466 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700467}
468
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000469#[inline]
470fn is_ident_start(c: char) -> bool {
David Tolnay03b43da2018-06-02 15:25:57 -0700471 ('a' <= c && c <= 'z')
472 || ('A' <= c && c <= 'Z')
473 || c == '_'
474 || (c > '\x7f' && UnicodeXID::is_xid_start(c))
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000475}
476
477#[inline]
478fn is_ident_continue(c: char) -> bool {
David Tolnay03b43da2018-06-02 15:25:57 -0700479 ('a' <= c && c <= 'z')
480 || ('A' <= c && c <= 'Z')
481 || c == '_'
482 || ('0' <= c && c <= '9')
483 || (c > '\x7f' && UnicodeXID::is_xid_continue(c))
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000484}
485
David Tolnay489c6422018-04-07 08:37:28 -0700486fn validate_term(string: &str) {
Alex Crichtonf3888432018-05-16 09:11:05 -0700487 let validate = string;
David Tolnay489c6422018-04-07 08:37:28 -0700488 if validate.is_empty() {
Alex Crichtonf3888432018-05-16 09:11:05 -0700489 panic!("Ident is not allowed to be empty; use Option<Ident>");
David Tolnay489c6422018-04-07 08:37:28 -0700490 }
491
492 if validate.bytes().all(|digit| digit >= b'0' && digit <= b'9') {
Alex Crichtonf3888432018-05-16 09:11:05 -0700493 panic!("Ident cannot be a number; use Literal instead");
David Tolnay489c6422018-04-07 08:37:28 -0700494 }
495
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000496 fn ident_ok(string: &str) -> bool {
David Tolnay489c6422018-04-07 08:37:28 -0700497 let mut chars = string.chars();
498 let first = chars.next().unwrap();
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000499 if !is_ident_start(first) {
David Tolnay489c6422018-04-07 08:37:28 -0700500 return false;
501 }
502 for ch in chars {
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000503 if !is_ident_continue(ch) {
David Tolnay489c6422018-04-07 08:37:28 -0700504 return false;
505 }
506 }
507 true
508 }
509
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000510 if !ident_ok(validate) {
Alex Crichtonf3888432018-05-16 09:11:05 -0700511 panic!("{:?} is not a valid Ident", string);
David Tolnay489c6422018-04-07 08:37:28 -0700512 }
513}
514
David Tolnayc0b0f2e2018-09-02 17:56:08 -0700515impl PartialEq for Ident {
516 fn eq(&self, other: &Ident) -> bool {
517 self.sym == other.sym && self.raw == other.raw
518 }
519}
520
521impl<T> PartialEq<T> for Ident
522where
523 T: ?Sized + AsRef<str>,
524{
525 fn eq(&self, other: &T) -> bool {
526 let other = other.as_ref();
527 if self.raw {
528 other.starts_with("r#") && self.sym == other[2..]
529 } else {
530 self.sym == other
531 }
532 }
533}
534
Alex Crichtonf3888432018-05-16 09:11:05 -0700535impl fmt::Display for Ident {
David Tolnay8ad3e3e2017-06-03 16:45:00 -0700536 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Alex Crichtonf3888432018-05-16 09:11:05 -0700537 if self.raw {
538 "r#".fmt(f)?;
539 }
David Tolnayc2309ca2018-06-02 15:47:57 -0700540 self.sym.fmt(f)
Alex Crichtonf3888432018-05-16 09:11:05 -0700541 }
542}
543
544impl fmt::Debug for Ident {
David Tolnayd8fcdb82018-06-02 15:43:53 -0700545 // Ident(proc_macro), Ident(r#union)
546 #[cfg(not(procmacro2_semver_exempt))]
547 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
548 let mut debug = f.debug_tuple("Ident");
549 debug.field(&format_args!("{}", self));
550 debug.finish()
551 }
552
553 // Ident {
554 // sym: proc_macro,
555 // span: bytes(128..138)
556 // }
557 #[cfg(procmacro2_semver_exempt)]
Alex Crichtonf3888432018-05-16 09:11:05 -0700558 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
559 let mut debug = f.debug_struct("Ident");
David Tolnayd8fcdb82018-06-02 15:43:53 -0700560 debug.field("sym", &format_args!("{}", self));
David Tolnay034205f2018-04-22 16:45:28 -0700561 debug.field("span", &self.span);
562 debug.finish()
David Tolnay8ad3e3e2017-06-03 16:45:00 -0700563 }
564}
565
David Tolnay034205f2018-04-22 16:45:28 -0700566#[derive(Clone)]
Alex Crichtonb2c94622018-04-04 07:36:41 -0700567pub struct Literal {
568 text: String,
569 span: Span,
570}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700571
Alex Crichtona914a612018-04-04 07:48:44 -0700572macro_rules! suffixed_numbers {
573 ($($name:ident => $kind:ident,)*) => ($(
574 pub fn $name(n: $kind) -> Literal {
575 Literal::_new(format!(concat!("{}", stringify!($kind)), n))
576 }
577 )*)
578}
579
580macro_rules! unsuffixed_numbers {
581 ($($name:ident => $kind:ident,)*) => ($(
582 pub fn $name(n: $kind) -> Literal {
583 Literal::_new(n.to_string())
584 }
585 )*)
586}
587
Alex Crichton852d53d2017-05-19 19:25:08 -0700588impl Literal {
Alex Crichtonb2c94622018-04-04 07:36:41 -0700589 fn _new(text: String) -> Literal {
590 Literal {
Alex Crichtona914a612018-04-04 07:48:44 -0700591 text: text,
Alex Crichtonb2c94622018-04-04 07:36:41 -0700592 span: Span::call_site(),
593 }
594 }
595
Alex Crichtona914a612018-04-04 07:48:44 -0700596 suffixed_numbers! {
597 u8_suffixed => u8,
598 u16_suffixed => u16,
599 u32_suffixed => u32,
600 u64_suffixed => u64,
601 usize_suffixed => usize,
602 i8_suffixed => i8,
603 i16_suffixed => i16,
604 i32_suffixed => i32,
605 i64_suffixed => i64,
606 isize_suffixed => isize,
607
608 f32_suffixed => f32,
609 f64_suffixed => f64,
610 }
611
612 unsuffixed_numbers! {
613 u8_unsuffixed => u8,
614 u16_unsuffixed => u16,
615 u32_unsuffixed => u32,
616 u64_unsuffixed => u64,
617 usize_unsuffixed => usize,
618 i8_unsuffixed => i8,
619 i16_unsuffixed => i16,
620 i32_unsuffixed => i32,
621 i64_unsuffixed => i64,
622 isize_unsuffixed => isize,
623 }
624
625 pub fn f32_unsuffixed(f: f32) -> Literal {
626 let mut s = f.to_string();
627 if !s.contains(".") {
628 s.push_str(".0");
Alex Crichton76a5cc82017-05-23 07:01:44 -0700629 }
Alex Crichtona914a612018-04-04 07:48:44 -0700630 Literal::_new(s)
631 }
632
633 pub fn f64_unsuffixed(f: f64) -> Literal {
634 let mut s = f.to_string();
635 if !s.contains(".") {
636 s.push_str(".0");
637 }
638 Literal::_new(s)
639 }
640
641 pub fn string(t: &str) -> Literal {
David Tolnay3d9d6ad2018-05-18 10:51:55 -0700642 let mut s = t
643 .chars()
Alex Crichtona914a612018-04-04 07:48:44 -0700644 .flat_map(|c| c.escape_default())
645 .collect::<String>();
646 s.push('"');
647 s.insert(0, '"');
648 Literal::_new(s)
649 }
650
651 pub fn character(t: char) -> Literal {
652 Literal::_new(format!("'{}'", t.escape_default().collect::<String>()))
Alex Crichton76a5cc82017-05-23 07:01:44 -0700653 }
654
Alex Crichton9c2fb0a2017-05-26 08:49:31 -0700655 pub fn byte_string(bytes: &[u8]) -> Literal {
Alex Crichton852d53d2017-05-19 19:25:08 -0700656 let mut escaped = "b\"".to_string();
657 for b in bytes {
658 match *b {
659 b'\0' => escaped.push_str(r"\0"),
660 b'\t' => escaped.push_str(r"\t"),
661 b'\n' => escaped.push_str(r"\n"),
662 b'\r' => escaped.push_str(r"\r"),
663 b'"' => escaped.push_str("\\\""),
664 b'\\' => escaped.push_str("\\\\"),
David Tolnayb28f38a2018-03-31 22:02:29 +0200665 b'\x20'...b'\x7E' => escaped.push(*b as char),
Alex Crichton852d53d2017-05-19 19:25:08 -0700666 _ => escaped.push_str(&format!("\\x{:02X}", b)),
667 }
668 }
669 escaped.push('"');
Alex Crichtonb2c94622018-04-04 07:36:41 -0700670 Literal::_new(escaped)
Alex Crichton76a5cc82017-05-23 07:01:44 -0700671 }
Alex Crichton9c2fb0a2017-05-26 08:49:31 -0700672
Alex Crichtonb2c94622018-04-04 07:36:41 -0700673 pub fn span(&self) -> Span {
674 self.span
Alex Crichton31316622017-05-26 12:54:47 -0700675 }
676
Alex Crichtonb2c94622018-04-04 07:36:41 -0700677 pub fn set_span(&mut self, span: Span) {
678 self.span = span;
Alex Crichton31316622017-05-26 12:54:47 -0700679 }
Alex Crichton852d53d2017-05-19 19:25:08 -0700680}
681
Alex Crichton44bffbc2017-05-19 17:51:59 -0700682impl fmt::Display for Literal {
683 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Alex Crichtonb2c94622018-04-04 07:36:41 -0700684 self.text.fmt(f)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700685 }
686}
687
David Tolnay034205f2018-04-22 16:45:28 -0700688impl fmt::Debug for Literal {
689 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
690 let mut debug = fmt.debug_struct("Literal");
691 debug.field("lit", &format_args!("{}", self.text));
692 #[cfg(procmacro2_semver_exempt)]
693 debug.field("span", &self.span);
694 debug.finish()
695 }
696}
697
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700698fn token_stream(mut input: Cursor) -> PResult<TokenStream> {
Alex Crichton1eb96a02018-04-04 13:07:35 -0700699 let mut trees = Vec::new();
700 loop {
701 let input_no_ws = skip_whitespace(input);
702 if input_no_ws.rest.len() == 0 {
David Tolnay48ea5042018-04-23 19:17:35 -0700703 break;
Alex Crichton1eb96a02018-04-04 13:07:35 -0700704 }
705 if let Ok((a, tokens)) = doc_comment(input_no_ws) {
706 input = a;
707 trees.extend(tokens);
David Tolnay48ea5042018-04-23 19:17:35 -0700708 continue;
Alex Crichton1eb96a02018-04-04 13:07:35 -0700709 }
710
711 let (a, tt) = match token_tree(input_no_ws) {
712 Ok(p) => p,
713 Err(_) => break,
714 };
715 trees.push(tt);
716 input = a;
717 }
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700718 Ok((input, TokenStream { inner: trees }))
Alex Crichton1eb96a02018-04-04 13:07:35 -0700719}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700720
David Tolnay1ebe3972018-01-02 20:14:20 -0800721#[cfg(not(procmacro2_semver_exempt))]
Alex Crichton1eb96a02018-04-04 13:07:35 -0700722fn spanned<'a, T>(
723 input: Cursor<'a>,
724 f: fn(Cursor<'a>) -> PResult<'a, T>,
725) -> PResult<'a, (T, ::Span)> {
726 let (a, b) = f(skip_whitespace(input))?;
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700727 Ok((a, ((b, ::Span::_new_stable(Span {})))))
David Tolnayddfca052017-12-31 10:41:24 -0500728}
729
David Tolnay1ebe3972018-01-02 20:14:20 -0800730#[cfg(procmacro2_semver_exempt)]
Alex Crichton1eb96a02018-04-04 13:07:35 -0700731fn spanned<'a, T>(
732 input: Cursor<'a>,
733 f: fn(Cursor<'a>) -> PResult<'a, T>,
734) -> PResult<'a, (T, ::Span)> {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500735 let input = skip_whitespace(input);
736 let lo = input.off;
Alex Crichton1eb96a02018-04-04 13:07:35 -0700737 let (a, b) = f(input)?;
738 let hi = a.off;
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700739 let span = ::Span::_new_stable(Span { lo: lo, hi: hi });
Alex Crichton1eb96a02018-04-04 13:07:35 -0700740 Ok((a, (b, span)))
741}
742
743fn token_tree(input: Cursor) -> PResult<TokenTree> {
744 let (rest, (mut tt, span)) = spanned(input, token_kind)?;
745 tt.set_span(span);
746 Ok((rest, tt))
Nika Layzellf8d5f212017-12-11 14:07:02 -0500747}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700748
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700749named!(token_kind -> TokenTree, alt!(
750 map!(group, TokenTree::Group)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700751 |
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700752 map!(literal, |l| TokenTree::Literal(::Literal::_new_stable(l))) // must be before symbol
Alex Crichton44bffbc2017-05-19 17:51:59 -0700753 |
Alex Crichtonf3888432018-05-16 09:11:05 -0700754 map!(op, TokenTree::Punct)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700755 |
Alex Crichtonf3888432018-05-16 09:11:05 -0700756 symbol_leading_ws
Alex Crichton44bffbc2017-05-19 17:51:59 -0700757));
758
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700759named!(group -> Group, alt!(
Alex Crichton44bffbc2017-05-19 17:51:59 -0700760 delimited!(
761 punct!("("),
762 token_stream,
763 punct!(")")
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700764 ) => { |ts| Group::new(Delimiter::Parenthesis, ::TokenStream::_new_stable(ts)) }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700765 |
766 delimited!(
767 punct!("["),
768 token_stream,
769 punct!("]")
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700770 ) => { |ts| Group::new(Delimiter::Bracket, ::TokenStream::_new_stable(ts)) }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700771 |
772 delimited!(
773 punct!("{"),
774 token_stream,
775 punct!("}")
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700776 ) => { |ts| Group::new(Delimiter::Brace, ::TokenStream::_new_stable(ts)) }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700777));
778
Alex Crichtonf3888432018-05-16 09:11:05 -0700779fn symbol_leading_ws(input: Cursor) -> PResult<TokenTree> {
780 symbol(skip_whitespace(input))
781}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700782
Alex Crichtonf3888432018-05-16 09:11:05 -0700783fn symbol(input: Cursor) -> PResult<TokenTree> {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700784 let mut chars = input.char_indices();
David Tolnaya202d502017-06-01 12:26:55 -0700785
Alex Crichtonf3888432018-05-16 09:11:05 -0700786 let raw = input.starts_with("r#");
David Tolnaya13d1422018-03-31 21:27:48 +0200787 if raw {
788 chars.next();
789 chars.next();
790 }
791
Alex Crichton44bffbc2017-05-19 17:51:59 -0700792 match chars.next() {
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000793 Some((_, ch)) if is_ident_start(ch) => {}
David Tolnay1218e122017-06-01 11:13:45 -0700794 _ => return Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -0700795 }
796
David Tolnay214c94c2017-06-01 12:42:56 -0700797 let mut end = input.len();
Alex Crichton44bffbc2017-05-19 17:51:59 -0700798 for (i, ch) in chars {
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000799 if !is_ident_continue(ch) {
David Tolnay214c94c2017-06-01 12:42:56 -0700800 end = i;
801 break;
Alex Crichton44bffbc2017-05-19 17:51:59 -0700802 }
803 }
804
David Tolnaya13d1422018-03-31 21:27:48 +0200805 let a = &input.rest[..end];
Alex Crichtonf3888432018-05-16 09:11:05 -0700806 if a == "r#_" {
David Tolnay214c94c2017-06-01 12:42:56 -0700807 Err(LexError)
808 } else {
Alex Crichtonf3888432018-05-16 09:11:05 -0700809 let ident = if raw {
810 ::Ident::_new_raw(&a[2..], ::Span::call_site())
811 } else {
812 ::Ident::new(a, ::Span::call_site())
813 };
814 Ok((input.advance(end), ident.into()))
David Tolnay214c94c2017-06-01 12:42:56 -0700815 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700816}
817
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700818fn literal(input: Cursor) -> PResult<Literal> {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700819 let input_no_ws = skip_whitespace(input);
820
821 match literal_nocapture(input_no_ws) {
David Tolnay1218e122017-06-01 11:13:45 -0700822 Ok((a, ())) => {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700823 let start = input.len() - input_no_ws.len();
824 let len = input_no_ws.len() - a.len();
825 let end = start + len;
David Tolnay3d9d6ad2018-05-18 10:51:55 -0700826 Ok((a, Literal::_new(input.rest[start..end].to_string())))
Alex Crichton44bffbc2017-05-19 17:51:59 -0700827 }
David Tolnay1218e122017-06-01 11:13:45 -0700828 Err(LexError) => Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -0700829 }
830}
831
832named!(literal_nocapture -> (), alt!(
833 string
834 |
835 byte_string
836 |
837 byte
838 |
839 character
840 |
841 float
842 |
843 int
Alex Crichton44bffbc2017-05-19 17:51:59 -0700844));
845
846named!(string -> (), alt!(
847 quoted_string
848 |
849 preceded!(
850 punct!("r"),
851 raw_string
852 ) => { |_| () }
853));
854
855named!(quoted_string -> (), delimited!(
856 punct!("\""),
857 cooked_string,
858 tag!("\"")
859));
860
Nika Layzellf8d5f212017-12-11 14:07:02 -0500861fn cooked_string(input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700862 let mut chars = input.char_indices().peekable();
863 while let Some((byte_offset, ch)) = chars.next() {
864 match ch {
865 '"' => {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500866 return Ok((input.advance(byte_offset), ()));
Alex Crichton44bffbc2017-05-19 17:51:59 -0700867 }
868 '\r' => {
869 if let Some((_, '\n')) = chars.next() {
870 // ...
871 } else {
872 break;
873 }
874 }
David Tolnayb28f38a2018-03-31 22:02:29 +0200875 '\\' => match chars.next() {
876 Some((_, 'x')) => {
877 if !backslash_x_char(&mut chars) {
878 break;
Alex Crichton44bffbc2017-05-19 17:51:59 -0700879 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700880 }
David Tolnayb28f38a2018-03-31 22:02:29 +0200881 Some((_, 'n')) | Some((_, 'r')) | Some((_, 't')) | Some((_, '\\'))
882 | Some((_, '\'')) | Some((_, '"')) | Some((_, '0')) => {}
883 Some((_, 'u')) => {
884 if !backslash_u(&mut chars) {
885 break;
886 }
887 }
888 Some((_, '\n')) | Some((_, '\r')) => {
889 while let Some(&(_, ch)) = chars.peek() {
890 if ch.is_whitespace() {
891 chars.next();
892 } else {
893 break;
894 }
895 }
896 }
897 _ => break,
898 },
Alex Crichton44bffbc2017-05-19 17:51:59 -0700899 _ch => {}
900 }
901 }
David Tolnay1218e122017-06-01 11:13:45 -0700902 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700903}
904
905named!(byte_string -> (), alt!(
906 delimited!(
907 punct!("b\""),
908 cooked_byte_string,
909 tag!("\"")
910 ) => { |_| () }
911 |
912 preceded!(
913 punct!("br"),
914 raw_string
915 ) => { |_| () }
916));
917
Nika Layzellf8d5f212017-12-11 14:07:02 -0500918fn cooked_byte_string(mut input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700919 let mut bytes = input.bytes().enumerate();
920 'outer: while let Some((offset, b)) = bytes.next() {
921 match b {
922 b'"' => {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500923 return Ok((input.advance(offset), ()));
Alex Crichton44bffbc2017-05-19 17:51:59 -0700924 }
925 b'\r' => {
926 if let Some((_, b'\n')) = bytes.next() {
927 // ...
928 } else {
929 break;
930 }
931 }
David Tolnayb28f38a2018-03-31 22:02:29 +0200932 b'\\' => match bytes.next() {
933 Some((_, b'x')) => {
934 if !backslash_x_byte(&mut bytes) {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700935 break;
936 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700937 }
David Tolnayb28f38a2018-03-31 22:02:29 +0200938 Some((_, b'n')) | Some((_, b'r')) | Some((_, b't')) | Some((_, b'\\'))
939 | Some((_, b'0')) | Some((_, b'\'')) | Some((_, b'"')) => {}
940 Some((newline, b'\n')) | Some((newline, b'\r')) => {
941 let rest = input.advance(newline + 1);
942 for (offset, ch) in rest.char_indices() {
943 if !ch.is_whitespace() {
944 input = rest.advance(offset);
945 bytes = input.bytes().enumerate();
946 continue 'outer;
947 }
948 }
949 break;
950 }
951 _ => break,
952 },
Alex Crichton44bffbc2017-05-19 17:51:59 -0700953 b if b < 0x80 => {}
954 _ => break,
955 }
956 }
David Tolnay1218e122017-06-01 11:13:45 -0700957 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700958}
959
Nika Layzellf8d5f212017-12-11 14:07:02 -0500960fn raw_string(input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700961 let mut chars = input.char_indices();
962 let mut n = 0;
963 while let Some((byte_offset, ch)) = chars.next() {
964 match ch {
965 '"' => {
966 n = byte_offset;
967 break;
968 }
969 '#' => {}
David Tolnay1218e122017-06-01 11:13:45 -0700970 _ => return Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -0700971 }
972 }
973 for (byte_offset, ch) in chars {
974 match ch {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500975 '"' if input.advance(byte_offset + 1).starts_with(&input.rest[..n]) => {
976 let rest = input.advance(byte_offset + 1 + n);
David Tolnayb28f38a2018-03-31 22:02:29 +0200977 return Ok((rest, ()));
Alex Crichton44bffbc2017-05-19 17:51:59 -0700978 }
979 '\r' => {}
980 _ => {}
981 }
982 }
David Tolnay1218e122017-06-01 11:13:45 -0700983 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700984}
985
986named!(byte -> (), do_parse!(
987 punct!("b") >>
988 tag!("'") >>
989 cooked_byte >>
990 tag!("'") >>
991 (())
992));
993
Nika Layzellf8d5f212017-12-11 14:07:02 -0500994fn cooked_byte(input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700995 let mut bytes = input.bytes().enumerate();
996 let ok = match bytes.next().map(|(_, b)| b) {
David Tolnayb28f38a2018-03-31 22:02:29 +0200997 Some(b'\\') => match bytes.next().map(|(_, b)| b) {
998 Some(b'x') => backslash_x_byte(&mut bytes),
999 Some(b'n') | Some(b'r') | Some(b't') | Some(b'\\') | Some(b'0') | Some(b'\'')
1000 | Some(b'"') => true,
1001 _ => false,
1002 },
Alex Crichton44bffbc2017-05-19 17:51:59 -07001003 b => b.is_some(),
1004 };
1005 if ok {
1006 match bytes.next() {
Alex Crichton8c030332018-01-16 08:07:36 -08001007 Some((offset, _)) => {
1008 if input.chars().as_str().is_char_boundary(offset) {
1009 Ok((input.advance(offset), ()))
1010 } else {
1011 Err(LexError)
1012 }
1013 }
Nika Layzellf8d5f212017-12-11 14:07:02 -05001014 None => Ok((input.advance(input.len()), ())),
Alex Crichton44bffbc2017-05-19 17:51:59 -07001015 }
1016 } else {
David Tolnay1218e122017-06-01 11:13:45 -07001017 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001018 }
1019}
1020
1021named!(character -> (), do_parse!(
1022 punct!("'") >>
1023 cooked_char >>
1024 tag!("'") >>
1025 (())
1026));
1027
Nika Layzellf8d5f212017-12-11 14:07:02 -05001028fn cooked_char(input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001029 let mut chars = input.char_indices();
1030 let ok = match chars.next().map(|(_, ch)| ch) {
David Tolnayb28f38a2018-03-31 22:02:29 +02001031 Some('\\') => match chars.next().map(|(_, ch)| ch) {
1032 Some('x') => backslash_x_char(&mut chars),
1033 Some('u') => backslash_u(&mut chars),
1034 Some('n') | Some('r') | Some('t') | Some('\\') | Some('0') | Some('\'') | Some('"') => {
1035 true
Alex Crichton44bffbc2017-05-19 17:51:59 -07001036 }
David Tolnayb28f38a2018-03-31 22:02:29 +02001037 _ => false,
1038 },
Alex Crichton44bffbc2017-05-19 17:51:59 -07001039 ch => ch.is_some(),
1040 };
1041 if ok {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001042 match chars.next() {
1043 Some((idx, _)) => Ok((input.advance(idx), ())),
1044 None => Ok((input.advance(input.len()), ())),
1045 }
Alex Crichton44bffbc2017-05-19 17:51:59 -07001046 } else {
David Tolnay1218e122017-06-01 11:13:45 -07001047 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001048 }
1049}
1050
1051macro_rules! next_ch {
1052 ($chars:ident @ $pat:pat $(| $rest:pat)*) => {
1053 match $chars.next() {
1054 Some((_, ch)) => match ch {
1055 $pat $(| $rest)* => ch,
1056 _ => return false,
1057 },
1058 None => return false
1059 }
1060 };
1061}
1062
1063fn backslash_x_char<I>(chars: &mut I) -> bool
David Tolnayb28f38a2018-03-31 22:02:29 +02001064where
1065 I: Iterator<Item = (usize, char)>,
Alex Crichton44bffbc2017-05-19 17:51:59 -07001066{
1067 next_ch!(chars @ '0'...'7');
1068 next_ch!(chars @ '0'...'9' | 'a'...'f' | 'A'...'F');
1069 true
1070}
1071
1072fn backslash_x_byte<I>(chars: &mut I) -> bool
David Tolnayb28f38a2018-03-31 22:02:29 +02001073where
1074 I: Iterator<Item = (usize, u8)>,
Alex Crichton44bffbc2017-05-19 17:51:59 -07001075{
1076 next_ch!(chars @ b'0'...b'9' | b'a'...b'f' | b'A'...b'F');
1077 next_ch!(chars @ b'0'...b'9' | b'a'...b'f' | b'A'...b'F');
1078 true
1079}
1080
1081fn backslash_u<I>(chars: &mut I) -> bool
David Tolnayb28f38a2018-03-31 22:02:29 +02001082where
1083 I: Iterator<Item = (usize, char)>,
Alex Crichton44bffbc2017-05-19 17:51:59 -07001084{
1085 next_ch!(chars @ '{');
1086 next_ch!(chars @ '0'...'9' | 'a'...'f' | 'A'...'F');
David Tolnay8d109342017-12-25 18:24:45 -05001087 loop {
1088 let c = next_ch!(chars @ '0'...'9' | 'a'...'f' | 'A'...'F' | '_' | '}');
1089 if c == '}' {
1090 return true;
1091 }
Alex Crichton44bffbc2017-05-19 17:51:59 -07001092 }
Alex Crichton44bffbc2017-05-19 17:51:59 -07001093}
1094
Nika Layzellf8d5f212017-12-11 14:07:02 -05001095fn float(input: Cursor) -> PResult<()> {
David Tolnay744a6b82017-06-01 11:34:29 -07001096 let (rest, ()) = float_digits(input)?;
1097 for suffix in &["f32", "f64"] {
1098 if rest.starts_with(suffix) {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001099 return word_break(rest.advance(suffix.len()));
David Tolnay744a6b82017-06-01 11:34:29 -07001100 }
1101 }
1102 word_break(rest)
1103}
Alex Crichton44bffbc2017-05-19 17:51:59 -07001104
Nika Layzellf8d5f212017-12-11 14:07:02 -05001105fn float_digits(input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001106 let mut chars = input.chars().peekable();
1107 match chars.next() {
1108 Some(ch) if ch >= '0' && ch <= '9' => {}
David Tolnay1218e122017-06-01 11:13:45 -07001109 _ => return Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -07001110 }
1111
1112 let mut len = 1;
1113 let mut has_dot = false;
1114 let mut has_exp = false;
1115 while let Some(&ch) = chars.peek() {
1116 match ch {
1117 '0'...'9' | '_' => {
1118 chars.next();
1119 len += 1;
1120 }
1121 '.' => {
1122 if has_dot {
1123 break;
1124 }
1125 chars.next();
David Tolnayb28f38a2018-03-31 22:02:29 +02001126 if chars
1127 .peek()
1128 .map(|&ch| ch == '.' || UnicodeXID::is_xid_start(ch))
1129 .unwrap_or(false)
1130 {
David Tolnay1218e122017-06-01 11:13:45 -07001131 return Err(LexError);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001132 }
1133 len += 1;
1134 has_dot = true;
1135 }
1136 'e' | 'E' => {
1137 chars.next();
1138 len += 1;
1139 has_exp = true;
1140 break;
1141 }
1142 _ => break,
1143 }
1144 }
1145
Nika Layzellf8d5f212017-12-11 14:07:02 -05001146 let rest = input.advance(len);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001147 if !(has_dot || has_exp || rest.starts_with("f32") || rest.starts_with("f64")) {
David Tolnay1218e122017-06-01 11:13:45 -07001148 return Err(LexError);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001149 }
1150
1151 if has_exp {
1152 let mut has_exp_value = false;
1153 while let Some(&ch) = chars.peek() {
1154 match ch {
1155 '+' | '-' => {
1156 if has_exp_value {
1157 break;
1158 }
1159 chars.next();
1160 len += 1;
1161 }
1162 '0'...'9' => {
1163 chars.next();
1164 len += 1;
1165 has_exp_value = true;
1166 }
1167 '_' => {
1168 chars.next();
1169 len += 1;
1170 }
1171 _ => break,
1172 }
1173 }
1174 if !has_exp_value {
David Tolnay1218e122017-06-01 11:13:45 -07001175 return Err(LexError);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001176 }
1177 }
1178
Nika Layzellf8d5f212017-12-11 14:07:02 -05001179 Ok((input.advance(len), ()))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001180}
1181
Nika Layzellf8d5f212017-12-11 14:07:02 -05001182fn int(input: Cursor) -> PResult<()> {
David Tolnay744a6b82017-06-01 11:34:29 -07001183 let (rest, ()) = digits(input)?;
1184 for suffix in &[
David Tolnay48ea5042018-04-23 19:17:35 -07001185 "isize", "i8", "i16", "i32", "i64", "i128", "usize", "u8", "u16", "u32", "u64", "u128",
David Tolnay744a6b82017-06-01 11:34:29 -07001186 ] {
1187 if rest.starts_with(suffix) {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001188 return word_break(rest.advance(suffix.len()));
David Tolnay744a6b82017-06-01 11:34:29 -07001189 }
1190 }
1191 word_break(rest)
1192}
Alex Crichton44bffbc2017-05-19 17:51:59 -07001193
Nika Layzellf8d5f212017-12-11 14:07:02 -05001194fn digits(mut input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001195 let base = if input.starts_with("0x") {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001196 input = input.advance(2);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001197 16
1198 } else if input.starts_with("0o") {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001199 input = input.advance(2);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001200 8
1201 } else if input.starts_with("0b") {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001202 input = input.advance(2);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001203 2
1204 } else {
1205 10
1206 };
1207
Alex Crichton44bffbc2017-05-19 17:51:59 -07001208 let mut len = 0;
1209 let mut empty = true;
1210 for b in input.bytes() {
1211 let digit = match b {
1212 b'0'...b'9' => (b - b'0') as u64,
1213 b'a'...b'f' => 10 + (b - b'a') as u64,
1214 b'A'...b'F' => 10 + (b - b'A') as u64,
1215 b'_' => {
1216 if empty && base == 10 {
David Tolnay1218e122017-06-01 11:13:45 -07001217 return Err(LexError);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001218 }
1219 len += 1;
1220 continue;
1221 }
1222 _ => break,
1223 };
1224 if digit >= base {
David Tolnay1218e122017-06-01 11:13:45 -07001225 return Err(LexError);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001226 }
Alex Crichton44bffbc2017-05-19 17:51:59 -07001227 len += 1;
1228 empty = false;
1229 }
1230 if empty {
David Tolnay1218e122017-06-01 11:13:45 -07001231 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001232 } else {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001233 Ok((input.advance(len), ()))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001234 }
1235}
1236
Alex Crichtonf3888432018-05-16 09:11:05 -07001237fn op(input: Cursor) -> PResult<Punct> {
David Tolnayea75c5f2017-05-31 23:40:33 -07001238 let input = skip_whitespace(input);
1239 match op_char(input) {
Alex Crichtonf3888432018-05-16 09:11:05 -07001240 Ok((rest, '\'')) => {
1241 symbol(rest)?;
1242 Ok((rest, Punct::new('\'', Spacing::Joint)))
1243 }
David Tolnay1218e122017-06-01 11:13:45 -07001244 Ok((rest, ch)) => {
David Tolnayea75c5f2017-05-31 23:40:33 -07001245 let kind = match op_char(rest) {
Alex Crichton1a7f7622017-07-05 17:47:15 -07001246 Ok(_) => Spacing::Joint,
1247 Err(LexError) => Spacing::Alone,
David Tolnayea75c5f2017-05-31 23:40:33 -07001248 };
Alex Crichtonf3888432018-05-16 09:11:05 -07001249 Ok((rest, Punct::new(ch, kind)))
David Tolnayea75c5f2017-05-31 23:40:33 -07001250 }
David Tolnay1218e122017-06-01 11:13:45 -07001251 Err(LexError) => Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -07001252 }
1253}
1254
Nika Layzellf8d5f212017-12-11 14:07:02 -05001255fn op_char(input: Cursor) -> PResult<char> {
David Tolnay3a592ad2018-04-22 21:20:24 -07001256 if input.starts_with("//") || input.starts_with("/*") {
1257 // Do not accept `/` of a comment as an op.
1258 return Err(LexError);
1259 }
1260
David Tolnayea75c5f2017-05-31 23:40:33 -07001261 let mut chars = input.chars();
1262 let first = match chars.next() {
1263 Some(ch) => ch,
1264 None => {
David Tolnay1218e122017-06-01 11:13:45 -07001265 return Err(LexError);
David Tolnayea75c5f2017-05-31 23:40:33 -07001266 }
1267 };
Alex Crichtonf3888432018-05-16 09:11:05 -07001268 let recognized = "~!@#$%^&*-=+|;:,<.>/?'";
David Tolnayea75c5f2017-05-31 23:40:33 -07001269 if recognized.contains(first) {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001270 Ok((input.advance(first.len_utf8()), first))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001271 } else {
David Tolnay1218e122017-06-01 11:13:45 -07001272 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001273 }
1274}
1275
Alex Crichton1eb96a02018-04-04 13:07:35 -07001276fn doc_comment(input: Cursor) -> PResult<Vec<TokenTree>> {
1277 let mut trees = Vec::new();
1278 let (rest, ((comment, inner), span)) = spanned(input, doc_comment_contents)?;
Alex Crichtonf3888432018-05-16 09:11:05 -07001279 trees.push(TokenTree::Punct(Punct::new('#', Spacing::Alone)));
Alex Crichton1eb96a02018-04-04 13:07:35 -07001280 if inner {
Alex Crichtonf3888432018-05-16 09:11:05 -07001281 trees.push(Punct::new('!', Spacing::Alone).into());
Alex Crichton1eb96a02018-04-04 13:07:35 -07001282 }
1283 let mut stream = vec![
Alex Crichtonf3888432018-05-16 09:11:05 -07001284 TokenTree::Ident(::Ident::new("doc", span)),
1285 TokenTree::Punct(Punct::new('=', Spacing::Alone)),
Alex Crichton1eb96a02018-04-04 13:07:35 -07001286 TokenTree::Literal(::Literal::string(comment)),
1287 ];
1288 for tt in stream.iter_mut() {
1289 tt.set_span(span);
1290 }
1291 trees.push(Group::new(Delimiter::Bracket, stream.into_iter().collect()).into());
1292 for tt in trees.iter_mut() {
1293 tt.set_span(span);
1294 }
1295 Ok((rest, trees))
1296}
1297
1298named!(doc_comment_contents -> (&str, bool), alt!(
Alex Crichton44bffbc2017-05-19 17:51:59 -07001299 do_parse!(
1300 punct!("//!") >>
Alex Crichton1eb96a02018-04-04 13:07:35 -07001301 s: take_until_newline_or_eof!() >>
1302 ((s, true))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001303 )
1304 |
1305 do_parse!(
1306 option!(whitespace) >>
1307 peek!(tag!("/*!")) >>
Alex Crichton1eb96a02018-04-04 13:07:35 -07001308 s: block_comment >>
1309 ((s, true))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001310 )
1311 |
1312 do_parse!(
1313 punct!("///") >>
1314 not!(tag!("/")) >>
Alex Crichton1eb96a02018-04-04 13:07:35 -07001315 s: take_until_newline_or_eof!() >>
1316 ((s, false))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001317 )
1318 |
1319 do_parse!(
1320 option!(whitespace) >>
1321 peek!(tuple!(tag!("/**"), not!(tag!("*")))) >>
Alex Crichton1eb96a02018-04-04 13:07:35 -07001322 s: block_comment >>
1323 ((s, false))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001324 )
1325));