blob: 30b8e7772b7c353a73c90ad8481ba7889b7ddd03 [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
Alex Crichtonf3888432018-05-16 09:11:05 -0700503impl fmt::Display for Ident {
David Tolnay8ad3e3e2017-06-03 16:45:00 -0700504 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Alex Crichtonf3888432018-05-16 09:11:05 -0700505 if self.raw {
506 "r#".fmt(f)?;
507 }
David Tolnayc2309ca2018-06-02 15:47:57 -0700508 self.sym.fmt(f)
Alex Crichtonf3888432018-05-16 09:11:05 -0700509 }
510}
511
512impl fmt::Debug for Ident {
David Tolnayd8fcdb82018-06-02 15:43:53 -0700513 // Ident(proc_macro), Ident(r#union)
514 #[cfg(not(procmacro2_semver_exempt))]
515 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
516 let mut debug = f.debug_tuple("Ident");
517 debug.field(&format_args!("{}", self));
518 debug.finish()
519 }
520
521 // Ident {
522 // sym: proc_macro,
523 // span: bytes(128..138)
524 // }
525 #[cfg(procmacro2_semver_exempt)]
Alex Crichtonf3888432018-05-16 09:11:05 -0700526 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
527 let mut debug = f.debug_struct("Ident");
David Tolnayd8fcdb82018-06-02 15:43:53 -0700528 debug.field("sym", &format_args!("{}", self));
David Tolnay034205f2018-04-22 16:45:28 -0700529 debug.field("span", &self.span);
530 debug.finish()
David Tolnay8ad3e3e2017-06-03 16:45:00 -0700531 }
532}
533
David Tolnay034205f2018-04-22 16:45:28 -0700534#[derive(Clone)]
Alex Crichtonb2c94622018-04-04 07:36:41 -0700535pub struct Literal {
536 text: String,
537 span: Span,
538}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700539
Alex Crichtona914a612018-04-04 07:48:44 -0700540macro_rules! suffixed_numbers {
541 ($($name:ident => $kind:ident,)*) => ($(
542 pub fn $name(n: $kind) -> Literal {
543 Literal::_new(format!(concat!("{}", stringify!($kind)), n))
544 }
545 )*)
546}
547
548macro_rules! unsuffixed_numbers {
549 ($($name:ident => $kind:ident,)*) => ($(
550 pub fn $name(n: $kind) -> Literal {
551 Literal::_new(n.to_string())
552 }
553 )*)
554}
555
Alex Crichton852d53d2017-05-19 19:25:08 -0700556impl Literal {
Alex Crichtonb2c94622018-04-04 07:36:41 -0700557 fn _new(text: String) -> Literal {
558 Literal {
Alex Crichtona914a612018-04-04 07:48:44 -0700559 text: text,
Alex Crichtonb2c94622018-04-04 07:36:41 -0700560 span: Span::call_site(),
561 }
562 }
563
Alex Crichtona914a612018-04-04 07:48:44 -0700564 suffixed_numbers! {
565 u8_suffixed => u8,
566 u16_suffixed => u16,
567 u32_suffixed => u32,
568 u64_suffixed => u64,
569 usize_suffixed => usize,
570 i8_suffixed => i8,
571 i16_suffixed => i16,
572 i32_suffixed => i32,
573 i64_suffixed => i64,
574 isize_suffixed => isize,
575
576 f32_suffixed => f32,
577 f64_suffixed => f64,
578 }
579
580 unsuffixed_numbers! {
581 u8_unsuffixed => u8,
582 u16_unsuffixed => u16,
583 u32_unsuffixed => u32,
584 u64_unsuffixed => u64,
585 usize_unsuffixed => usize,
586 i8_unsuffixed => i8,
587 i16_unsuffixed => i16,
588 i32_unsuffixed => i32,
589 i64_unsuffixed => i64,
590 isize_unsuffixed => isize,
591 }
592
593 pub fn f32_unsuffixed(f: f32) -> Literal {
594 let mut s = f.to_string();
595 if !s.contains(".") {
596 s.push_str(".0");
Alex Crichton76a5cc82017-05-23 07:01:44 -0700597 }
Alex Crichtona914a612018-04-04 07:48:44 -0700598 Literal::_new(s)
599 }
600
601 pub fn f64_unsuffixed(f: f64) -> Literal {
602 let mut s = f.to_string();
603 if !s.contains(".") {
604 s.push_str(".0");
605 }
606 Literal::_new(s)
607 }
608
609 pub fn string(t: &str) -> Literal {
David Tolnay3d9d6ad2018-05-18 10:51:55 -0700610 let mut s = t
611 .chars()
Alex Crichtona914a612018-04-04 07:48:44 -0700612 .flat_map(|c| c.escape_default())
613 .collect::<String>();
614 s.push('"');
615 s.insert(0, '"');
616 Literal::_new(s)
617 }
618
619 pub fn character(t: char) -> Literal {
620 Literal::_new(format!("'{}'", t.escape_default().collect::<String>()))
Alex Crichton76a5cc82017-05-23 07:01:44 -0700621 }
622
Alex Crichton9c2fb0a2017-05-26 08:49:31 -0700623 pub fn byte_string(bytes: &[u8]) -> Literal {
Alex Crichton852d53d2017-05-19 19:25:08 -0700624 let mut escaped = "b\"".to_string();
625 for b in bytes {
626 match *b {
627 b'\0' => escaped.push_str(r"\0"),
628 b'\t' => escaped.push_str(r"\t"),
629 b'\n' => escaped.push_str(r"\n"),
630 b'\r' => escaped.push_str(r"\r"),
631 b'"' => escaped.push_str("\\\""),
632 b'\\' => escaped.push_str("\\\\"),
David Tolnayb28f38a2018-03-31 22:02:29 +0200633 b'\x20'...b'\x7E' => escaped.push(*b as char),
Alex Crichton852d53d2017-05-19 19:25:08 -0700634 _ => escaped.push_str(&format!("\\x{:02X}", b)),
635 }
636 }
637 escaped.push('"');
Alex Crichtonb2c94622018-04-04 07:36:41 -0700638 Literal::_new(escaped)
Alex Crichton76a5cc82017-05-23 07:01:44 -0700639 }
Alex Crichton9c2fb0a2017-05-26 08:49:31 -0700640
Alex Crichtonb2c94622018-04-04 07:36:41 -0700641 pub fn span(&self) -> Span {
642 self.span
Alex Crichton31316622017-05-26 12:54:47 -0700643 }
644
Alex Crichtonb2c94622018-04-04 07:36:41 -0700645 pub fn set_span(&mut self, span: Span) {
646 self.span = span;
Alex Crichton31316622017-05-26 12:54:47 -0700647 }
Alex Crichton852d53d2017-05-19 19:25:08 -0700648}
649
Alex Crichton44bffbc2017-05-19 17:51:59 -0700650impl fmt::Display for Literal {
651 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Alex Crichtonb2c94622018-04-04 07:36:41 -0700652 self.text.fmt(f)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700653 }
654}
655
David Tolnay034205f2018-04-22 16:45:28 -0700656impl fmt::Debug for Literal {
657 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
658 let mut debug = fmt.debug_struct("Literal");
659 debug.field("lit", &format_args!("{}", self.text));
660 #[cfg(procmacro2_semver_exempt)]
661 debug.field("span", &self.span);
662 debug.finish()
663 }
664}
665
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700666fn token_stream(mut input: Cursor) -> PResult<TokenStream> {
Alex Crichton1eb96a02018-04-04 13:07:35 -0700667 let mut trees = Vec::new();
668 loop {
669 let input_no_ws = skip_whitespace(input);
670 if input_no_ws.rest.len() == 0 {
David Tolnay48ea5042018-04-23 19:17:35 -0700671 break;
Alex Crichton1eb96a02018-04-04 13:07:35 -0700672 }
673 if let Ok((a, tokens)) = doc_comment(input_no_ws) {
674 input = a;
675 trees.extend(tokens);
David Tolnay48ea5042018-04-23 19:17:35 -0700676 continue;
Alex Crichton1eb96a02018-04-04 13:07:35 -0700677 }
678
679 let (a, tt) = match token_tree(input_no_ws) {
680 Ok(p) => p,
681 Err(_) => break,
682 };
683 trees.push(tt);
684 input = a;
685 }
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700686 Ok((input, TokenStream { inner: trees }))
Alex Crichton1eb96a02018-04-04 13:07:35 -0700687}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700688
David Tolnay1ebe3972018-01-02 20:14:20 -0800689#[cfg(not(procmacro2_semver_exempt))]
Alex Crichton1eb96a02018-04-04 13:07:35 -0700690fn spanned<'a, T>(
691 input: Cursor<'a>,
692 f: fn(Cursor<'a>) -> PResult<'a, T>,
693) -> PResult<'a, (T, ::Span)> {
694 let (a, b) = f(skip_whitespace(input))?;
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700695 Ok((a, ((b, ::Span::_new_stable(Span {})))))
David Tolnayddfca052017-12-31 10:41:24 -0500696}
697
David Tolnay1ebe3972018-01-02 20:14:20 -0800698#[cfg(procmacro2_semver_exempt)]
Alex Crichton1eb96a02018-04-04 13:07:35 -0700699fn spanned<'a, T>(
700 input: Cursor<'a>,
701 f: fn(Cursor<'a>) -> PResult<'a, T>,
702) -> PResult<'a, (T, ::Span)> {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500703 let input = skip_whitespace(input);
704 let lo = input.off;
Alex Crichton1eb96a02018-04-04 13:07:35 -0700705 let (a, b) = f(input)?;
706 let hi = a.off;
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700707 let span = ::Span::_new_stable(Span { lo: lo, hi: hi });
Alex Crichton1eb96a02018-04-04 13:07:35 -0700708 Ok((a, (b, span)))
709}
710
711fn token_tree(input: Cursor) -> PResult<TokenTree> {
712 let (rest, (mut tt, span)) = spanned(input, token_kind)?;
713 tt.set_span(span);
714 Ok((rest, tt))
Nika Layzellf8d5f212017-12-11 14:07:02 -0500715}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700716
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700717named!(token_kind -> TokenTree, alt!(
718 map!(group, TokenTree::Group)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700719 |
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700720 map!(literal, |l| TokenTree::Literal(::Literal::_new_stable(l))) // must be before symbol
Alex Crichton44bffbc2017-05-19 17:51:59 -0700721 |
Alex Crichtonf3888432018-05-16 09:11:05 -0700722 map!(op, TokenTree::Punct)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700723 |
Alex Crichtonf3888432018-05-16 09:11:05 -0700724 symbol_leading_ws
Alex Crichton44bffbc2017-05-19 17:51:59 -0700725));
726
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700727named!(group -> Group, alt!(
Alex Crichton44bffbc2017-05-19 17:51:59 -0700728 delimited!(
729 punct!("("),
730 token_stream,
731 punct!(")")
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700732 ) => { |ts| Group::new(Delimiter::Parenthesis, ::TokenStream::_new_stable(ts)) }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700733 |
734 delimited!(
735 punct!("["),
736 token_stream,
737 punct!("]")
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700738 ) => { |ts| Group::new(Delimiter::Bracket, ::TokenStream::_new_stable(ts)) }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700739 |
740 delimited!(
741 punct!("{"),
742 token_stream,
743 punct!("}")
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700744 ) => { |ts| Group::new(Delimiter::Brace, ::TokenStream::_new_stable(ts)) }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700745));
746
Alex Crichtonf3888432018-05-16 09:11:05 -0700747fn symbol_leading_ws(input: Cursor) -> PResult<TokenTree> {
748 symbol(skip_whitespace(input))
749}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700750
Alex Crichtonf3888432018-05-16 09:11:05 -0700751fn symbol(input: Cursor) -> PResult<TokenTree> {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700752 let mut chars = input.char_indices();
David Tolnaya202d502017-06-01 12:26:55 -0700753
Alex Crichtonf3888432018-05-16 09:11:05 -0700754 let raw = input.starts_with("r#");
David Tolnaya13d1422018-03-31 21:27:48 +0200755 if raw {
756 chars.next();
757 chars.next();
758 }
759
Alex Crichton44bffbc2017-05-19 17:51:59 -0700760 match chars.next() {
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000761 Some((_, ch)) if is_ident_start(ch) => {}
David Tolnay1218e122017-06-01 11:13:45 -0700762 _ => return Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -0700763 }
764
David Tolnay214c94c2017-06-01 12:42:56 -0700765 let mut end = input.len();
Alex Crichton44bffbc2017-05-19 17:51:59 -0700766 for (i, ch) in chars {
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000767 if !is_ident_continue(ch) {
David Tolnay214c94c2017-06-01 12:42:56 -0700768 end = i;
769 break;
Alex Crichton44bffbc2017-05-19 17:51:59 -0700770 }
771 }
772
David Tolnaya13d1422018-03-31 21:27:48 +0200773 let a = &input.rest[..end];
Alex Crichtonf3888432018-05-16 09:11:05 -0700774 if a == "r#_" {
David Tolnay214c94c2017-06-01 12:42:56 -0700775 Err(LexError)
776 } else {
Alex Crichtonf3888432018-05-16 09:11:05 -0700777 let ident = if raw {
778 ::Ident::_new_raw(&a[2..], ::Span::call_site())
779 } else {
780 ::Ident::new(a, ::Span::call_site())
781 };
782 Ok((input.advance(end), ident.into()))
David Tolnay214c94c2017-06-01 12:42:56 -0700783 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700784}
785
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700786fn literal(input: Cursor) -> PResult<Literal> {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700787 let input_no_ws = skip_whitespace(input);
788
789 match literal_nocapture(input_no_ws) {
David Tolnay1218e122017-06-01 11:13:45 -0700790 Ok((a, ())) => {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700791 let start = input.len() - input_no_ws.len();
792 let len = input_no_ws.len() - a.len();
793 let end = start + len;
David Tolnay3d9d6ad2018-05-18 10:51:55 -0700794 Ok((a, Literal::_new(input.rest[start..end].to_string())))
Alex Crichton44bffbc2017-05-19 17:51:59 -0700795 }
David Tolnay1218e122017-06-01 11:13:45 -0700796 Err(LexError) => Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -0700797 }
798}
799
800named!(literal_nocapture -> (), alt!(
801 string
802 |
803 byte_string
804 |
805 byte
806 |
807 character
808 |
809 float
810 |
811 int
Alex Crichton44bffbc2017-05-19 17:51:59 -0700812));
813
814named!(string -> (), alt!(
815 quoted_string
816 |
817 preceded!(
818 punct!("r"),
819 raw_string
820 ) => { |_| () }
821));
822
823named!(quoted_string -> (), delimited!(
824 punct!("\""),
825 cooked_string,
826 tag!("\"")
827));
828
Nika Layzellf8d5f212017-12-11 14:07:02 -0500829fn cooked_string(input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700830 let mut chars = input.char_indices().peekable();
831 while let Some((byte_offset, ch)) = chars.next() {
832 match ch {
833 '"' => {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500834 return Ok((input.advance(byte_offset), ()));
Alex Crichton44bffbc2017-05-19 17:51:59 -0700835 }
836 '\r' => {
837 if let Some((_, '\n')) = chars.next() {
838 // ...
839 } else {
840 break;
841 }
842 }
David Tolnayb28f38a2018-03-31 22:02:29 +0200843 '\\' => match chars.next() {
844 Some((_, 'x')) => {
845 if !backslash_x_char(&mut chars) {
846 break;
Alex Crichton44bffbc2017-05-19 17:51:59 -0700847 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700848 }
David Tolnayb28f38a2018-03-31 22:02:29 +0200849 Some((_, 'n')) | Some((_, 'r')) | Some((_, 't')) | Some((_, '\\'))
850 | Some((_, '\'')) | Some((_, '"')) | Some((_, '0')) => {}
851 Some((_, 'u')) => {
852 if !backslash_u(&mut chars) {
853 break;
854 }
855 }
856 Some((_, '\n')) | Some((_, '\r')) => {
857 while let Some(&(_, ch)) = chars.peek() {
858 if ch.is_whitespace() {
859 chars.next();
860 } else {
861 break;
862 }
863 }
864 }
865 _ => break,
866 },
Alex Crichton44bffbc2017-05-19 17:51:59 -0700867 _ch => {}
868 }
869 }
David Tolnay1218e122017-06-01 11:13:45 -0700870 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700871}
872
873named!(byte_string -> (), alt!(
874 delimited!(
875 punct!("b\""),
876 cooked_byte_string,
877 tag!("\"")
878 ) => { |_| () }
879 |
880 preceded!(
881 punct!("br"),
882 raw_string
883 ) => { |_| () }
884));
885
Nika Layzellf8d5f212017-12-11 14:07:02 -0500886fn cooked_byte_string(mut input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700887 let mut bytes = input.bytes().enumerate();
888 'outer: while let Some((offset, b)) = bytes.next() {
889 match b {
890 b'"' => {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500891 return Ok((input.advance(offset), ()));
Alex Crichton44bffbc2017-05-19 17:51:59 -0700892 }
893 b'\r' => {
894 if let Some((_, b'\n')) = bytes.next() {
895 // ...
896 } else {
897 break;
898 }
899 }
David Tolnayb28f38a2018-03-31 22:02:29 +0200900 b'\\' => match bytes.next() {
901 Some((_, b'x')) => {
902 if !backslash_x_byte(&mut bytes) {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700903 break;
904 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700905 }
David Tolnayb28f38a2018-03-31 22:02:29 +0200906 Some((_, b'n')) | Some((_, b'r')) | Some((_, b't')) | Some((_, b'\\'))
907 | Some((_, b'0')) | Some((_, b'\'')) | Some((_, b'"')) => {}
908 Some((newline, b'\n')) | Some((newline, b'\r')) => {
909 let rest = input.advance(newline + 1);
910 for (offset, ch) in rest.char_indices() {
911 if !ch.is_whitespace() {
912 input = rest.advance(offset);
913 bytes = input.bytes().enumerate();
914 continue 'outer;
915 }
916 }
917 break;
918 }
919 _ => break,
920 },
Alex Crichton44bffbc2017-05-19 17:51:59 -0700921 b if b < 0x80 => {}
922 _ => break,
923 }
924 }
David Tolnay1218e122017-06-01 11:13:45 -0700925 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700926}
927
Nika Layzellf8d5f212017-12-11 14:07:02 -0500928fn raw_string(input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700929 let mut chars = input.char_indices();
930 let mut n = 0;
931 while let Some((byte_offset, ch)) = chars.next() {
932 match ch {
933 '"' => {
934 n = byte_offset;
935 break;
936 }
937 '#' => {}
David Tolnay1218e122017-06-01 11:13:45 -0700938 _ => return Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -0700939 }
940 }
941 for (byte_offset, ch) in chars {
942 match ch {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500943 '"' if input.advance(byte_offset + 1).starts_with(&input.rest[..n]) => {
944 let rest = input.advance(byte_offset + 1 + n);
David Tolnayb28f38a2018-03-31 22:02:29 +0200945 return Ok((rest, ()));
Alex Crichton44bffbc2017-05-19 17:51:59 -0700946 }
947 '\r' => {}
948 _ => {}
949 }
950 }
David Tolnay1218e122017-06-01 11:13:45 -0700951 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700952}
953
954named!(byte -> (), do_parse!(
955 punct!("b") >>
956 tag!("'") >>
957 cooked_byte >>
958 tag!("'") >>
959 (())
960));
961
Nika Layzellf8d5f212017-12-11 14:07:02 -0500962fn cooked_byte(input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700963 let mut bytes = input.bytes().enumerate();
964 let ok = match bytes.next().map(|(_, b)| b) {
David Tolnayb28f38a2018-03-31 22:02:29 +0200965 Some(b'\\') => match bytes.next().map(|(_, b)| b) {
966 Some(b'x') => backslash_x_byte(&mut bytes),
967 Some(b'n') | Some(b'r') | Some(b't') | Some(b'\\') | Some(b'0') | Some(b'\'')
968 | Some(b'"') => true,
969 _ => false,
970 },
Alex Crichton44bffbc2017-05-19 17:51:59 -0700971 b => b.is_some(),
972 };
973 if ok {
974 match bytes.next() {
Alex Crichton8c030332018-01-16 08:07:36 -0800975 Some((offset, _)) => {
976 if input.chars().as_str().is_char_boundary(offset) {
977 Ok((input.advance(offset), ()))
978 } else {
979 Err(LexError)
980 }
981 }
Nika Layzellf8d5f212017-12-11 14:07:02 -0500982 None => Ok((input.advance(input.len()), ())),
Alex Crichton44bffbc2017-05-19 17:51:59 -0700983 }
984 } else {
David Tolnay1218e122017-06-01 11:13:45 -0700985 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700986 }
987}
988
989named!(character -> (), do_parse!(
990 punct!("'") >>
991 cooked_char >>
992 tag!("'") >>
993 (())
994));
995
Nika Layzellf8d5f212017-12-11 14:07:02 -0500996fn cooked_char(input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700997 let mut chars = input.char_indices();
998 let ok = match chars.next().map(|(_, ch)| ch) {
David Tolnayb28f38a2018-03-31 22:02:29 +0200999 Some('\\') => match chars.next().map(|(_, ch)| ch) {
1000 Some('x') => backslash_x_char(&mut chars),
1001 Some('u') => backslash_u(&mut chars),
1002 Some('n') | Some('r') | Some('t') | Some('\\') | Some('0') | Some('\'') | Some('"') => {
1003 true
Alex Crichton44bffbc2017-05-19 17:51:59 -07001004 }
David Tolnayb28f38a2018-03-31 22:02:29 +02001005 _ => false,
1006 },
Alex Crichton44bffbc2017-05-19 17:51:59 -07001007 ch => ch.is_some(),
1008 };
1009 if ok {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001010 match chars.next() {
1011 Some((idx, _)) => Ok((input.advance(idx), ())),
1012 None => Ok((input.advance(input.len()), ())),
1013 }
Alex Crichton44bffbc2017-05-19 17:51:59 -07001014 } else {
David Tolnay1218e122017-06-01 11:13:45 -07001015 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001016 }
1017}
1018
1019macro_rules! next_ch {
1020 ($chars:ident @ $pat:pat $(| $rest:pat)*) => {
1021 match $chars.next() {
1022 Some((_, ch)) => match ch {
1023 $pat $(| $rest)* => ch,
1024 _ => return false,
1025 },
1026 None => return false
1027 }
1028 };
1029}
1030
1031fn backslash_x_char<I>(chars: &mut I) -> bool
David Tolnayb28f38a2018-03-31 22:02:29 +02001032where
1033 I: Iterator<Item = (usize, char)>,
Alex Crichton44bffbc2017-05-19 17:51:59 -07001034{
1035 next_ch!(chars @ '0'...'7');
1036 next_ch!(chars @ '0'...'9' | 'a'...'f' | 'A'...'F');
1037 true
1038}
1039
1040fn backslash_x_byte<I>(chars: &mut I) -> bool
David Tolnayb28f38a2018-03-31 22:02:29 +02001041where
1042 I: Iterator<Item = (usize, u8)>,
Alex Crichton44bffbc2017-05-19 17:51:59 -07001043{
1044 next_ch!(chars @ b'0'...b'9' | b'a'...b'f' | b'A'...b'F');
1045 next_ch!(chars @ b'0'...b'9' | b'a'...b'f' | b'A'...b'F');
1046 true
1047}
1048
1049fn backslash_u<I>(chars: &mut I) -> bool
David Tolnayb28f38a2018-03-31 22:02:29 +02001050where
1051 I: Iterator<Item = (usize, char)>,
Alex Crichton44bffbc2017-05-19 17:51:59 -07001052{
1053 next_ch!(chars @ '{');
1054 next_ch!(chars @ '0'...'9' | 'a'...'f' | 'A'...'F');
David Tolnay8d109342017-12-25 18:24:45 -05001055 loop {
1056 let c = next_ch!(chars @ '0'...'9' | 'a'...'f' | 'A'...'F' | '_' | '}');
1057 if c == '}' {
1058 return true;
1059 }
Alex Crichton44bffbc2017-05-19 17:51:59 -07001060 }
Alex Crichton44bffbc2017-05-19 17:51:59 -07001061}
1062
Nika Layzellf8d5f212017-12-11 14:07:02 -05001063fn float(input: Cursor) -> PResult<()> {
David Tolnay744a6b82017-06-01 11:34:29 -07001064 let (rest, ()) = float_digits(input)?;
1065 for suffix in &["f32", "f64"] {
1066 if rest.starts_with(suffix) {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001067 return word_break(rest.advance(suffix.len()));
David Tolnay744a6b82017-06-01 11:34:29 -07001068 }
1069 }
1070 word_break(rest)
1071}
Alex Crichton44bffbc2017-05-19 17:51:59 -07001072
Nika Layzellf8d5f212017-12-11 14:07:02 -05001073fn float_digits(input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001074 let mut chars = input.chars().peekable();
1075 match chars.next() {
1076 Some(ch) if ch >= '0' && ch <= '9' => {}
David Tolnay1218e122017-06-01 11:13:45 -07001077 _ => return Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -07001078 }
1079
1080 let mut len = 1;
1081 let mut has_dot = false;
1082 let mut has_exp = false;
1083 while let Some(&ch) = chars.peek() {
1084 match ch {
1085 '0'...'9' | '_' => {
1086 chars.next();
1087 len += 1;
1088 }
1089 '.' => {
1090 if has_dot {
1091 break;
1092 }
1093 chars.next();
David Tolnayb28f38a2018-03-31 22:02:29 +02001094 if chars
1095 .peek()
1096 .map(|&ch| ch == '.' || UnicodeXID::is_xid_start(ch))
1097 .unwrap_or(false)
1098 {
David Tolnay1218e122017-06-01 11:13:45 -07001099 return Err(LexError);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001100 }
1101 len += 1;
1102 has_dot = true;
1103 }
1104 'e' | 'E' => {
1105 chars.next();
1106 len += 1;
1107 has_exp = true;
1108 break;
1109 }
1110 _ => break,
1111 }
1112 }
1113
Nika Layzellf8d5f212017-12-11 14:07:02 -05001114 let rest = input.advance(len);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001115 if !(has_dot || has_exp || rest.starts_with("f32") || rest.starts_with("f64")) {
David Tolnay1218e122017-06-01 11:13:45 -07001116 return Err(LexError);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001117 }
1118
1119 if has_exp {
1120 let mut has_exp_value = false;
1121 while let Some(&ch) = chars.peek() {
1122 match ch {
1123 '+' | '-' => {
1124 if has_exp_value {
1125 break;
1126 }
1127 chars.next();
1128 len += 1;
1129 }
1130 '0'...'9' => {
1131 chars.next();
1132 len += 1;
1133 has_exp_value = true;
1134 }
1135 '_' => {
1136 chars.next();
1137 len += 1;
1138 }
1139 _ => break,
1140 }
1141 }
1142 if !has_exp_value {
David Tolnay1218e122017-06-01 11:13:45 -07001143 return Err(LexError);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001144 }
1145 }
1146
Nika Layzellf8d5f212017-12-11 14:07:02 -05001147 Ok((input.advance(len), ()))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001148}
1149
Nika Layzellf8d5f212017-12-11 14:07:02 -05001150fn int(input: Cursor) -> PResult<()> {
David Tolnay744a6b82017-06-01 11:34:29 -07001151 let (rest, ()) = digits(input)?;
1152 for suffix in &[
David Tolnay48ea5042018-04-23 19:17:35 -07001153 "isize", "i8", "i16", "i32", "i64", "i128", "usize", "u8", "u16", "u32", "u64", "u128",
David Tolnay744a6b82017-06-01 11:34:29 -07001154 ] {
1155 if rest.starts_with(suffix) {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001156 return word_break(rest.advance(suffix.len()));
David Tolnay744a6b82017-06-01 11:34:29 -07001157 }
1158 }
1159 word_break(rest)
1160}
Alex Crichton44bffbc2017-05-19 17:51:59 -07001161
Nika Layzellf8d5f212017-12-11 14:07:02 -05001162fn digits(mut input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001163 let base = if input.starts_with("0x") {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001164 input = input.advance(2);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001165 16
1166 } else if input.starts_with("0o") {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001167 input = input.advance(2);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001168 8
1169 } else if input.starts_with("0b") {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001170 input = input.advance(2);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001171 2
1172 } else {
1173 10
1174 };
1175
Alex Crichton44bffbc2017-05-19 17:51:59 -07001176 let mut len = 0;
1177 let mut empty = true;
1178 for b in input.bytes() {
1179 let digit = match b {
1180 b'0'...b'9' => (b - b'0') as u64,
1181 b'a'...b'f' => 10 + (b - b'a') as u64,
1182 b'A'...b'F' => 10 + (b - b'A') as u64,
1183 b'_' => {
1184 if empty && base == 10 {
David Tolnay1218e122017-06-01 11:13:45 -07001185 return Err(LexError);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001186 }
1187 len += 1;
1188 continue;
1189 }
1190 _ => break,
1191 };
1192 if digit >= base {
David Tolnay1218e122017-06-01 11:13:45 -07001193 return Err(LexError);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001194 }
Alex Crichton44bffbc2017-05-19 17:51:59 -07001195 len += 1;
1196 empty = false;
1197 }
1198 if empty {
David Tolnay1218e122017-06-01 11:13:45 -07001199 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001200 } else {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001201 Ok((input.advance(len), ()))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001202 }
1203}
1204
Alex Crichtonf3888432018-05-16 09:11:05 -07001205fn op(input: Cursor) -> PResult<Punct> {
David Tolnayea75c5f2017-05-31 23:40:33 -07001206 let input = skip_whitespace(input);
1207 match op_char(input) {
Alex Crichtonf3888432018-05-16 09:11:05 -07001208 Ok((rest, '\'')) => {
1209 symbol(rest)?;
1210 Ok((rest, Punct::new('\'', Spacing::Joint)))
1211 }
David Tolnay1218e122017-06-01 11:13:45 -07001212 Ok((rest, ch)) => {
David Tolnayea75c5f2017-05-31 23:40:33 -07001213 let kind = match op_char(rest) {
Alex Crichton1a7f7622017-07-05 17:47:15 -07001214 Ok(_) => Spacing::Joint,
1215 Err(LexError) => Spacing::Alone,
David Tolnayea75c5f2017-05-31 23:40:33 -07001216 };
Alex Crichtonf3888432018-05-16 09:11:05 -07001217 Ok((rest, Punct::new(ch, kind)))
David Tolnayea75c5f2017-05-31 23:40:33 -07001218 }
David Tolnay1218e122017-06-01 11:13:45 -07001219 Err(LexError) => Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -07001220 }
1221}
1222
Nika Layzellf8d5f212017-12-11 14:07:02 -05001223fn op_char(input: Cursor) -> PResult<char> {
David Tolnay3a592ad2018-04-22 21:20:24 -07001224 if input.starts_with("//") || input.starts_with("/*") {
1225 // Do not accept `/` of a comment as an op.
1226 return Err(LexError);
1227 }
1228
David Tolnayea75c5f2017-05-31 23:40:33 -07001229 let mut chars = input.chars();
1230 let first = match chars.next() {
1231 Some(ch) => ch,
1232 None => {
David Tolnay1218e122017-06-01 11:13:45 -07001233 return Err(LexError);
David Tolnayea75c5f2017-05-31 23:40:33 -07001234 }
1235 };
Alex Crichtonf3888432018-05-16 09:11:05 -07001236 let recognized = "~!@#$%^&*-=+|;:,<.>/?'";
David Tolnayea75c5f2017-05-31 23:40:33 -07001237 if recognized.contains(first) {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001238 Ok((input.advance(first.len_utf8()), first))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001239 } else {
David Tolnay1218e122017-06-01 11:13:45 -07001240 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001241 }
1242}
1243
Alex Crichton1eb96a02018-04-04 13:07:35 -07001244fn doc_comment(input: Cursor) -> PResult<Vec<TokenTree>> {
1245 let mut trees = Vec::new();
1246 let (rest, ((comment, inner), span)) = spanned(input, doc_comment_contents)?;
Alex Crichtonf3888432018-05-16 09:11:05 -07001247 trees.push(TokenTree::Punct(Punct::new('#', Spacing::Alone)));
Alex Crichton1eb96a02018-04-04 13:07:35 -07001248 if inner {
Alex Crichtonf3888432018-05-16 09:11:05 -07001249 trees.push(Punct::new('!', Spacing::Alone).into());
Alex Crichton1eb96a02018-04-04 13:07:35 -07001250 }
1251 let mut stream = vec![
Alex Crichtonf3888432018-05-16 09:11:05 -07001252 TokenTree::Ident(::Ident::new("doc", span)),
1253 TokenTree::Punct(Punct::new('=', Spacing::Alone)),
Alex Crichton1eb96a02018-04-04 13:07:35 -07001254 TokenTree::Literal(::Literal::string(comment)),
1255 ];
1256 for tt in stream.iter_mut() {
1257 tt.set_span(span);
1258 }
1259 trees.push(Group::new(Delimiter::Bracket, stream.into_iter().collect()).into());
1260 for tt in trees.iter_mut() {
1261 tt.set_span(span);
1262 }
1263 Ok((rest, trees))
1264}
1265
1266named!(doc_comment_contents -> (&str, bool), alt!(
Alex Crichton44bffbc2017-05-19 17:51:59 -07001267 do_parse!(
1268 punct!("//!") >>
Alex Crichton1eb96a02018-04-04 13:07:35 -07001269 s: take_until_newline_or_eof!() >>
1270 ((s, true))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001271 )
1272 |
1273 do_parse!(
1274 option!(whitespace) >>
1275 peek!(tag!("/*!")) >>
Alex Crichton1eb96a02018-04-04 13:07:35 -07001276 s: block_comment >>
1277 ((s, true))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001278 )
1279 |
1280 do_parse!(
1281 punct!("///") >>
1282 not!(tag!("/")) >>
Alex Crichton1eb96a02018-04-04 13:07:35 -07001283 s: take_until_newline_or_eof!() >>
1284 ((s, false))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001285 )
1286 |
1287 do_parse!(
1288 option!(whitespace) >>
1289 peek!(tuple!(tag!("/**"), not!(tag!("*")))) >>
Alex Crichton1eb96a02018-04-04 13:07:35 -07001290 s: block_comment >>
1291 ((s, false))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001292 )
1293));