blob: 935e86c99ec48171915dbdc7cff19a8d740a519a [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 Crichtonf3888432018-05-16 09:11:05 -0700157impl Extend<TokenTree> for TokenStream {
158 fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, streams: I) {
159 self.inner.extend(streams);
160 }
161}
162
David Tolnay5c58c532018-08-13 11:33:51 -0700163impl Extend<TokenStream> for TokenStream {
164 fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
165 self.inner
166 .extend(streams.into_iter().flat_map(|stream| stream));
167 }
168}
169
Alex Crichton1a7f7622017-07-05 17:47:15 -0700170pub type TokenTreeIter = vec::IntoIter<TokenTree>;
Alex Crichton44bffbc2017-05-19 17:51:59 -0700171
172impl IntoIterator for TokenStream {
173 type Item = TokenTree;
Alex Crichton1a7f7622017-07-05 17:47:15 -0700174 type IntoIter = TokenTreeIter;
Alex Crichton44bffbc2017-05-19 17:51:59 -0700175
Alex Crichton1a7f7622017-07-05 17:47:15 -0700176 fn into_iter(self) -> TokenTreeIter {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700177 self.inner.into_iter()
178 }
179}
180
Nika Layzellb35a9a32017-12-30 14:34:35 -0500181#[derive(Clone, PartialEq, Eq, Debug)]
182pub struct FileName(String);
183
Alex Crichtonf3888432018-05-16 09:11:05 -0700184#[allow(dead_code)]
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700185pub fn file_name(s: String) -> FileName {
186 FileName(s)
187}
188
Nika Layzellb35a9a32017-12-30 14:34:35 -0500189impl fmt::Display for FileName {
190 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
191 self.0.fmt(f)
192 }
193}
194
Nika Layzellf8d5f212017-12-11 14:07:02 -0500195#[derive(Clone, PartialEq, Eq)]
196pub struct SourceFile {
Nika Layzellb35a9a32017-12-30 14:34:35 -0500197 name: FileName,
Nika Layzellf8d5f212017-12-11 14:07:02 -0500198}
199
200impl SourceFile {
201 /// Get the path to this source file as a string.
Nika Layzellb35a9a32017-12-30 14:34:35 -0500202 pub fn path(&self) -> &FileName {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500203 &self.name
204 }
205
206 pub fn is_real(&self) -> bool {
207 // XXX(nika): Support real files in the future?
208 false
209 }
210}
211
Nika Layzellb35a9a32017-12-30 14:34:35 -0500212impl AsRef<FileName> for SourceFile {
213 fn as_ref(&self) -> &FileName {
214 self.path()
Nika Layzellf8d5f212017-12-11 14:07:02 -0500215 }
216}
217
218impl fmt::Debug for SourceFile {
219 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
220 f.debug_struct("SourceFile")
Nika Layzellb35a9a32017-12-30 14:34:35 -0500221 .field("path", &self.path())
Nika Layzellf8d5f212017-12-11 14:07:02 -0500222 .field("is_real", &self.is_real())
223 .finish()
224 }
225}
226
227#[derive(Clone, Copy, Debug, PartialEq, Eq)]
228pub struct LineColumn {
229 pub line: usize,
230 pub column: usize,
231}
232
David Tolnay1ebe3972018-01-02 20:14:20 -0800233#[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500234thread_local! {
235 static CODEMAP: RefCell<Codemap> = RefCell::new(Codemap {
236 // NOTE: We start with a single dummy file which all call_site() and
237 // def_site() spans reference.
238 files: vec![FileInfo {
239 name: "<unspecified>".to_owned(),
240 span: Span { lo: 0, hi: 0 },
241 lines: vec![0],
242 }],
243 });
244}
245
David Tolnay1ebe3972018-01-02 20:14:20 -0800246#[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500247struct FileInfo {
248 name: String,
249 span: Span,
250 lines: Vec<usize>,
251}
252
David Tolnay1ebe3972018-01-02 20:14:20 -0800253#[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500254impl FileInfo {
255 fn offset_line_column(&self, offset: usize) -> LineColumn {
David Tolnayb28f38a2018-03-31 22:02:29 +0200256 assert!(self.span_within(Span {
257 lo: offset as u32,
258 hi: offset as u32
259 }));
Nika Layzellf8d5f212017-12-11 14:07:02 -0500260 let offset = offset - self.span.lo as usize;
261 match self.lines.binary_search(&offset) {
262 Ok(found) => LineColumn {
263 line: found + 1,
David Tolnayb28f38a2018-03-31 22:02:29 +0200264 column: 0,
Nika Layzellf8d5f212017-12-11 14:07:02 -0500265 },
266 Err(idx) => LineColumn {
267 line: idx,
David Tolnayb28f38a2018-03-31 22:02:29 +0200268 column: offset - self.lines[idx - 1],
Nika Layzellf8d5f212017-12-11 14:07:02 -0500269 },
270 }
271 }
272
273 fn span_within(&self, span: Span) -> bool {
274 span.lo >= self.span.lo && span.hi <= self.span.hi
275 }
276}
277
Alex Crichtona914a612018-04-04 07:48:44 -0700278/// Computesthe offsets of each line in the given source string.
David Tolnay1ebe3972018-01-02 20:14:20 -0800279#[cfg(procmacro2_semver_exempt)]
Nika Layzella0a7c3d2017-12-30 14:52:39 -0500280fn lines_offsets(s: &str) -> Vec<usize> {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500281 let mut lines = vec![0];
282 let mut prev = 0;
Nika Layzella0a7c3d2017-12-30 14:52:39 -0500283 while let Some(len) = s[prev..].find('\n') {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500284 prev += len + 1;
285 lines.push(prev);
286 }
287 lines
288}
289
David Tolnay1ebe3972018-01-02 20:14:20 -0800290#[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500291struct Codemap {
292 files: Vec<FileInfo>,
293}
294
David Tolnay1ebe3972018-01-02 20:14:20 -0800295#[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500296impl Codemap {
297 fn next_start_pos(&self) -> u32 {
298 // Add 1 so there's always space between files.
299 //
300 // We'll always have at least 1 file, as we initialize our files list
301 // with a dummy file.
302 self.files.last().unwrap().span.hi + 1
303 }
304
305 fn add_file(&mut self, name: &str, src: &str) -> Span {
Nika Layzella0a7c3d2017-12-30 14:52:39 -0500306 let lines = lines_offsets(src);
Nika Layzellf8d5f212017-12-11 14:07:02 -0500307 let lo = self.next_start_pos();
308 // XXX(nika): Shouild we bother doing a checked cast or checked add here?
David Tolnayb28f38a2018-03-31 22:02:29 +0200309 let span = Span {
310 lo: lo,
311 hi: lo + (src.len() as u32),
312 };
Nika Layzellf8d5f212017-12-11 14:07:02 -0500313
314 self.files.push(FileInfo {
315 name: name.to_owned(),
316 span: span,
317 lines: lines,
318 });
319
320 span
321 }
322
323 fn fileinfo(&self, span: Span) -> &FileInfo {
324 for file in &self.files {
325 if file.span_within(span) {
326 return file;
327 }
328 }
329 panic!("Invalid span with no related FileInfo!");
330 }
331}
332
David Tolnay034205f2018-04-22 16:45:28 -0700333#[derive(Clone, Copy, PartialEq, Eq)]
David Tolnayddfca052017-12-31 10:41:24 -0500334pub struct Span {
David Tolnay1ebe3972018-01-02 20:14:20 -0800335 #[cfg(procmacro2_semver_exempt)]
David Tolnayddfca052017-12-31 10:41:24 -0500336 lo: u32,
David Tolnay1ebe3972018-01-02 20:14:20 -0800337 #[cfg(procmacro2_semver_exempt)]
David Tolnayddfca052017-12-31 10:41:24 -0500338 hi: u32,
339}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700340
341impl Span {
David Tolnay1ebe3972018-01-02 20:14:20 -0800342 #[cfg(not(procmacro2_semver_exempt))]
Alex Crichton44bffbc2017-05-19 17:51:59 -0700343 pub fn call_site() -> Span {
David Tolnay79105e52017-12-31 11:03:04 -0500344 Span {}
345 }
346
David Tolnay1ebe3972018-01-02 20:14:20 -0800347 #[cfg(procmacro2_semver_exempt)]
David Tolnay79105e52017-12-31 11:03:04 -0500348 pub fn call_site() -> Span {
349 Span { lo: 0, hi: 0 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700350 }
Alex Crichtone6085b72017-11-21 07:24:25 -0800351
352 pub fn def_site() -> Span {
David Tolnay79105e52017-12-31 11:03:04 -0500353 Span::call_site()
Nika Layzellf8d5f212017-12-11 14:07:02 -0500354 }
355
David Tolnay4e8e3972018-01-05 18:10:22 -0800356 pub fn resolved_at(&self, _other: Span) -> Span {
357 // Stable spans consist only of line/column information, so
358 // `resolved_at` and `located_at` only select which span the
359 // caller wants line/column information from.
360 *self
361 }
362
363 pub fn located_at(&self, other: Span) -> Span {
364 other
365 }
366
David Tolnay1ebe3972018-01-02 20:14:20 -0800367 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500368 pub fn source_file(&self) -> SourceFile {
369 CODEMAP.with(|cm| {
370 let cm = cm.borrow();
371 let fi = cm.fileinfo(*self);
372 SourceFile {
Nika Layzellb35a9a32017-12-30 14:34:35 -0500373 name: FileName(fi.name.clone()),
Nika Layzellf8d5f212017-12-11 14:07:02 -0500374 }
375 })
376 }
377
David Tolnay1ebe3972018-01-02 20:14:20 -0800378 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500379 pub fn start(&self) -> LineColumn {
380 CODEMAP.with(|cm| {
381 let cm = cm.borrow();
382 let fi = cm.fileinfo(*self);
383 fi.offset_line_column(self.lo as usize)
384 })
385 }
386
David Tolnay1ebe3972018-01-02 20:14:20 -0800387 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500388 pub fn end(&self) -> LineColumn {
389 CODEMAP.with(|cm| {
390 let cm = cm.borrow();
391 let fi = cm.fileinfo(*self);
392 fi.offset_line_column(self.hi as usize)
393 })
394 }
395
David Tolnay1ebe3972018-01-02 20:14:20 -0800396 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500397 pub fn join(&self, other: Span) -> Option<Span> {
398 CODEMAP.with(|cm| {
399 let cm = cm.borrow();
400 // If `other` is not within the same FileInfo as us, return None.
401 if !cm.fileinfo(*self).span_within(other) {
402 return None;
403 }
404 Some(Span {
405 lo: cmp::min(self.lo, other.lo),
406 hi: cmp::max(self.hi, other.hi),
407 })
408 })
Alex Crichtone6085b72017-11-21 07:24:25 -0800409 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700410}
411
David Tolnay034205f2018-04-22 16:45:28 -0700412impl fmt::Debug for Span {
413 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
414 #[cfg(procmacro2_semver_exempt)]
415 return write!(f, "bytes({}..{})", self.lo, self.hi);
416
417 #[cfg(not(procmacro2_semver_exempt))]
418 write!(f, "Span")
419 }
420}
421
Alex Crichtonf3888432018-05-16 09:11:05 -0700422#[derive(Clone)]
423pub struct Ident {
David Tolnayc2309ca2018-06-02 15:47:57 -0700424 sym: String,
Alex Crichtonb2c94622018-04-04 07:36:41 -0700425 span: Span,
Alex Crichtonf3888432018-05-16 09:11:05 -0700426 raw: bool,
David Tolnay041bcd42017-06-03 09:18:04 -0700427}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700428
Alex Crichtonf3888432018-05-16 09:11:05 -0700429impl Ident {
430 fn _new(string: &str, raw: bool, span: Span) -> Ident {
David Tolnay489c6422018-04-07 08:37:28 -0700431 validate_term(string);
432
Alex Crichtonf3888432018-05-16 09:11:05 -0700433 Ident {
David Tolnayc2309ca2018-06-02 15:47:57 -0700434 sym: string.to_owned(),
Alex Crichtona914a612018-04-04 07:48:44 -0700435 span: span,
Alex Crichtonf3888432018-05-16 09:11:05 -0700436 raw: raw,
David Tolnay041bcd42017-06-03 09:18:04 -0700437 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700438 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700439
Alex Crichtonf3888432018-05-16 09:11:05 -0700440 pub fn new(string: &str, span: Span) -> Ident {
441 Ident::_new(string, false, span)
442 }
443
444 pub fn new_raw(string: &str, span: Span) -> Ident {
445 Ident::_new(string, true, span)
446 }
447
Alex Crichtonb2c94622018-04-04 07:36:41 -0700448 pub fn span(&self) -> Span {
449 self.span
450 }
451
452 pub fn set_span(&mut self, span: Span) {
453 self.span = span;
454 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700455}
456
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000457#[inline]
458fn is_ident_start(c: char) -> bool {
David Tolnay03b43da2018-06-02 15:25:57 -0700459 ('a' <= c && c <= 'z')
460 || ('A' <= c && c <= 'Z')
461 || c == '_'
462 || (c > '\x7f' && UnicodeXID::is_xid_start(c))
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000463}
464
465#[inline]
466fn is_ident_continue(c: char) -> bool {
David Tolnay03b43da2018-06-02 15:25:57 -0700467 ('a' <= c && c <= 'z')
468 || ('A' <= c && c <= 'Z')
469 || c == '_'
470 || ('0' <= c && c <= '9')
471 || (c > '\x7f' && UnicodeXID::is_xid_continue(c))
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000472}
473
David Tolnay489c6422018-04-07 08:37:28 -0700474fn validate_term(string: &str) {
Alex Crichtonf3888432018-05-16 09:11:05 -0700475 let validate = string;
David Tolnay489c6422018-04-07 08:37:28 -0700476 if validate.is_empty() {
Alex Crichtonf3888432018-05-16 09:11:05 -0700477 panic!("Ident is not allowed to be empty; use Option<Ident>");
David Tolnay489c6422018-04-07 08:37:28 -0700478 }
479
480 if validate.bytes().all(|digit| digit >= b'0' && digit <= b'9') {
Alex Crichtonf3888432018-05-16 09:11:05 -0700481 panic!("Ident cannot be a number; use Literal instead");
David Tolnay489c6422018-04-07 08:37:28 -0700482 }
483
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000484 fn ident_ok(string: &str) -> bool {
David Tolnay489c6422018-04-07 08:37:28 -0700485 let mut chars = string.chars();
486 let first = chars.next().unwrap();
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000487 if !is_ident_start(first) {
David Tolnay489c6422018-04-07 08:37:28 -0700488 return false;
489 }
490 for ch in chars {
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000491 if !is_ident_continue(ch) {
David Tolnay489c6422018-04-07 08:37:28 -0700492 return false;
493 }
494 }
495 true
496 }
497
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000498 if !ident_ok(validate) {
Alex Crichtonf3888432018-05-16 09:11:05 -0700499 panic!("{:?} is not a valid Ident", string);
David Tolnay489c6422018-04-07 08:37:28 -0700500 }
501}
502
David Tolnayc0b0f2e2018-09-02 17:56:08 -0700503impl PartialEq for Ident {
504 fn eq(&self, other: &Ident) -> bool {
505 self.sym == other.sym && self.raw == other.raw
506 }
507}
508
509impl<T> PartialEq<T> for Ident
510where
511 T: ?Sized + AsRef<str>,
512{
513 fn eq(&self, other: &T) -> bool {
514 let other = other.as_ref();
515 if self.raw {
516 other.starts_with("r#") && self.sym == other[2..]
517 } else {
518 self.sym == other
519 }
520 }
521}
522
Alex Crichtonf3888432018-05-16 09:11:05 -0700523impl fmt::Display for Ident {
David Tolnay8ad3e3e2017-06-03 16:45:00 -0700524 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Alex Crichtonf3888432018-05-16 09:11:05 -0700525 if self.raw {
526 "r#".fmt(f)?;
527 }
David Tolnayc2309ca2018-06-02 15:47:57 -0700528 self.sym.fmt(f)
Alex Crichtonf3888432018-05-16 09:11:05 -0700529 }
530}
531
532impl fmt::Debug for Ident {
David Tolnayd8fcdb82018-06-02 15:43:53 -0700533 // Ident(proc_macro), Ident(r#union)
534 #[cfg(not(procmacro2_semver_exempt))]
535 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
536 let mut debug = f.debug_tuple("Ident");
537 debug.field(&format_args!("{}", self));
538 debug.finish()
539 }
540
541 // Ident {
542 // sym: proc_macro,
543 // span: bytes(128..138)
544 // }
545 #[cfg(procmacro2_semver_exempt)]
Alex Crichtonf3888432018-05-16 09:11:05 -0700546 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
547 let mut debug = f.debug_struct("Ident");
David Tolnayd8fcdb82018-06-02 15:43:53 -0700548 debug.field("sym", &format_args!("{}", self));
David Tolnay034205f2018-04-22 16:45:28 -0700549 debug.field("span", &self.span);
550 debug.finish()
David Tolnay8ad3e3e2017-06-03 16:45:00 -0700551 }
552}
553
David Tolnay034205f2018-04-22 16:45:28 -0700554#[derive(Clone)]
Alex Crichtonb2c94622018-04-04 07:36:41 -0700555pub struct Literal {
556 text: String,
557 span: Span,
558}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700559
Alex Crichtona914a612018-04-04 07:48:44 -0700560macro_rules! suffixed_numbers {
561 ($($name:ident => $kind:ident,)*) => ($(
562 pub fn $name(n: $kind) -> Literal {
563 Literal::_new(format!(concat!("{}", stringify!($kind)), n))
564 }
565 )*)
566}
567
568macro_rules! unsuffixed_numbers {
569 ($($name:ident => $kind:ident,)*) => ($(
570 pub fn $name(n: $kind) -> Literal {
571 Literal::_new(n.to_string())
572 }
573 )*)
574}
575
Alex Crichton852d53d2017-05-19 19:25:08 -0700576impl Literal {
Alex Crichtonb2c94622018-04-04 07:36:41 -0700577 fn _new(text: String) -> Literal {
578 Literal {
Alex Crichtona914a612018-04-04 07:48:44 -0700579 text: text,
Alex Crichtonb2c94622018-04-04 07:36:41 -0700580 span: Span::call_site(),
581 }
582 }
583
Alex Crichtona914a612018-04-04 07:48:44 -0700584 suffixed_numbers! {
585 u8_suffixed => u8,
586 u16_suffixed => u16,
587 u32_suffixed => u32,
588 u64_suffixed => u64,
589 usize_suffixed => usize,
590 i8_suffixed => i8,
591 i16_suffixed => i16,
592 i32_suffixed => i32,
593 i64_suffixed => i64,
594 isize_suffixed => isize,
595
596 f32_suffixed => f32,
597 f64_suffixed => f64,
598 }
599
600 unsuffixed_numbers! {
601 u8_unsuffixed => u8,
602 u16_unsuffixed => u16,
603 u32_unsuffixed => u32,
604 u64_unsuffixed => u64,
605 usize_unsuffixed => usize,
606 i8_unsuffixed => i8,
607 i16_unsuffixed => i16,
608 i32_unsuffixed => i32,
609 i64_unsuffixed => i64,
610 isize_unsuffixed => isize,
611 }
612
613 pub fn f32_unsuffixed(f: f32) -> Literal {
614 let mut s = f.to_string();
615 if !s.contains(".") {
616 s.push_str(".0");
Alex Crichton76a5cc82017-05-23 07:01:44 -0700617 }
Alex Crichtona914a612018-04-04 07:48:44 -0700618 Literal::_new(s)
619 }
620
621 pub fn f64_unsuffixed(f: f64) -> Literal {
622 let mut s = f.to_string();
623 if !s.contains(".") {
624 s.push_str(".0");
625 }
626 Literal::_new(s)
627 }
628
629 pub fn string(t: &str) -> Literal {
David Tolnay3d9d6ad2018-05-18 10:51:55 -0700630 let mut s = t
631 .chars()
Alex Crichtona914a612018-04-04 07:48:44 -0700632 .flat_map(|c| c.escape_default())
633 .collect::<String>();
634 s.push('"');
635 s.insert(0, '"');
636 Literal::_new(s)
637 }
638
639 pub fn character(t: char) -> Literal {
640 Literal::_new(format!("'{}'", t.escape_default().collect::<String>()))
Alex Crichton76a5cc82017-05-23 07:01:44 -0700641 }
642
Alex Crichton9c2fb0a2017-05-26 08:49:31 -0700643 pub fn byte_string(bytes: &[u8]) -> Literal {
Alex Crichton852d53d2017-05-19 19:25:08 -0700644 let mut escaped = "b\"".to_string();
645 for b in bytes {
646 match *b {
647 b'\0' => escaped.push_str(r"\0"),
648 b'\t' => escaped.push_str(r"\t"),
649 b'\n' => escaped.push_str(r"\n"),
650 b'\r' => escaped.push_str(r"\r"),
651 b'"' => escaped.push_str("\\\""),
652 b'\\' => escaped.push_str("\\\\"),
David Tolnayb28f38a2018-03-31 22:02:29 +0200653 b'\x20'...b'\x7E' => escaped.push(*b as char),
Alex Crichton852d53d2017-05-19 19:25:08 -0700654 _ => escaped.push_str(&format!("\\x{:02X}", b)),
655 }
656 }
657 escaped.push('"');
Alex Crichtonb2c94622018-04-04 07:36:41 -0700658 Literal::_new(escaped)
Alex Crichton76a5cc82017-05-23 07:01:44 -0700659 }
Alex Crichton9c2fb0a2017-05-26 08:49:31 -0700660
Alex Crichtonb2c94622018-04-04 07:36:41 -0700661 pub fn span(&self) -> Span {
662 self.span
Alex Crichton31316622017-05-26 12:54:47 -0700663 }
664
Alex Crichtonb2c94622018-04-04 07:36:41 -0700665 pub fn set_span(&mut self, span: Span) {
666 self.span = span;
Alex Crichton31316622017-05-26 12:54:47 -0700667 }
Alex Crichton852d53d2017-05-19 19:25:08 -0700668}
669
Alex Crichton44bffbc2017-05-19 17:51:59 -0700670impl fmt::Display for Literal {
671 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Alex Crichtonb2c94622018-04-04 07:36:41 -0700672 self.text.fmt(f)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700673 }
674}
675
David Tolnay034205f2018-04-22 16:45:28 -0700676impl fmt::Debug for Literal {
677 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
678 let mut debug = fmt.debug_struct("Literal");
679 debug.field("lit", &format_args!("{}", self.text));
680 #[cfg(procmacro2_semver_exempt)]
681 debug.field("span", &self.span);
682 debug.finish()
683 }
684}
685
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700686fn token_stream(mut input: Cursor) -> PResult<TokenStream> {
Alex Crichton1eb96a02018-04-04 13:07:35 -0700687 let mut trees = Vec::new();
688 loop {
689 let input_no_ws = skip_whitespace(input);
690 if input_no_ws.rest.len() == 0 {
David Tolnay48ea5042018-04-23 19:17:35 -0700691 break;
Alex Crichton1eb96a02018-04-04 13:07:35 -0700692 }
693 if let Ok((a, tokens)) = doc_comment(input_no_ws) {
694 input = a;
695 trees.extend(tokens);
David Tolnay48ea5042018-04-23 19:17:35 -0700696 continue;
Alex Crichton1eb96a02018-04-04 13:07:35 -0700697 }
698
699 let (a, tt) = match token_tree(input_no_ws) {
700 Ok(p) => p,
701 Err(_) => break,
702 };
703 trees.push(tt);
704 input = a;
705 }
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700706 Ok((input, TokenStream { inner: trees }))
Alex Crichton1eb96a02018-04-04 13:07:35 -0700707}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700708
David Tolnay1ebe3972018-01-02 20:14:20 -0800709#[cfg(not(procmacro2_semver_exempt))]
Alex Crichton1eb96a02018-04-04 13:07:35 -0700710fn spanned<'a, T>(
711 input: Cursor<'a>,
712 f: fn(Cursor<'a>) -> PResult<'a, T>,
713) -> PResult<'a, (T, ::Span)> {
714 let (a, b) = f(skip_whitespace(input))?;
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700715 Ok((a, ((b, ::Span::_new_stable(Span {})))))
David Tolnayddfca052017-12-31 10:41:24 -0500716}
717
David Tolnay1ebe3972018-01-02 20:14:20 -0800718#[cfg(procmacro2_semver_exempt)]
Alex Crichton1eb96a02018-04-04 13:07:35 -0700719fn spanned<'a, T>(
720 input: Cursor<'a>,
721 f: fn(Cursor<'a>) -> PResult<'a, T>,
722) -> PResult<'a, (T, ::Span)> {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500723 let input = skip_whitespace(input);
724 let lo = input.off;
Alex Crichton1eb96a02018-04-04 13:07:35 -0700725 let (a, b) = f(input)?;
726 let hi = a.off;
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700727 let span = ::Span::_new_stable(Span { lo: lo, hi: hi });
Alex Crichton1eb96a02018-04-04 13:07:35 -0700728 Ok((a, (b, span)))
729}
730
731fn token_tree(input: Cursor) -> PResult<TokenTree> {
732 let (rest, (mut tt, span)) = spanned(input, token_kind)?;
733 tt.set_span(span);
734 Ok((rest, tt))
Nika Layzellf8d5f212017-12-11 14:07:02 -0500735}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700736
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700737named!(token_kind -> TokenTree, alt!(
738 map!(group, TokenTree::Group)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700739 |
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700740 map!(literal, |l| TokenTree::Literal(::Literal::_new_stable(l))) // must be before symbol
Alex Crichton44bffbc2017-05-19 17:51:59 -0700741 |
Alex Crichtonf3888432018-05-16 09:11:05 -0700742 map!(op, TokenTree::Punct)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700743 |
Alex Crichtonf3888432018-05-16 09:11:05 -0700744 symbol_leading_ws
Alex Crichton44bffbc2017-05-19 17:51:59 -0700745));
746
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700747named!(group -> Group, alt!(
Alex Crichton44bffbc2017-05-19 17:51:59 -0700748 delimited!(
749 punct!("("),
750 token_stream,
751 punct!(")")
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700752 ) => { |ts| Group::new(Delimiter::Parenthesis, ::TokenStream::_new_stable(ts)) }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700753 |
754 delimited!(
755 punct!("["),
756 token_stream,
757 punct!("]")
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700758 ) => { |ts| Group::new(Delimiter::Bracket, ::TokenStream::_new_stable(ts)) }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700759 |
760 delimited!(
761 punct!("{"),
762 token_stream,
763 punct!("}")
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700764 ) => { |ts| Group::new(Delimiter::Brace, ::TokenStream::_new_stable(ts)) }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700765));
766
Alex Crichtonf3888432018-05-16 09:11:05 -0700767fn symbol_leading_ws(input: Cursor) -> PResult<TokenTree> {
768 symbol(skip_whitespace(input))
769}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700770
Alex Crichtonf3888432018-05-16 09:11:05 -0700771fn symbol(input: Cursor) -> PResult<TokenTree> {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700772 let mut chars = input.char_indices();
David Tolnaya202d502017-06-01 12:26:55 -0700773
Alex Crichtonf3888432018-05-16 09:11:05 -0700774 let raw = input.starts_with("r#");
David Tolnaya13d1422018-03-31 21:27:48 +0200775 if raw {
776 chars.next();
777 chars.next();
778 }
779
Alex Crichton44bffbc2017-05-19 17:51:59 -0700780 match chars.next() {
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000781 Some((_, ch)) if is_ident_start(ch) => {}
David Tolnay1218e122017-06-01 11:13:45 -0700782 _ => return Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -0700783 }
784
David Tolnay214c94c2017-06-01 12:42:56 -0700785 let mut end = input.len();
Alex Crichton44bffbc2017-05-19 17:51:59 -0700786 for (i, ch) in chars {
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000787 if !is_ident_continue(ch) {
David Tolnay214c94c2017-06-01 12:42:56 -0700788 end = i;
789 break;
Alex Crichton44bffbc2017-05-19 17:51:59 -0700790 }
791 }
792
David Tolnaya13d1422018-03-31 21:27:48 +0200793 let a = &input.rest[..end];
Alex Crichtonf3888432018-05-16 09:11:05 -0700794 if a == "r#_" {
David Tolnay214c94c2017-06-01 12:42:56 -0700795 Err(LexError)
796 } else {
Alex Crichtonf3888432018-05-16 09:11:05 -0700797 let ident = if raw {
798 ::Ident::_new_raw(&a[2..], ::Span::call_site())
799 } else {
800 ::Ident::new(a, ::Span::call_site())
801 };
802 Ok((input.advance(end), ident.into()))
David Tolnay214c94c2017-06-01 12:42:56 -0700803 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700804}
805
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700806fn literal(input: Cursor) -> PResult<Literal> {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700807 let input_no_ws = skip_whitespace(input);
808
809 match literal_nocapture(input_no_ws) {
David Tolnay1218e122017-06-01 11:13:45 -0700810 Ok((a, ())) => {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700811 let start = input.len() - input_no_ws.len();
812 let len = input_no_ws.len() - a.len();
813 let end = start + len;
David Tolnay3d9d6ad2018-05-18 10:51:55 -0700814 Ok((a, Literal::_new(input.rest[start..end].to_string())))
Alex Crichton44bffbc2017-05-19 17:51:59 -0700815 }
David Tolnay1218e122017-06-01 11:13:45 -0700816 Err(LexError) => Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -0700817 }
818}
819
820named!(literal_nocapture -> (), alt!(
821 string
822 |
823 byte_string
824 |
825 byte
826 |
827 character
828 |
829 float
830 |
831 int
Alex Crichton44bffbc2017-05-19 17:51:59 -0700832));
833
834named!(string -> (), alt!(
835 quoted_string
836 |
837 preceded!(
838 punct!("r"),
839 raw_string
840 ) => { |_| () }
841));
842
843named!(quoted_string -> (), delimited!(
844 punct!("\""),
845 cooked_string,
846 tag!("\"")
847));
848
Nika Layzellf8d5f212017-12-11 14:07:02 -0500849fn cooked_string(input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700850 let mut chars = input.char_indices().peekable();
851 while let Some((byte_offset, ch)) = chars.next() {
852 match ch {
853 '"' => {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500854 return Ok((input.advance(byte_offset), ()));
Alex Crichton44bffbc2017-05-19 17:51:59 -0700855 }
856 '\r' => {
857 if let Some((_, '\n')) = chars.next() {
858 // ...
859 } else {
860 break;
861 }
862 }
David Tolnayb28f38a2018-03-31 22:02:29 +0200863 '\\' => match chars.next() {
864 Some((_, 'x')) => {
865 if !backslash_x_char(&mut chars) {
866 break;
Alex Crichton44bffbc2017-05-19 17:51:59 -0700867 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700868 }
David Tolnayb28f38a2018-03-31 22:02:29 +0200869 Some((_, 'n')) | Some((_, 'r')) | Some((_, 't')) | Some((_, '\\'))
870 | Some((_, '\'')) | Some((_, '"')) | Some((_, '0')) => {}
871 Some((_, 'u')) => {
872 if !backslash_u(&mut chars) {
873 break;
874 }
875 }
876 Some((_, '\n')) | Some((_, '\r')) => {
877 while let Some(&(_, ch)) = chars.peek() {
878 if ch.is_whitespace() {
879 chars.next();
880 } else {
881 break;
882 }
883 }
884 }
885 _ => break,
886 },
Alex Crichton44bffbc2017-05-19 17:51:59 -0700887 _ch => {}
888 }
889 }
David Tolnay1218e122017-06-01 11:13:45 -0700890 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700891}
892
893named!(byte_string -> (), alt!(
894 delimited!(
895 punct!("b\""),
896 cooked_byte_string,
897 tag!("\"")
898 ) => { |_| () }
899 |
900 preceded!(
901 punct!("br"),
902 raw_string
903 ) => { |_| () }
904));
905
Nika Layzellf8d5f212017-12-11 14:07:02 -0500906fn cooked_byte_string(mut input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700907 let mut bytes = input.bytes().enumerate();
908 'outer: while let Some((offset, b)) = bytes.next() {
909 match b {
910 b'"' => {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500911 return Ok((input.advance(offset), ()));
Alex Crichton44bffbc2017-05-19 17:51:59 -0700912 }
913 b'\r' => {
914 if let Some((_, b'\n')) = bytes.next() {
915 // ...
916 } else {
917 break;
918 }
919 }
David Tolnayb28f38a2018-03-31 22:02:29 +0200920 b'\\' => match bytes.next() {
921 Some((_, b'x')) => {
922 if !backslash_x_byte(&mut bytes) {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700923 break;
924 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700925 }
David Tolnayb28f38a2018-03-31 22:02:29 +0200926 Some((_, b'n')) | Some((_, b'r')) | Some((_, b't')) | Some((_, b'\\'))
927 | Some((_, b'0')) | Some((_, b'\'')) | Some((_, b'"')) => {}
928 Some((newline, b'\n')) | Some((newline, b'\r')) => {
929 let rest = input.advance(newline + 1);
930 for (offset, ch) in rest.char_indices() {
931 if !ch.is_whitespace() {
932 input = rest.advance(offset);
933 bytes = input.bytes().enumerate();
934 continue 'outer;
935 }
936 }
937 break;
938 }
939 _ => break,
940 },
Alex Crichton44bffbc2017-05-19 17:51:59 -0700941 b if b < 0x80 => {}
942 _ => break,
943 }
944 }
David Tolnay1218e122017-06-01 11:13:45 -0700945 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700946}
947
Nika Layzellf8d5f212017-12-11 14:07:02 -0500948fn raw_string(input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700949 let mut chars = input.char_indices();
950 let mut n = 0;
951 while let Some((byte_offset, ch)) = chars.next() {
952 match ch {
953 '"' => {
954 n = byte_offset;
955 break;
956 }
957 '#' => {}
David Tolnay1218e122017-06-01 11:13:45 -0700958 _ => return Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -0700959 }
960 }
961 for (byte_offset, ch) in chars {
962 match ch {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500963 '"' if input.advance(byte_offset + 1).starts_with(&input.rest[..n]) => {
964 let rest = input.advance(byte_offset + 1 + n);
David Tolnayb28f38a2018-03-31 22:02:29 +0200965 return Ok((rest, ()));
Alex Crichton44bffbc2017-05-19 17:51:59 -0700966 }
967 '\r' => {}
968 _ => {}
969 }
970 }
David Tolnay1218e122017-06-01 11:13:45 -0700971 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700972}
973
974named!(byte -> (), do_parse!(
975 punct!("b") >>
976 tag!("'") >>
977 cooked_byte >>
978 tag!("'") >>
979 (())
980));
981
Nika Layzellf8d5f212017-12-11 14:07:02 -0500982fn cooked_byte(input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700983 let mut bytes = input.bytes().enumerate();
984 let ok = match bytes.next().map(|(_, b)| b) {
David Tolnayb28f38a2018-03-31 22:02:29 +0200985 Some(b'\\') => match bytes.next().map(|(_, b)| b) {
986 Some(b'x') => backslash_x_byte(&mut bytes),
987 Some(b'n') | Some(b'r') | Some(b't') | Some(b'\\') | Some(b'0') | Some(b'\'')
988 | Some(b'"') => true,
989 _ => false,
990 },
Alex Crichton44bffbc2017-05-19 17:51:59 -0700991 b => b.is_some(),
992 };
993 if ok {
994 match bytes.next() {
Alex Crichton8c030332018-01-16 08:07:36 -0800995 Some((offset, _)) => {
996 if input.chars().as_str().is_char_boundary(offset) {
997 Ok((input.advance(offset), ()))
998 } else {
999 Err(LexError)
1000 }
1001 }
Nika Layzellf8d5f212017-12-11 14:07:02 -05001002 None => Ok((input.advance(input.len()), ())),
Alex Crichton44bffbc2017-05-19 17:51:59 -07001003 }
1004 } else {
David Tolnay1218e122017-06-01 11:13:45 -07001005 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001006 }
1007}
1008
1009named!(character -> (), do_parse!(
1010 punct!("'") >>
1011 cooked_char >>
1012 tag!("'") >>
1013 (())
1014));
1015
Nika Layzellf8d5f212017-12-11 14:07:02 -05001016fn cooked_char(input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001017 let mut chars = input.char_indices();
1018 let ok = match chars.next().map(|(_, ch)| ch) {
David Tolnayb28f38a2018-03-31 22:02:29 +02001019 Some('\\') => match chars.next().map(|(_, ch)| ch) {
1020 Some('x') => backslash_x_char(&mut chars),
1021 Some('u') => backslash_u(&mut chars),
1022 Some('n') | Some('r') | Some('t') | Some('\\') | Some('0') | Some('\'') | Some('"') => {
1023 true
Alex Crichton44bffbc2017-05-19 17:51:59 -07001024 }
David Tolnayb28f38a2018-03-31 22:02:29 +02001025 _ => false,
1026 },
Alex Crichton44bffbc2017-05-19 17:51:59 -07001027 ch => ch.is_some(),
1028 };
1029 if ok {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001030 match chars.next() {
1031 Some((idx, _)) => Ok((input.advance(idx), ())),
1032 None => Ok((input.advance(input.len()), ())),
1033 }
Alex Crichton44bffbc2017-05-19 17:51:59 -07001034 } else {
David Tolnay1218e122017-06-01 11:13:45 -07001035 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001036 }
1037}
1038
1039macro_rules! next_ch {
1040 ($chars:ident @ $pat:pat $(| $rest:pat)*) => {
1041 match $chars.next() {
1042 Some((_, ch)) => match ch {
1043 $pat $(| $rest)* => ch,
1044 _ => return false,
1045 },
1046 None => return false
1047 }
1048 };
1049}
1050
1051fn backslash_x_char<I>(chars: &mut I) -> bool
David Tolnayb28f38a2018-03-31 22:02:29 +02001052where
1053 I: Iterator<Item = (usize, char)>,
Alex Crichton44bffbc2017-05-19 17:51:59 -07001054{
1055 next_ch!(chars @ '0'...'7');
1056 next_ch!(chars @ '0'...'9' | 'a'...'f' | 'A'...'F');
1057 true
1058}
1059
1060fn backslash_x_byte<I>(chars: &mut I) -> bool
David Tolnayb28f38a2018-03-31 22:02:29 +02001061where
1062 I: Iterator<Item = (usize, u8)>,
Alex Crichton44bffbc2017-05-19 17:51:59 -07001063{
1064 next_ch!(chars @ b'0'...b'9' | b'a'...b'f' | b'A'...b'F');
1065 next_ch!(chars @ b'0'...b'9' | b'a'...b'f' | b'A'...b'F');
1066 true
1067}
1068
1069fn backslash_u<I>(chars: &mut I) -> bool
David Tolnayb28f38a2018-03-31 22:02:29 +02001070where
1071 I: Iterator<Item = (usize, char)>,
Alex Crichton44bffbc2017-05-19 17:51:59 -07001072{
1073 next_ch!(chars @ '{');
1074 next_ch!(chars @ '0'...'9' | 'a'...'f' | 'A'...'F');
David Tolnay8d109342017-12-25 18:24:45 -05001075 loop {
1076 let c = next_ch!(chars @ '0'...'9' | 'a'...'f' | 'A'...'F' | '_' | '}');
1077 if c == '}' {
1078 return true;
1079 }
Alex Crichton44bffbc2017-05-19 17:51:59 -07001080 }
Alex Crichton44bffbc2017-05-19 17:51:59 -07001081}
1082
Nika Layzellf8d5f212017-12-11 14:07:02 -05001083fn float(input: Cursor) -> PResult<()> {
David Tolnay744a6b82017-06-01 11:34:29 -07001084 let (rest, ()) = float_digits(input)?;
1085 for suffix in &["f32", "f64"] {
1086 if rest.starts_with(suffix) {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001087 return word_break(rest.advance(suffix.len()));
David Tolnay744a6b82017-06-01 11:34:29 -07001088 }
1089 }
1090 word_break(rest)
1091}
Alex Crichton44bffbc2017-05-19 17:51:59 -07001092
Nika Layzellf8d5f212017-12-11 14:07:02 -05001093fn float_digits(input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001094 let mut chars = input.chars().peekable();
1095 match chars.next() {
1096 Some(ch) if ch >= '0' && ch <= '9' => {}
David Tolnay1218e122017-06-01 11:13:45 -07001097 _ => return Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -07001098 }
1099
1100 let mut len = 1;
1101 let mut has_dot = false;
1102 let mut has_exp = false;
1103 while let Some(&ch) = chars.peek() {
1104 match ch {
1105 '0'...'9' | '_' => {
1106 chars.next();
1107 len += 1;
1108 }
1109 '.' => {
1110 if has_dot {
1111 break;
1112 }
1113 chars.next();
David Tolnayb28f38a2018-03-31 22:02:29 +02001114 if chars
1115 .peek()
1116 .map(|&ch| ch == '.' || UnicodeXID::is_xid_start(ch))
1117 .unwrap_or(false)
1118 {
David Tolnay1218e122017-06-01 11:13:45 -07001119 return Err(LexError);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001120 }
1121 len += 1;
1122 has_dot = true;
1123 }
1124 'e' | 'E' => {
1125 chars.next();
1126 len += 1;
1127 has_exp = true;
1128 break;
1129 }
1130 _ => break,
1131 }
1132 }
1133
Nika Layzellf8d5f212017-12-11 14:07:02 -05001134 let rest = input.advance(len);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001135 if !(has_dot || has_exp || rest.starts_with("f32") || rest.starts_with("f64")) {
David Tolnay1218e122017-06-01 11:13:45 -07001136 return Err(LexError);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001137 }
1138
1139 if has_exp {
1140 let mut has_exp_value = false;
1141 while let Some(&ch) = chars.peek() {
1142 match ch {
1143 '+' | '-' => {
1144 if has_exp_value {
1145 break;
1146 }
1147 chars.next();
1148 len += 1;
1149 }
1150 '0'...'9' => {
1151 chars.next();
1152 len += 1;
1153 has_exp_value = true;
1154 }
1155 '_' => {
1156 chars.next();
1157 len += 1;
1158 }
1159 _ => break,
1160 }
1161 }
1162 if !has_exp_value {
David Tolnay1218e122017-06-01 11:13:45 -07001163 return Err(LexError);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001164 }
1165 }
1166
Nika Layzellf8d5f212017-12-11 14:07:02 -05001167 Ok((input.advance(len), ()))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001168}
1169
Nika Layzellf8d5f212017-12-11 14:07:02 -05001170fn int(input: Cursor) -> PResult<()> {
David Tolnay744a6b82017-06-01 11:34:29 -07001171 let (rest, ()) = digits(input)?;
1172 for suffix in &[
David Tolnay48ea5042018-04-23 19:17:35 -07001173 "isize", "i8", "i16", "i32", "i64", "i128", "usize", "u8", "u16", "u32", "u64", "u128",
David Tolnay744a6b82017-06-01 11:34:29 -07001174 ] {
1175 if rest.starts_with(suffix) {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001176 return word_break(rest.advance(suffix.len()));
David Tolnay744a6b82017-06-01 11:34:29 -07001177 }
1178 }
1179 word_break(rest)
1180}
Alex Crichton44bffbc2017-05-19 17:51:59 -07001181
Nika Layzellf8d5f212017-12-11 14:07:02 -05001182fn digits(mut input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001183 let base = if input.starts_with("0x") {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001184 input = input.advance(2);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001185 16
1186 } else if input.starts_with("0o") {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001187 input = input.advance(2);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001188 8
1189 } else if input.starts_with("0b") {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001190 input = input.advance(2);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001191 2
1192 } else {
1193 10
1194 };
1195
Alex Crichton44bffbc2017-05-19 17:51:59 -07001196 let mut len = 0;
1197 let mut empty = true;
1198 for b in input.bytes() {
1199 let digit = match b {
1200 b'0'...b'9' => (b - b'0') as u64,
1201 b'a'...b'f' => 10 + (b - b'a') as u64,
1202 b'A'...b'F' => 10 + (b - b'A') as u64,
1203 b'_' => {
1204 if empty && base == 10 {
David Tolnay1218e122017-06-01 11:13:45 -07001205 return Err(LexError);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001206 }
1207 len += 1;
1208 continue;
1209 }
1210 _ => break,
1211 };
1212 if digit >= base {
David Tolnay1218e122017-06-01 11:13:45 -07001213 return Err(LexError);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001214 }
Alex Crichton44bffbc2017-05-19 17:51:59 -07001215 len += 1;
1216 empty = false;
1217 }
1218 if empty {
David Tolnay1218e122017-06-01 11:13:45 -07001219 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001220 } else {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001221 Ok((input.advance(len), ()))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001222 }
1223}
1224
Alex Crichtonf3888432018-05-16 09:11:05 -07001225fn op(input: Cursor) -> PResult<Punct> {
David Tolnayea75c5f2017-05-31 23:40:33 -07001226 let input = skip_whitespace(input);
1227 match op_char(input) {
Alex Crichtonf3888432018-05-16 09:11:05 -07001228 Ok((rest, '\'')) => {
1229 symbol(rest)?;
1230 Ok((rest, Punct::new('\'', Spacing::Joint)))
1231 }
David Tolnay1218e122017-06-01 11:13:45 -07001232 Ok((rest, ch)) => {
David Tolnayea75c5f2017-05-31 23:40:33 -07001233 let kind = match op_char(rest) {
Alex Crichton1a7f7622017-07-05 17:47:15 -07001234 Ok(_) => Spacing::Joint,
1235 Err(LexError) => Spacing::Alone,
David Tolnayea75c5f2017-05-31 23:40:33 -07001236 };
Alex Crichtonf3888432018-05-16 09:11:05 -07001237 Ok((rest, Punct::new(ch, kind)))
David Tolnayea75c5f2017-05-31 23:40:33 -07001238 }
David Tolnay1218e122017-06-01 11:13:45 -07001239 Err(LexError) => Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -07001240 }
1241}
1242
Nika Layzellf8d5f212017-12-11 14:07:02 -05001243fn op_char(input: Cursor) -> PResult<char> {
David Tolnay3a592ad2018-04-22 21:20:24 -07001244 if input.starts_with("//") || input.starts_with("/*") {
1245 // Do not accept `/` of a comment as an op.
1246 return Err(LexError);
1247 }
1248
David Tolnayea75c5f2017-05-31 23:40:33 -07001249 let mut chars = input.chars();
1250 let first = match chars.next() {
1251 Some(ch) => ch,
1252 None => {
David Tolnay1218e122017-06-01 11:13:45 -07001253 return Err(LexError);
David Tolnayea75c5f2017-05-31 23:40:33 -07001254 }
1255 };
Alex Crichtonf3888432018-05-16 09:11:05 -07001256 let recognized = "~!@#$%^&*-=+|;:,<.>/?'";
David Tolnayea75c5f2017-05-31 23:40:33 -07001257 if recognized.contains(first) {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001258 Ok((input.advance(first.len_utf8()), first))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001259 } else {
David Tolnay1218e122017-06-01 11:13:45 -07001260 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001261 }
1262}
1263
Alex Crichton1eb96a02018-04-04 13:07:35 -07001264fn doc_comment(input: Cursor) -> PResult<Vec<TokenTree>> {
1265 let mut trees = Vec::new();
1266 let (rest, ((comment, inner), span)) = spanned(input, doc_comment_contents)?;
Alex Crichtonf3888432018-05-16 09:11:05 -07001267 trees.push(TokenTree::Punct(Punct::new('#', Spacing::Alone)));
Alex Crichton1eb96a02018-04-04 13:07:35 -07001268 if inner {
Alex Crichtonf3888432018-05-16 09:11:05 -07001269 trees.push(Punct::new('!', Spacing::Alone).into());
Alex Crichton1eb96a02018-04-04 13:07:35 -07001270 }
1271 let mut stream = vec![
Alex Crichtonf3888432018-05-16 09:11:05 -07001272 TokenTree::Ident(::Ident::new("doc", span)),
1273 TokenTree::Punct(Punct::new('=', Spacing::Alone)),
Alex Crichton1eb96a02018-04-04 13:07:35 -07001274 TokenTree::Literal(::Literal::string(comment)),
1275 ];
1276 for tt in stream.iter_mut() {
1277 tt.set_span(span);
1278 }
1279 trees.push(Group::new(Delimiter::Bracket, stream.into_iter().collect()).into());
1280 for tt in trees.iter_mut() {
1281 tt.set_span(span);
1282 }
1283 Ok((rest, trees))
1284}
1285
1286named!(doc_comment_contents -> (&str, bool), alt!(
Alex Crichton44bffbc2017-05-19 17:51:59 -07001287 do_parse!(
1288 punct!("//!") >>
Alex Crichton1eb96a02018-04-04 13:07:35 -07001289 s: take_until_newline_or_eof!() >>
1290 ((s, true))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001291 )
1292 |
1293 do_parse!(
1294 option!(whitespace) >>
1295 peek!(tag!("/*!")) >>
Alex Crichton1eb96a02018-04-04 13:07:35 -07001296 s: block_comment >>
1297 ((s, true))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001298 )
1299 |
1300 do_parse!(
1301 punct!("///") >>
1302 not!(tag!("/")) >>
Alex Crichton1eb96a02018-04-04 13:07:35 -07001303 s: take_until_newline_or_eof!() >>
1304 ((s, false))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001305 )
1306 |
1307 do_parse!(
1308 option!(whitespace) >>
1309 peek!(tuple!(tag!("/**"), not!(tag!("*")))) >>
Alex Crichton1eb96a02018-04-04 13:07:35 -07001310 s: block_comment >>
1311 ((s, false))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001312 )
1313));