blob: 928c7472c452c2fcf95b2f181b5bf2f3af4b28c8 [file] [log] [blame]
David Tolnay3b1f7d22019-01-28 12:22:11 -08001#[cfg(span_locations)]
Alex Crichton44bffbc2017-05-19 17:51:59 -07002use std::cell::RefCell;
David Tolnay1ebe3972018-01-02 20:14:20 -08003#[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -05004use std::cmp;
Alex Crichton44bffbc2017-05-19 17:51:59 -07005use std::fmt;
6use std::iter;
David Tolnay9cd3b4c2018-11-11 16:47:32 -08007#[cfg(procmacro2_semver_exempt)]
8use std::path::Path;
9use std::path::PathBuf;
Alex Crichton44bffbc2017-05-19 17:51:59 -070010use std::str::FromStr;
11use std::vec;
12
David Tolnayb28f38a2018-03-31 22:02:29 +020013use strnom::{block_comment, skip_whitespace, whitespace, word_break, Cursor, PResult};
David Tolnayb1032662017-05-31 15:52:28 -070014use unicode_xid::UnicodeXID;
Alex Crichton44bffbc2017-05-19 17:51:59 -070015
David Tolnayf14813f2018-09-08 17:14:07 -070016use {Delimiter, Punct, Spacing, TokenTree};
Alex Crichton44bffbc2017-05-19 17:51:59 -070017
David Tolnay034205f2018-04-22 16:45:28 -070018#[derive(Clone)]
Alex Crichton44bffbc2017-05-19 17:51:59 -070019pub struct TokenStream {
20 inner: Vec<TokenTree>,
21}
22
23#[derive(Debug)]
24pub struct LexError;
25
26impl TokenStream {
David Tolnayc3bb4592018-05-28 20:09:44 -070027 pub fn new() -> TokenStream {
Alex Crichton44bffbc2017-05-19 17:51:59 -070028 TokenStream { inner: Vec::new() }
29 }
30
31 pub fn is_empty(&self) -> bool {
32 self.inner.len() == 0
33 }
34}
35
David Tolnay3b1f7d22019-01-28 12:22:11 -080036#[cfg(span_locations)]
Nika Layzella9dbc182017-12-30 14:50:13 -050037fn get_cursor(src: &str) -> Cursor {
38 // Create a dummy file & add it to the codemap
39 CODEMAP.with(|cm| {
40 let mut cm = cm.borrow_mut();
41 let name = format!("<parsed string {}>", cm.files.len());
42 let span = cm.add_file(&name, src);
43 Cursor {
44 rest: src,
45 off: span.lo,
46 }
47 })
48}
49
David Tolnay3b1f7d22019-01-28 12:22:11 -080050#[cfg(not(span_locations))]
Nika Layzella9dbc182017-12-30 14:50:13 -050051fn get_cursor(src: &str) -> Cursor {
David Tolnayb28f38a2018-03-31 22:02:29 +020052 Cursor { rest: src }
Nika Layzella9dbc182017-12-30 14:50:13 -050053}
54
Alex Crichton44bffbc2017-05-19 17:51:59 -070055impl FromStr for TokenStream {
56 type Err = LexError;
57
58 fn from_str(src: &str) -> Result<TokenStream, LexError> {
Nika Layzellf8d5f212017-12-11 14:07:02 -050059 // Create a dummy file & add it to the codemap
Nika Layzella9dbc182017-12-30 14:50:13 -050060 let cursor = get_cursor(src);
Nika Layzellf8d5f212017-12-11 14:07:02 -050061
62 match token_stream(cursor) {
David Tolnay1218e122017-06-01 11:13:45 -070063 Ok((input, output)) => {
Alex Crichton44bffbc2017-05-19 17:51:59 -070064 if skip_whitespace(input).len() != 0 {
65 Err(LexError)
66 } else {
Alex Crichton30a4e9e2018-04-27 17:02:19 -070067 Ok(output)
Alex Crichton44bffbc2017-05-19 17:51:59 -070068 }
69 }
David Tolnay1218e122017-06-01 11:13:45 -070070 Err(LexError) => Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -070071 }
72 }
73}
74
75impl fmt::Display for TokenStream {
76 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
77 let mut joint = false;
78 for (i, tt) in self.inner.iter().enumerate() {
79 if i != 0 && !joint {
80 write!(f, " ")?;
81 }
82 joint = false;
Alex Crichtonaf5bad42018-03-27 14:45:10 -070083 match *tt {
84 TokenTree::Group(ref tt) => {
85 let (start, end) = match tt.delimiter() {
Alex Crichton44bffbc2017-05-19 17:51:59 -070086 Delimiter::Parenthesis => ("(", ")"),
87 Delimiter::Brace => ("{", "}"),
88 Delimiter::Bracket => ("[", "]"),
89 Delimiter::None => ("", ""),
90 };
Alex Crichton30a4e9e2018-04-27 17:02:19 -070091 if tt.stream().into_iter().next().is_none() {
Alex Crichton852d53d2017-05-19 19:25:08 -070092 write!(f, "{} {}", start, end)?
93 } else {
Alex Crichtonaf5bad42018-03-27 14:45:10 -070094 write!(f, "{} {} {}", start, tt.stream(), end)?
Alex Crichton852d53d2017-05-19 19:25:08 -070095 }
Alex Crichton44bffbc2017-05-19 17:51:59 -070096 }
Alex Crichtonf3888432018-05-16 09:11:05 -070097 TokenTree::Ident(ref tt) => write!(f, "{}", tt)?,
98 TokenTree::Punct(ref tt) => {
99 write!(f, "{}", tt.as_char())?;
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700100 match tt.spacing() {
Alex Crichton1a7f7622017-07-05 17:47:15 -0700101 Spacing::Alone => {}
102 Spacing::Joint => joint = true,
Alex Crichton44bffbc2017-05-19 17:51:59 -0700103 }
104 }
Alex Crichtonb2c94622018-04-04 07:36:41 -0700105 TokenTree::Literal(ref tt) => write!(f, "{}", tt)?,
Alex Crichton44bffbc2017-05-19 17:51:59 -0700106 }
107 }
108
109 Ok(())
110 }
111}
112
David Tolnay034205f2018-04-22 16:45:28 -0700113impl fmt::Debug for TokenStream {
114 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
115 f.write_str("TokenStream ")?;
116 f.debug_list().entries(self.clone()).finish()
117 }
118}
119
Alex Crichton53548482018-08-11 21:54:05 -0700120#[cfg(use_proc_macro)]
Alex Crichton0e8e7f42018-02-22 06:15:13 -0800121impl From<::proc_macro::TokenStream> for TokenStream {
122 fn from(inner: ::proc_macro::TokenStream) -> TokenStream {
David Tolnayb28f38a2018-03-31 22:02:29 +0200123 inner
124 .to_string()
125 .parse()
126 .expect("compiler token stream parse failed")
Alex Crichton44bffbc2017-05-19 17:51:59 -0700127 }
128}
129
Alex Crichton53548482018-08-11 21:54:05 -0700130#[cfg(use_proc_macro)]
Alex Crichton0e8e7f42018-02-22 06:15:13 -0800131impl From<TokenStream> for ::proc_macro::TokenStream {
132 fn from(inner: TokenStream) -> ::proc_macro::TokenStream {
David Tolnayb28f38a2018-03-31 22:02:29 +0200133 inner
134 .to_string()
135 .parse()
136 .expect("failed to parse to compiler tokens")
Alex Crichton44bffbc2017-05-19 17:51:59 -0700137 }
138}
139
Alex Crichton44bffbc2017-05-19 17:51:59 -0700140impl From<TokenTree> for TokenStream {
141 fn from(tree: TokenTree) -> TokenStream {
142 TokenStream { inner: vec![tree] }
143 }
144}
145
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700146impl iter::FromIterator<TokenTree> for TokenStream {
David Tolnayb28f38a2018-03-31 22:02:29 +0200147 fn from_iter<I: IntoIterator<Item = TokenTree>>(streams: I) -> Self {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700148 let mut v = Vec::new();
149
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700150 for token in streams.into_iter() {
151 v.push(token);
Alex Crichton44bffbc2017-05-19 17:51:59 -0700152 }
153
154 TokenStream { inner: v }
155 }
156}
157
Alex Crichton53b00672018-09-06 17:16:10 -0700158impl iter::FromIterator<TokenStream> for TokenStream {
159 fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
160 let mut v = Vec::new();
161
162 for stream in streams.into_iter() {
163 v.extend(stream.inner);
164 }
165
166 TokenStream { inner: v }
167 }
168}
169
Alex Crichtonf3888432018-05-16 09:11:05 -0700170impl Extend<TokenTree> for TokenStream {
171 fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, streams: I) {
172 self.inner.extend(streams);
173 }
174}
175
David Tolnay5c58c532018-08-13 11:33:51 -0700176impl Extend<TokenStream> for TokenStream {
177 fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
178 self.inner
179 .extend(streams.into_iter().flat_map(|stream| stream));
180 }
181}
182
Alex Crichton1a7f7622017-07-05 17:47:15 -0700183pub type TokenTreeIter = vec::IntoIter<TokenTree>;
Alex Crichton44bffbc2017-05-19 17:51:59 -0700184
185impl IntoIterator for TokenStream {
186 type Item = TokenTree;
Alex Crichton1a7f7622017-07-05 17:47:15 -0700187 type IntoIter = TokenTreeIter;
Alex Crichton44bffbc2017-05-19 17:51:59 -0700188
Alex Crichton1a7f7622017-07-05 17:47:15 -0700189 fn into_iter(self) -> TokenTreeIter {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700190 self.inner.into_iter()
191 }
192}
193
Nika Layzellf8d5f212017-12-11 14:07:02 -0500194#[derive(Clone, PartialEq, Eq)]
195pub struct SourceFile {
David Tolnay9cd3b4c2018-11-11 16:47:32 -0800196 path: PathBuf,
Nika Layzellf8d5f212017-12-11 14:07:02 -0500197}
198
199impl SourceFile {
200 /// Get the path to this source file as a string.
David Tolnay9cd3b4c2018-11-11 16:47:32 -0800201 pub fn path(&self) -> PathBuf {
202 self.path.clone()
Nika Layzellf8d5f212017-12-11 14:07:02 -0500203 }
204
205 pub fn is_real(&self) -> bool {
206 // XXX(nika): Support real files in the future?
207 false
208 }
209}
210
Nika Layzellf8d5f212017-12-11 14:07:02 -0500211impl fmt::Debug for SourceFile {
212 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
213 f.debug_struct("SourceFile")
Nika Layzellb35a9a32017-12-30 14:34:35 -0500214 .field("path", &self.path())
Nika Layzellf8d5f212017-12-11 14:07:02 -0500215 .field("is_real", &self.is_real())
216 .finish()
217 }
218}
219
220#[derive(Clone, Copy, Debug, PartialEq, Eq)]
221pub struct LineColumn {
222 pub line: usize,
223 pub column: usize,
224}
225
David Tolnay3b1f7d22019-01-28 12:22:11 -0800226#[cfg(span_locations)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500227thread_local! {
228 static CODEMAP: RefCell<Codemap> = RefCell::new(Codemap {
229 // NOTE: We start with a single dummy file which all call_site() and
230 // def_site() spans reference.
David Tolnay3b1f7d22019-01-28 12:22:11 -0800231 files: vec![{
232 #[cfg(procmacro2_semver_exempt)]
233 {
234 FileInfo {
235 name: "<unspecified>".to_owned(),
236 span: Span { lo: 0, hi: 0 },
237 lines: vec![0],
238 }
239 }
240
241 #[cfg(not(procmacro2_semver_exempt))]
242 {
243 FileInfo {
244 span: Span { lo: 0, hi: 0 },
245 lines: vec![0],
246 }
247 }
Nika Layzellf8d5f212017-12-11 14:07:02 -0500248 }],
249 });
250}
251
David Tolnay3b1f7d22019-01-28 12:22:11 -0800252#[cfg(span_locations)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500253struct FileInfo {
David Tolnay3b1f7d22019-01-28 12:22:11 -0800254 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500255 name: String,
256 span: Span,
257 lines: Vec<usize>,
258}
259
David Tolnay3b1f7d22019-01-28 12:22:11 -0800260#[cfg(span_locations)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500261impl FileInfo {
262 fn offset_line_column(&self, offset: usize) -> LineColumn {
David Tolnayb28f38a2018-03-31 22:02:29 +0200263 assert!(self.span_within(Span {
264 lo: offset as u32,
265 hi: offset as u32
266 }));
Nika Layzellf8d5f212017-12-11 14:07:02 -0500267 let offset = offset - self.span.lo as usize;
268 match self.lines.binary_search(&offset) {
269 Ok(found) => LineColumn {
270 line: found + 1,
David Tolnayb28f38a2018-03-31 22:02:29 +0200271 column: 0,
Nika Layzellf8d5f212017-12-11 14:07:02 -0500272 },
273 Err(idx) => LineColumn {
274 line: idx,
David Tolnayb28f38a2018-03-31 22:02:29 +0200275 column: offset - self.lines[idx - 1],
Nika Layzellf8d5f212017-12-11 14:07:02 -0500276 },
277 }
278 }
279
280 fn span_within(&self, span: Span) -> bool {
281 span.lo >= self.span.lo && span.hi <= self.span.hi
282 }
283}
284
Alex Crichtona914a612018-04-04 07:48:44 -0700285/// Computesthe offsets of each line in the given source string.
David Tolnay3b1f7d22019-01-28 12:22:11 -0800286#[cfg(span_locations)]
Nika Layzella0a7c3d2017-12-30 14:52:39 -0500287fn lines_offsets(s: &str) -> Vec<usize> {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500288 let mut lines = vec![0];
289 let mut prev = 0;
Nika Layzella0a7c3d2017-12-30 14:52:39 -0500290 while let Some(len) = s[prev..].find('\n') {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500291 prev += len + 1;
292 lines.push(prev);
293 }
294 lines
295}
296
David Tolnay3b1f7d22019-01-28 12:22:11 -0800297#[cfg(span_locations)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500298struct Codemap {
299 files: Vec<FileInfo>,
300}
301
David Tolnay3b1f7d22019-01-28 12:22:11 -0800302#[cfg(span_locations)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500303impl Codemap {
304 fn next_start_pos(&self) -> u32 {
305 // Add 1 so there's always space between files.
306 //
307 // We'll always have at least 1 file, as we initialize our files list
308 // with a dummy file.
309 self.files.last().unwrap().span.hi + 1
310 }
311
312 fn add_file(&mut self, name: &str, src: &str) -> Span {
Nika Layzella0a7c3d2017-12-30 14:52:39 -0500313 let lines = lines_offsets(src);
Nika Layzellf8d5f212017-12-11 14:07:02 -0500314 let lo = self.next_start_pos();
315 // XXX(nika): Shouild we bother doing a checked cast or checked add here?
David Tolnayb28f38a2018-03-31 22:02:29 +0200316 let span = Span {
317 lo: lo,
318 hi: lo + (src.len() as u32),
319 };
Nika Layzellf8d5f212017-12-11 14:07:02 -0500320
David Tolnay3b1f7d22019-01-28 12:22:11 -0800321 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500322 self.files.push(FileInfo {
323 name: name.to_owned(),
324 span: span,
325 lines: lines,
326 });
327
David Tolnay3b1f7d22019-01-28 12:22:11 -0800328 #[cfg(not(procmacro2_semver_exempt))]
329 self.files.push(FileInfo {
330 span: span,
331 lines: lines,
332 });
333 let _ = name;
334
Nika Layzellf8d5f212017-12-11 14:07:02 -0500335 span
336 }
337
338 fn fileinfo(&self, span: Span) -> &FileInfo {
339 for file in &self.files {
340 if file.span_within(span) {
341 return file;
342 }
343 }
344 panic!("Invalid span with no related FileInfo!");
345 }
346}
347
David Tolnay034205f2018-04-22 16:45:28 -0700348#[derive(Clone, Copy, PartialEq, Eq)]
David Tolnayddfca052017-12-31 10:41:24 -0500349pub struct Span {
David Tolnay3b1f7d22019-01-28 12:22:11 -0800350 #[cfg(span_locations)]
David Tolnayddfca052017-12-31 10:41:24 -0500351 lo: u32,
David Tolnay3b1f7d22019-01-28 12:22:11 -0800352 #[cfg(span_locations)]
David Tolnayddfca052017-12-31 10:41:24 -0500353 hi: u32,
354}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700355
356impl Span {
David Tolnay3b1f7d22019-01-28 12:22:11 -0800357 #[cfg(not(span_locations))]
Alex Crichton44bffbc2017-05-19 17:51:59 -0700358 pub fn call_site() -> Span {
David Tolnay79105e52017-12-31 11:03:04 -0500359 Span {}
360 }
361
David Tolnay3b1f7d22019-01-28 12:22:11 -0800362 #[cfg(span_locations)]
David Tolnay79105e52017-12-31 11:03:04 -0500363 pub fn call_site() -> Span {
364 Span { lo: 0, hi: 0 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700365 }
Alex Crichtone6085b72017-11-21 07:24:25 -0800366
David Tolnay3b1f7d22019-01-28 12:22:11 -0800367 #[cfg(procmacro2_semver_exempt)]
Alex Crichtone6085b72017-11-21 07:24:25 -0800368 pub fn def_site() -> Span {
David Tolnay79105e52017-12-31 11:03:04 -0500369 Span::call_site()
Nika Layzellf8d5f212017-12-11 14:07:02 -0500370 }
371
David Tolnay3b1f7d22019-01-28 12:22:11 -0800372 #[cfg(procmacro2_semver_exempt)]
David Tolnay4e8e3972018-01-05 18:10:22 -0800373 pub fn resolved_at(&self, _other: Span) -> Span {
374 // Stable spans consist only of line/column information, so
375 // `resolved_at` and `located_at` only select which span the
376 // caller wants line/column information from.
377 *self
378 }
379
David Tolnay3b1f7d22019-01-28 12:22:11 -0800380 #[cfg(procmacro2_semver_exempt)]
David Tolnay4e8e3972018-01-05 18:10:22 -0800381 pub fn located_at(&self, other: Span) -> Span {
382 other
383 }
384
David Tolnay1ebe3972018-01-02 20:14:20 -0800385 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500386 pub fn source_file(&self) -> SourceFile {
387 CODEMAP.with(|cm| {
388 let cm = cm.borrow();
389 let fi = cm.fileinfo(*self);
390 SourceFile {
David Tolnay9cd3b4c2018-11-11 16:47:32 -0800391 path: Path::new(&fi.name).to_owned(),
Nika Layzellf8d5f212017-12-11 14:07:02 -0500392 }
393 })
394 }
395
David Tolnay3b1f7d22019-01-28 12:22:11 -0800396 #[cfg(span_locations)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500397 pub fn start(&self) -> LineColumn {
398 CODEMAP.with(|cm| {
399 let cm = cm.borrow();
400 let fi = cm.fileinfo(*self);
401 fi.offset_line_column(self.lo as usize)
402 })
403 }
404
David Tolnay3b1f7d22019-01-28 12:22:11 -0800405 #[cfg(span_locations)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500406 pub fn end(&self) -> LineColumn {
407 CODEMAP.with(|cm| {
408 let cm = cm.borrow();
409 let fi = cm.fileinfo(*self);
410 fi.offset_line_column(self.hi as usize)
411 })
412 }
413
David Tolnay1ebe3972018-01-02 20:14:20 -0800414 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500415 pub fn join(&self, other: Span) -> Option<Span> {
416 CODEMAP.with(|cm| {
417 let cm = cm.borrow();
418 // If `other` is not within the same FileInfo as us, return None.
419 if !cm.fileinfo(*self).span_within(other) {
420 return None;
421 }
422 Some(Span {
423 lo: cmp::min(self.lo, other.lo),
424 hi: cmp::max(self.hi, other.hi),
425 })
426 })
Alex Crichtone6085b72017-11-21 07:24:25 -0800427 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700428}
429
David Tolnay034205f2018-04-22 16:45:28 -0700430impl fmt::Debug for Span {
431 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
432 #[cfg(procmacro2_semver_exempt)]
433 return write!(f, "bytes({}..{})", self.lo, self.hi);
434
435 #[cfg(not(procmacro2_semver_exempt))]
436 write!(f, "Span")
437 }
438}
439
David Tolnayfd8cdc82019-01-19 19:23:59 -0800440pub fn debug_span_field_if_nontrivial(debug: &mut fmt::DebugStruct, span: Span) {
441 if cfg!(procmacro2_semver_exempt) {
442 debug.field("span", &span);
443 }
444}
445
Alex Crichtonf3888432018-05-16 09:11:05 -0700446#[derive(Clone)]
David Tolnayf14813f2018-09-08 17:14:07 -0700447pub struct Group {
448 delimiter: Delimiter,
449 stream: TokenStream,
450 span: Span,
451}
452
453impl Group {
454 pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
455 Group {
456 delimiter: delimiter,
457 stream: stream,
458 span: Span::call_site(),
459 }
460 }
461
462 pub fn delimiter(&self) -> Delimiter {
463 self.delimiter
464 }
465
466 pub fn stream(&self) -> TokenStream {
467 self.stream.clone()
468 }
469
470 pub fn span(&self) -> Span {
471 self.span
472 }
473
David Tolnay3b1f7d22019-01-28 12:22:11 -0800474 #[cfg(procmacro2_semver_exempt)]
David Tolnayf14813f2018-09-08 17:14:07 -0700475 pub fn span_open(&self) -> Span {
476 self.span
477 }
478
David Tolnay3b1f7d22019-01-28 12:22:11 -0800479 #[cfg(procmacro2_semver_exempt)]
David Tolnayf14813f2018-09-08 17:14:07 -0700480 pub fn span_close(&self) -> Span {
481 self.span
482 }
483
484 pub fn set_span(&mut self, span: Span) {
485 self.span = span;
486 }
487}
488
489impl fmt::Display for Group {
490 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
491 let (left, right) = match self.delimiter {
492 Delimiter::Parenthesis => ("(", ")"),
493 Delimiter::Brace => ("{", "}"),
494 Delimiter::Bracket => ("[", "]"),
495 Delimiter::None => ("", ""),
496 };
497
498 f.write_str(left)?;
499 self.stream.fmt(f)?;
500 f.write_str(right)?;
501
502 Ok(())
503 }
504}
505
506impl fmt::Debug for Group {
507 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
508 let mut debug = fmt.debug_struct("Group");
509 debug.field("delimiter", &self.delimiter);
510 debug.field("stream", &self.stream);
511 #[cfg(procmacro2_semver_exempt)]
512 debug.field("span", &self.span);
513 debug.finish()
514 }
515}
516
517#[derive(Clone)]
Alex Crichtonf3888432018-05-16 09:11:05 -0700518pub struct Ident {
David Tolnayc2309ca2018-06-02 15:47:57 -0700519 sym: String,
Alex Crichtonb2c94622018-04-04 07:36:41 -0700520 span: Span,
Alex Crichtonf3888432018-05-16 09:11:05 -0700521 raw: bool,
David Tolnay041bcd42017-06-03 09:18:04 -0700522}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700523
Alex Crichtonf3888432018-05-16 09:11:05 -0700524impl Ident {
525 fn _new(string: &str, raw: bool, span: Span) -> Ident {
David Tolnay489c6422018-04-07 08:37:28 -0700526 validate_term(string);
527
Alex Crichtonf3888432018-05-16 09:11:05 -0700528 Ident {
David Tolnayc2309ca2018-06-02 15:47:57 -0700529 sym: string.to_owned(),
Alex Crichtona914a612018-04-04 07:48:44 -0700530 span: span,
Alex Crichtonf3888432018-05-16 09:11:05 -0700531 raw: raw,
David Tolnay041bcd42017-06-03 09:18:04 -0700532 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700533 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700534
Alex Crichtonf3888432018-05-16 09:11:05 -0700535 pub fn new(string: &str, span: Span) -> Ident {
536 Ident::_new(string, false, span)
537 }
538
539 pub fn new_raw(string: &str, span: Span) -> Ident {
540 Ident::_new(string, true, span)
541 }
542
Alex Crichtonb2c94622018-04-04 07:36:41 -0700543 pub fn span(&self) -> Span {
544 self.span
545 }
546
547 pub fn set_span(&mut self, span: Span) {
548 self.span = span;
549 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700550}
551
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000552#[inline]
553fn is_ident_start(c: char) -> bool {
David Tolnay03b43da2018-06-02 15:25:57 -0700554 ('a' <= c && c <= 'z')
555 || ('A' <= c && c <= 'Z')
556 || c == '_'
557 || (c > '\x7f' && UnicodeXID::is_xid_start(c))
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000558}
559
560#[inline]
561fn is_ident_continue(c: char) -> bool {
David Tolnay03b43da2018-06-02 15:25:57 -0700562 ('a' <= c && c <= 'z')
563 || ('A' <= c && c <= 'Z')
564 || c == '_'
565 || ('0' <= c && c <= '9')
566 || (c > '\x7f' && UnicodeXID::is_xid_continue(c))
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000567}
568
David Tolnay489c6422018-04-07 08:37:28 -0700569fn validate_term(string: &str) {
Alex Crichtonf3888432018-05-16 09:11:05 -0700570 let validate = string;
David Tolnay489c6422018-04-07 08:37:28 -0700571 if validate.is_empty() {
Alex Crichtonf3888432018-05-16 09:11:05 -0700572 panic!("Ident is not allowed to be empty; use Option<Ident>");
David Tolnay489c6422018-04-07 08:37:28 -0700573 }
574
575 if validate.bytes().all(|digit| digit >= b'0' && digit <= b'9') {
Alex Crichtonf3888432018-05-16 09:11:05 -0700576 panic!("Ident cannot be a number; use Literal instead");
David Tolnay489c6422018-04-07 08:37:28 -0700577 }
578
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000579 fn ident_ok(string: &str) -> bool {
David Tolnay489c6422018-04-07 08:37:28 -0700580 let mut chars = string.chars();
581 let first = chars.next().unwrap();
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000582 if !is_ident_start(first) {
David Tolnay489c6422018-04-07 08:37:28 -0700583 return false;
584 }
585 for ch in chars {
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000586 if !is_ident_continue(ch) {
David Tolnay489c6422018-04-07 08:37:28 -0700587 return false;
588 }
589 }
590 true
591 }
592
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000593 if !ident_ok(validate) {
Alex Crichtonf3888432018-05-16 09:11:05 -0700594 panic!("{:?} is not a valid Ident", string);
David Tolnay489c6422018-04-07 08:37:28 -0700595 }
596}
597
David Tolnayc0b0f2e2018-09-02 17:56:08 -0700598impl PartialEq for Ident {
599 fn eq(&self, other: &Ident) -> bool {
600 self.sym == other.sym && self.raw == other.raw
601 }
602}
603
604impl<T> PartialEq<T> for Ident
605where
606 T: ?Sized + AsRef<str>,
607{
608 fn eq(&self, other: &T) -> bool {
609 let other = other.as_ref();
610 if self.raw {
611 other.starts_with("r#") && self.sym == other[2..]
612 } else {
613 self.sym == other
614 }
615 }
616}
617
Alex Crichtonf3888432018-05-16 09:11:05 -0700618impl fmt::Display for Ident {
David Tolnay8ad3e3e2017-06-03 16:45:00 -0700619 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Alex Crichtonf3888432018-05-16 09:11:05 -0700620 if self.raw {
621 "r#".fmt(f)?;
622 }
David Tolnayc2309ca2018-06-02 15:47:57 -0700623 self.sym.fmt(f)
Alex Crichtonf3888432018-05-16 09:11:05 -0700624 }
625}
626
627impl fmt::Debug for Ident {
David Tolnayd8fcdb82018-06-02 15:43:53 -0700628 // Ident(proc_macro), Ident(r#union)
629 #[cfg(not(procmacro2_semver_exempt))]
630 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
631 let mut debug = f.debug_tuple("Ident");
632 debug.field(&format_args!("{}", self));
633 debug.finish()
634 }
635
636 // Ident {
637 // sym: proc_macro,
638 // span: bytes(128..138)
639 // }
640 #[cfg(procmacro2_semver_exempt)]
Alex Crichtonf3888432018-05-16 09:11:05 -0700641 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
642 let mut debug = f.debug_struct("Ident");
David Tolnayd8fcdb82018-06-02 15:43:53 -0700643 debug.field("sym", &format_args!("{}", self));
David Tolnay034205f2018-04-22 16:45:28 -0700644 debug.field("span", &self.span);
645 debug.finish()
David Tolnay8ad3e3e2017-06-03 16:45:00 -0700646 }
647}
648
David Tolnay034205f2018-04-22 16:45:28 -0700649#[derive(Clone)]
Alex Crichtonb2c94622018-04-04 07:36:41 -0700650pub struct Literal {
651 text: String,
652 span: Span,
653}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700654
Alex Crichtona914a612018-04-04 07:48:44 -0700655macro_rules! suffixed_numbers {
656 ($($name:ident => $kind:ident,)*) => ($(
657 pub fn $name(n: $kind) -> Literal {
658 Literal::_new(format!(concat!("{}", stringify!($kind)), n))
659 }
660 )*)
661}
662
663macro_rules! unsuffixed_numbers {
664 ($($name:ident => $kind:ident,)*) => ($(
665 pub fn $name(n: $kind) -> Literal {
666 Literal::_new(n.to_string())
667 }
668 )*)
669}
670
Alex Crichton852d53d2017-05-19 19:25:08 -0700671impl Literal {
Alex Crichtonb2c94622018-04-04 07:36:41 -0700672 fn _new(text: String) -> Literal {
673 Literal {
Alex Crichtona914a612018-04-04 07:48:44 -0700674 text: text,
Alex Crichtonb2c94622018-04-04 07:36:41 -0700675 span: Span::call_site(),
676 }
677 }
678
Alex Crichtona914a612018-04-04 07:48:44 -0700679 suffixed_numbers! {
680 u8_suffixed => u8,
681 u16_suffixed => u16,
682 u32_suffixed => u32,
683 u64_suffixed => u64,
684 usize_suffixed => usize,
685 i8_suffixed => i8,
686 i16_suffixed => i16,
687 i32_suffixed => i32,
688 i64_suffixed => i64,
689 isize_suffixed => isize,
690
691 f32_suffixed => f32,
692 f64_suffixed => f64,
693 }
694
Alex Crichton69385662018-11-08 06:30:04 -0800695 #[cfg(u128)]
696 suffixed_numbers! {
697 u128_suffixed => u128,
698 i128_suffixed => i128,
699 }
700
Alex Crichtona914a612018-04-04 07:48:44 -0700701 unsuffixed_numbers! {
702 u8_unsuffixed => u8,
703 u16_unsuffixed => u16,
704 u32_unsuffixed => u32,
705 u64_unsuffixed => u64,
706 usize_unsuffixed => usize,
707 i8_unsuffixed => i8,
708 i16_unsuffixed => i16,
709 i32_unsuffixed => i32,
710 i64_unsuffixed => i64,
711 isize_unsuffixed => isize,
712 }
713
Alex Crichton69385662018-11-08 06:30:04 -0800714 #[cfg(u128)]
715 unsuffixed_numbers! {
716 u128_unsuffixed => u128,
717 i128_unsuffixed => i128,
718 }
719
Alex Crichtona914a612018-04-04 07:48:44 -0700720 pub fn f32_unsuffixed(f: f32) -> Literal {
721 let mut s = f.to_string();
722 if !s.contains(".") {
723 s.push_str(".0");
Alex Crichton76a5cc82017-05-23 07:01:44 -0700724 }
Alex Crichtona914a612018-04-04 07:48:44 -0700725 Literal::_new(s)
726 }
727
728 pub fn f64_unsuffixed(f: f64) -> Literal {
729 let mut s = f.to_string();
730 if !s.contains(".") {
731 s.push_str(".0");
732 }
733 Literal::_new(s)
734 }
735
736 pub fn string(t: &str) -> Literal {
David Tolnay3d9d6ad2018-05-18 10:51:55 -0700737 let mut s = t
738 .chars()
Alex Crichtona914a612018-04-04 07:48:44 -0700739 .flat_map(|c| c.escape_default())
740 .collect::<String>();
741 s.push('"');
742 s.insert(0, '"');
743 Literal::_new(s)
744 }
745
746 pub fn character(t: char) -> Literal {
747 Literal::_new(format!("'{}'", t.escape_default().collect::<String>()))
Alex Crichton76a5cc82017-05-23 07:01:44 -0700748 }
749
Alex Crichton9c2fb0a2017-05-26 08:49:31 -0700750 pub fn byte_string(bytes: &[u8]) -> Literal {
Alex Crichton852d53d2017-05-19 19:25:08 -0700751 let mut escaped = "b\"".to_string();
752 for b in bytes {
753 match *b {
754 b'\0' => escaped.push_str(r"\0"),
755 b'\t' => escaped.push_str(r"\t"),
756 b'\n' => escaped.push_str(r"\n"),
757 b'\r' => escaped.push_str(r"\r"),
758 b'"' => escaped.push_str("\\\""),
759 b'\\' => escaped.push_str("\\\\"),
David Tolnayb28f38a2018-03-31 22:02:29 +0200760 b'\x20'...b'\x7E' => escaped.push(*b as char),
Alex Crichton852d53d2017-05-19 19:25:08 -0700761 _ => escaped.push_str(&format!("\\x{:02X}", b)),
762 }
763 }
764 escaped.push('"');
Alex Crichtonb2c94622018-04-04 07:36:41 -0700765 Literal::_new(escaped)
Alex Crichton76a5cc82017-05-23 07:01:44 -0700766 }
Alex Crichton9c2fb0a2017-05-26 08:49:31 -0700767
Alex Crichtonb2c94622018-04-04 07:36:41 -0700768 pub fn span(&self) -> Span {
769 self.span
Alex Crichton31316622017-05-26 12:54:47 -0700770 }
771
Alex Crichtonb2c94622018-04-04 07:36:41 -0700772 pub fn set_span(&mut self, span: Span) {
773 self.span = span;
Alex Crichton31316622017-05-26 12:54:47 -0700774 }
Alex Crichton852d53d2017-05-19 19:25:08 -0700775}
776
Alex Crichton44bffbc2017-05-19 17:51:59 -0700777impl fmt::Display for Literal {
778 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Alex Crichtonb2c94622018-04-04 07:36:41 -0700779 self.text.fmt(f)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700780 }
781}
782
David Tolnay034205f2018-04-22 16:45:28 -0700783impl fmt::Debug for Literal {
784 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
785 let mut debug = fmt.debug_struct("Literal");
786 debug.field("lit", &format_args!("{}", self.text));
787 #[cfg(procmacro2_semver_exempt)]
788 debug.field("span", &self.span);
789 debug.finish()
790 }
791}
792
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700793fn token_stream(mut input: Cursor) -> PResult<TokenStream> {
Alex Crichton1eb96a02018-04-04 13:07:35 -0700794 let mut trees = Vec::new();
795 loop {
796 let input_no_ws = skip_whitespace(input);
797 if input_no_ws.rest.len() == 0 {
David Tolnay48ea5042018-04-23 19:17:35 -0700798 break;
Alex Crichton1eb96a02018-04-04 13:07:35 -0700799 }
800 if let Ok((a, tokens)) = doc_comment(input_no_ws) {
801 input = a;
802 trees.extend(tokens);
David Tolnay48ea5042018-04-23 19:17:35 -0700803 continue;
Alex Crichton1eb96a02018-04-04 13:07:35 -0700804 }
805
806 let (a, tt) = match token_tree(input_no_ws) {
807 Ok(p) => p,
808 Err(_) => break,
809 };
810 trees.push(tt);
811 input = a;
812 }
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700813 Ok((input, TokenStream { inner: trees }))
Alex Crichton1eb96a02018-04-04 13:07:35 -0700814}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700815
David Tolnay3b1f7d22019-01-28 12:22:11 -0800816#[cfg(not(span_locations))]
Alex Crichton1eb96a02018-04-04 13:07:35 -0700817fn spanned<'a, T>(
818 input: Cursor<'a>,
819 f: fn(Cursor<'a>) -> PResult<'a, T>,
820) -> PResult<'a, (T, ::Span)> {
821 let (a, b) = f(skip_whitespace(input))?;
David Tolnay3b1f7d22019-01-28 12:22:11 -0800822 Ok((a, ((b, ::Span::_new_stable(Span::call_site())))))
David Tolnayddfca052017-12-31 10:41:24 -0500823}
824
David Tolnay3b1f7d22019-01-28 12:22:11 -0800825#[cfg(span_locations)]
Alex Crichton1eb96a02018-04-04 13:07:35 -0700826fn spanned<'a, T>(
827 input: Cursor<'a>,
828 f: fn(Cursor<'a>) -> PResult<'a, T>,
829) -> PResult<'a, (T, ::Span)> {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500830 let input = skip_whitespace(input);
831 let lo = input.off;
Alex Crichton1eb96a02018-04-04 13:07:35 -0700832 let (a, b) = f(input)?;
833 let hi = a.off;
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700834 let span = ::Span::_new_stable(Span { lo: lo, hi: hi });
Alex Crichton1eb96a02018-04-04 13:07:35 -0700835 Ok((a, (b, span)))
836}
837
838fn token_tree(input: Cursor) -> PResult<TokenTree> {
839 let (rest, (mut tt, span)) = spanned(input, token_kind)?;
840 tt.set_span(span);
841 Ok((rest, tt))
Nika Layzellf8d5f212017-12-11 14:07:02 -0500842}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700843
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700844named!(token_kind -> TokenTree, alt!(
David Tolnayf14813f2018-09-08 17:14:07 -0700845 map!(group, |g| TokenTree::Group(::Group::_new_stable(g)))
Alex Crichton44bffbc2017-05-19 17:51:59 -0700846 |
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700847 map!(literal, |l| TokenTree::Literal(::Literal::_new_stable(l))) // must be before symbol
Alex Crichton44bffbc2017-05-19 17:51:59 -0700848 |
Alex Crichtonf3888432018-05-16 09:11:05 -0700849 map!(op, TokenTree::Punct)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700850 |
Alex Crichtonf3888432018-05-16 09:11:05 -0700851 symbol_leading_ws
Alex Crichton44bffbc2017-05-19 17:51:59 -0700852));
853
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700854named!(group -> Group, alt!(
Alex Crichton44bffbc2017-05-19 17:51:59 -0700855 delimited!(
856 punct!("("),
857 token_stream,
858 punct!(")")
David Tolnayf14813f2018-09-08 17:14:07 -0700859 ) => { |ts| Group::new(Delimiter::Parenthesis, ts) }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700860 |
861 delimited!(
862 punct!("["),
863 token_stream,
864 punct!("]")
David Tolnayf14813f2018-09-08 17:14:07 -0700865 ) => { |ts| Group::new(Delimiter::Bracket, ts) }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700866 |
867 delimited!(
868 punct!("{"),
869 token_stream,
870 punct!("}")
David Tolnayf14813f2018-09-08 17:14:07 -0700871 ) => { |ts| Group::new(Delimiter::Brace, ts) }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700872));
873
Alex Crichtonf3888432018-05-16 09:11:05 -0700874fn symbol_leading_ws(input: Cursor) -> PResult<TokenTree> {
875 symbol(skip_whitespace(input))
876}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700877
Alex Crichtonf3888432018-05-16 09:11:05 -0700878fn symbol(input: Cursor) -> PResult<TokenTree> {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700879 let mut chars = input.char_indices();
David Tolnaya202d502017-06-01 12:26:55 -0700880
Alex Crichtonf3888432018-05-16 09:11:05 -0700881 let raw = input.starts_with("r#");
David Tolnaya13d1422018-03-31 21:27:48 +0200882 if raw {
883 chars.next();
884 chars.next();
885 }
886
Alex Crichton44bffbc2017-05-19 17:51:59 -0700887 match chars.next() {
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000888 Some((_, ch)) if is_ident_start(ch) => {}
David Tolnay1218e122017-06-01 11:13:45 -0700889 _ => return Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -0700890 }
891
David Tolnay214c94c2017-06-01 12:42:56 -0700892 let mut end = input.len();
Alex Crichton44bffbc2017-05-19 17:51:59 -0700893 for (i, ch) in chars {
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000894 if !is_ident_continue(ch) {
David Tolnay214c94c2017-06-01 12:42:56 -0700895 end = i;
896 break;
Alex Crichton44bffbc2017-05-19 17:51:59 -0700897 }
898 }
899
David Tolnaya13d1422018-03-31 21:27:48 +0200900 let a = &input.rest[..end];
Alex Crichtonf3888432018-05-16 09:11:05 -0700901 if a == "r#_" {
David Tolnay214c94c2017-06-01 12:42:56 -0700902 Err(LexError)
903 } else {
Alex Crichtonf3888432018-05-16 09:11:05 -0700904 let ident = if raw {
905 ::Ident::_new_raw(&a[2..], ::Span::call_site())
906 } else {
907 ::Ident::new(a, ::Span::call_site())
908 };
909 Ok((input.advance(end), ident.into()))
David Tolnay214c94c2017-06-01 12:42:56 -0700910 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700911}
912
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700913fn literal(input: Cursor) -> PResult<Literal> {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700914 let input_no_ws = skip_whitespace(input);
915
916 match literal_nocapture(input_no_ws) {
David Tolnay1218e122017-06-01 11:13:45 -0700917 Ok((a, ())) => {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700918 let start = input.len() - input_no_ws.len();
919 let len = input_no_ws.len() - a.len();
920 let end = start + len;
David Tolnay3d9d6ad2018-05-18 10:51:55 -0700921 Ok((a, Literal::_new(input.rest[start..end].to_string())))
Alex Crichton44bffbc2017-05-19 17:51:59 -0700922 }
David Tolnay1218e122017-06-01 11:13:45 -0700923 Err(LexError) => Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -0700924 }
925}
926
927named!(literal_nocapture -> (), alt!(
928 string
929 |
930 byte_string
931 |
932 byte
933 |
934 character
935 |
936 float
937 |
938 int
Alex Crichton44bffbc2017-05-19 17:51:59 -0700939));
940
941named!(string -> (), alt!(
942 quoted_string
943 |
944 preceded!(
945 punct!("r"),
946 raw_string
947 ) => { |_| () }
948));
949
950named!(quoted_string -> (), delimited!(
951 punct!("\""),
952 cooked_string,
953 tag!("\"")
954));
955
Nika Layzellf8d5f212017-12-11 14:07:02 -0500956fn cooked_string(input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700957 let mut chars = input.char_indices().peekable();
958 while let Some((byte_offset, ch)) = chars.next() {
959 match ch {
960 '"' => {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500961 return Ok((input.advance(byte_offset), ()));
Alex Crichton44bffbc2017-05-19 17:51:59 -0700962 }
963 '\r' => {
964 if let Some((_, '\n')) = chars.next() {
965 // ...
966 } else {
967 break;
968 }
969 }
David Tolnayb28f38a2018-03-31 22:02:29 +0200970 '\\' => match chars.next() {
971 Some((_, 'x')) => {
972 if !backslash_x_char(&mut chars) {
973 break;
Alex Crichton44bffbc2017-05-19 17:51:59 -0700974 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700975 }
David Tolnayb28f38a2018-03-31 22:02:29 +0200976 Some((_, 'n')) | Some((_, 'r')) | Some((_, 't')) | Some((_, '\\'))
977 | Some((_, '\'')) | Some((_, '"')) | Some((_, '0')) => {}
978 Some((_, 'u')) => {
979 if !backslash_u(&mut chars) {
980 break;
981 }
982 }
983 Some((_, '\n')) | Some((_, '\r')) => {
984 while let Some(&(_, ch)) = chars.peek() {
985 if ch.is_whitespace() {
986 chars.next();
987 } else {
988 break;
989 }
990 }
991 }
992 _ => break,
993 },
Alex Crichton44bffbc2017-05-19 17:51:59 -0700994 _ch => {}
995 }
996 }
David Tolnay1218e122017-06-01 11:13:45 -0700997 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700998}
999
1000named!(byte_string -> (), alt!(
1001 delimited!(
1002 punct!("b\""),
1003 cooked_byte_string,
1004 tag!("\"")
1005 ) => { |_| () }
1006 |
1007 preceded!(
1008 punct!("br"),
1009 raw_string
1010 ) => { |_| () }
1011));
1012
Nika Layzellf8d5f212017-12-11 14:07:02 -05001013fn cooked_byte_string(mut input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001014 let mut bytes = input.bytes().enumerate();
1015 'outer: while let Some((offset, b)) = bytes.next() {
1016 match b {
1017 b'"' => {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001018 return Ok((input.advance(offset), ()));
Alex Crichton44bffbc2017-05-19 17:51:59 -07001019 }
1020 b'\r' => {
1021 if let Some((_, b'\n')) = bytes.next() {
1022 // ...
1023 } else {
1024 break;
1025 }
1026 }
David Tolnayb28f38a2018-03-31 22:02:29 +02001027 b'\\' => match bytes.next() {
1028 Some((_, b'x')) => {
1029 if !backslash_x_byte(&mut bytes) {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001030 break;
1031 }
Alex Crichton44bffbc2017-05-19 17:51:59 -07001032 }
David Tolnayb28f38a2018-03-31 22:02:29 +02001033 Some((_, b'n')) | Some((_, b'r')) | Some((_, b't')) | Some((_, b'\\'))
1034 | Some((_, b'0')) | Some((_, b'\'')) | Some((_, b'"')) => {}
1035 Some((newline, b'\n')) | Some((newline, b'\r')) => {
1036 let rest = input.advance(newline + 1);
1037 for (offset, ch) in rest.char_indices() {
1038 if !ch.is_whitespace() {
1039 input = rest.advance(offset);
1040 bytes = input.bytes().enumerate();
1041 continue 'outer;
1042 }
1043 }
1044 break;
1045 }
1046 _ => break,
1047 },
Alex Crichton44bffbc2017-05-19 17:51:59 -07001048 b if b < 0x80 => {}
1049 _ => break,
1050 }
1051 }
David Tolnay1218e122017-06-01 11:13:45 -07001052 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001053}
1054
Nika Layzellf8d5f212017-12-11 14:07:02 -05001055fn raw_string(input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001056 let mut chars = input.char_indices();
1057 let mut n = 0;
1058 while let Some((byte_offset, ch)) = chars.next() {
1059 match ch {
1060 '"' => {
1061 n = byte_offset;
1062 break;
1063 }
1064 '#' => {}
David Tolnay1218e122017-06-01 11:13:45 -07001065 _ => return Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -07001066 }
1067 }
1068 for (byte_offset, ch) in chars {
1069 match ch {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001070 '"' if input.advance(byte_offset + 1).starts_with(&input.rest[..n]) => {
1071 let rest = input.advance(byte_offset + 1 + n);
David Tolnayb28f38a2018-03-31 22:02:29 +02001072 return Ok((rest, ()));
Alex Crichton44bffbc2017-05-19 17:51:59 -07001073 }
1074 '\r' => {}
1075 _ => {}
1076 }
1077 }
David Tolnay1218e122017-06-01 11:13:45 -07001078 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001079}
1080
1081named!(byte -> (), do_parse!(
1082 punct!("b") >>
1083 tag!("'") >>
1084 cooked_byte >>
1085 tag!("'") >>
1086 (())
1087));
1088
Nika Layzellf8d5f212017-12-11 14:07:02 -05001089fn cooked_byte(input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001090 let mut bytes = input.bytes().enumerate();
1091 let ok = match bytes.next().map(|(_, b)| b) {
David Tolnayb28f38a2018-03-31 22:02:29 +02001092 Some(b'\\') => match bytes.next().map(|(_, b)| b) {
1093 Some(b'x') => backslash_x_byte(&mut bytes),
1094 Some(b'n') | Some(b'r') | Some(b't') | Some(b'\\') | Some(b'0') | Some(b'\'')
1095 | Some(b'"') => true,
1096 _ => false,
1097 },
Alex Crichton44bffbc2017-05-19 17:51:59 -07001098 b => b.is_some(),
1099 };
1100 if ok {
1101 match bytes.next() {
Alex Crichton8c030332018-01-16 08:07:36 -08001102 Some((offset, _)) => {
1103 if input.chars().as_str().is_char_boundary(offset) {
1104 Ok((input.advance(offset), ()))
1105 } else {
1106 Err(LexError)
1107 }
1108 }
Nika Layzellf8d5f212017-12-11 14:07:02 -05001109 None => Ok((input.advance(input.len()), ())),
Alex Crichton44bffbc2017-05-19 17:51:59 -07001110 }
1111 } else {
David Tolnay1218e122017-06-01 11:13:45 -07001112 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001113 }
1114}
1115
1116named!(character -> (), do_parse!(
1117 punct!("'") >>
1118 cooked_char >>
1119 tag!("'") >>
1120 (())
1121));
1122
Nika Layzellf8d5f212017-12-11 14:07:02 -05001123fn cooked_char(input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001124 let mut chars = input.char_indices();
1125 let ok = match chars.next().map(|(_, ch)| ch) {
David Tolnayb28f38a2018-03-31 22:02:29 +02001126 Some('\\') => match chars.next().map(|(_, ch)| ch) {
1127 Some('x') => backslash_x_char(&mut chars),
1128 Some('u') => backslash_u(&mut chars),
1129 Some('n') | Some('r') | Some('t') | Some('\\') | Some('0') | Some('\'') | Some('"') => {
1130 true
Alex Crichton44bffbc2017-05-19 17:51:59 -07001131 }
David Tolnayb28f38a2018-03-31 22:02:29 +02001132 _ => false,
1133 },
Alex Crichton44bffbc2017-05-19 17:51:59 -07001134 ch => ch.is_some(),
1135 };
1136 if ok {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001137 match chars.next() {
1138 Some((idx, _)) => Ok((input.advance(idx), ())),
1139 None => Ok((input.advance(input.len()), ())),
1140 }
Alex Crichton44bffbc2017-05-19 17:51:59 -07001141 } else {
David Tolnay1218e122017-06-01 11:13:45 -07001142 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001143 }
1144}
1145
1146macro_rules! next_ch {
1147 ($chars:ident @ $pat:pat $(| $rest:pat)*) => {
1148 match $chars.next() {
1149 Some((_, ch)) => match ch {
1150 $pat $(| $rest)* => ch,
1151 _ => return false,
1152 },
1153 None => return false
1154 }
1155 };
1156}
1157
1158fn backslash_x_char<I>(chars: &mut I) -> bool
David Tolnayb28f38a2018-03-31 22:02:29 +02001159where
1160 I: Iterator<Item = (usize, char)>,
Alex Crichton44bffbc2017-05-19 17:51:59 -07001161{
1162 next_ch!(chars @ '0'...'7');
1163 next_ch!(chars @ '0'...'9' | 'a'...'f' | 'A'...'F');
1164 true
1165}
1166
1167fn backslash_x_byte<I>(chars: &mut I) -> bool
David Tolnayb28f38a2018-03-31 22:02:29 +02001168where
1169 I: Iterator<Item = (usize, u8)>,
Alex Crichton44bffbc2017-05-19 17:51:59 -07001170{
1171 next_ch!(chars @ b'0'...b'9' | b'a'...b'f' | b'A'...b'F');
1172 next_ch!(chars @ b'0'...b'9' | b'a'...b'f' | b'A'...b'F');
1173 true
1174}
1175
1176fn backslash_u<I>(chars: &mut I) -> bool
David Tolnayb28f38a2018-03-31 22:02:29 +02001177where
1178 I: Iterator<Item = (usize, char)>,
Alex Crichton44bffbc2017-05-19 17:51:59 -07001179{
1180 next_ch!(chars @ '{');
1181 next_ch!(chars @ '0'...'9' | 'a'...'f' | 'A'...'F');
David Tolnay8d109342017-12-25 18:24:45 -05001182 loop {
1183 let c = next_ch!(chars @ '0'...'9' | 'a'...'f' | 'A'...'F' | '_' | '}');
1184 if c == '}' {
1185 return true;
1186 }
Alex Crichton44bffbc2017-05-19 17:51:59 -07001187 }
Alex Crichton44bffbc2017-05-19 17:51:59 -07001188}
1189
Nika Layzellf8d5f212017-12-11 14:07:02 -05001190fn float(input: Cursor) -> PResult<()> {
David Tolnay744a6b82017-06-01 11:34:29 -07001191 let (rest, ()) = float_digits(input)?;
1192 for suffix in &["f32", "f64"] {
1193 if rest.starts_with(suffix) {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001194 return word_break(rest.advance(suffix.len()));
David Tolnay744a6b82017-06-01 11:34:29 -07001195 }
1196 }
1197 word_break(rest)
1198}
Alex Crichton44bffbc2017-05-19 17:51:59 -07001199
Nika Layzellf8d5f212017-12-11 14:07:02 -05001200fn float_digits(input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001201 let mut chars = input.chars().peekable();
1202 match chars.next() {
1203 Some(ch) if ch >= '0' && ch <= '9' => {}
David Tolnay1218e122017-06-01 11:13:45 -07001204 _ => return Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -07001205 }
1206
1207 let mut len = 1;
1208 let mut has_dot = false;
1209 let mut has_exp = false;
1210 while let Some(&ch) = chars.peek() {
1211 match ch {
1212 '0'...'9' | '_' => {
1213 chars.next();
1214 len += 1;
1215 }
1216 '.' => {
1217 if has_dot {
1218 break;
1219 }
1220 chars.next();
David Tolnayb28f38a2018-03-31 22:02:29 +02001221 if chars
1222 .peek()
1223 .map(|&ch| ch == '.' || UnicodeXID::is_xid_start(ch))
1224 .unwrap_or(false)
1225 {
David Tolnay1218e122017-06-01 11:13:45 -07001226 return Err(LexError);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001227 }
1228 len += 1;
1229 has_dot = true;
1230 }
1231 'e' | 'E' => {
1232 chars.next();
1233 len += 1;
1234 has_exp = true;
1235 break;
1236 }
1237 _ => break,
1238 }
1239 }
1240
Nika Layzellf8d5f212017-12-11 14:07:02 -05001241 let rest = input.advance(len);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001242 if !(has_dot || has_exp || rest.starts_with("f32") || rest.starts_with("f64")) {
David Tolnay1218e122017-06-01 11:13:45 -07001243 return Err(LexError);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001244 }
1245
1246 if has_exp {
1247 let mut has_exp_value = false;
1248 while let Some(&ch) = chars.peek() {
1249 match ch {
1250 '+' | '-' => {
1251 if has_exp_value {
1252 break;
1253 }
1254 chars.next();
1255 len += 1;
1256 }
1257 '0'...'9' => {
1258 chars.next();
1259 len += 1;
1260 has_exp_value = true;
1261 }
1262 '_' => {
1263 chars.next();
1264 len += 1;
1265 }
1266 _ => break,
1267 }
1268 }
1269 if !has_exp_value {
David Tolnay1218e122017-06-01 11:13:45 -07001270 return Err(LexError);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001271 }
1272 }
1273
Nika Layzellf8d5f212017-12-11 14:07:02 -05001274 Ok((input.advance(len), ()))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001275}
1276
Nika Layzellf8d5f212017-12-11 14:07:02 -05001277fn int(input: Cursor) -> PResult<()> {
David Tolnay744a6b82017-06-01 11:34:29 -07001278 let (rest, ()) = digits(input)?;
1279 for suffix in &[
David Tolnay48ea5042018-04-23 19:17:35 -07001280 "isize", "i8", "i16", "i32", "i64", "i128", "usize", "u8", "u16", "u32", "u64", "u128",
David Tolnay744a6b82017-06-01 11:34:29 -07001281 ] {
1282 if rest.starts_with(suffix) {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001283 return word_break(rest.advance(suffix.len()));
David Tolnay744a6b82017-06-01 11:34:29 -07001284 }
1285 }
1286 word_break(rest)
1287}
Alex Crichton44bffbc2017-05-19 17:51:59 -07001288
Nika Layzellf8d5f212017-12-11 14:07:02 -05001289fn digits(mut input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001290 let base = if input.starts_with("0x") {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001291 input = input.advance(2);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001292 16
1293 } else if input.starts_with("0o") {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001294 input = input.advance(2);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001295 8
1296 } else if input.starts_with("0b") {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001297 input = input.advance(2);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001298 2
1299 } else {
1300 10
1301 };
1302
Alex Crichton44bffbc2017-05-19 17:51:59 -07001303 let mut len = 0;
1304 let mut empty = true;
1305 for b in input.bytes() {
1306 let digit = match b {
1307 b'0'...b'9' => (b - b'0') as u64,
1308 b'a'...b'f' => 10 + (b - b'a') as u64,
1309 b'A'...b'F' => 10 + (b - b'A') as u64,
1310 b'_' => {
1311 if empty && base == 10 {
David Tolnay1218e122017-06-01 11:13:45 -07001312 return Err(LexError);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001313 }
1314 len += 1;
1315 continue;
1316 }
1317 _ => break,
1318 };
1319 if digit >= base {
David Tolnay1218e122017-06-01 11:13:45 -07001320 return Err(LexError);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001321 }
Alex Crichton44bffbc2017-05-19 17:51:59 -07001322 len += 1;
1323 empty = false;
1324 }
1325 if empty {
David Tolnay1218e122017-06-01 11:13:45 -07001326 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001327 } else {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001328 Ok((input.advance(len), ()))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001329 }
1330}
1331
Alex Crichtonf3888432018-05-16 09:11:05 -07001332fn op(input: Cursor) -> PResult<Punct> {
David Tolnayea75c5f2017-05-31 23:40:33 -07001333 let input = skip_whitespace(input);
1334 match op_char(input) {
Alex Crichtonf3888432018-05-16 09:11:05 -07001335 Ok((rest, '\'')) => {
1336 symbol(rest)?;
1337 Ok((rest, Punct::new('\'', Spacing::Joint)))
1338 }
David Tolnay1218e122017-06-01 11:13:45 -07001339 Ok((rest, ch)) => {
David Tolnayea75c5f2017-05-31 23:40:33 -07001340 let kind = match op_char(rest) {
Alex Crichton1a7f7622017-07-05 17:47:15 -07001341 Ok(_) => Spacing::Joint,
1342 Err(LexError) => Spacing::Alone,
David Tolnayea75c5f2017-05-31 23:40:33 -07001343 };
Alex Crichtonf3888432018-05-16 09:11:05 -07001344 Ok((rest, Punct::new(ch, kind)))
David Tolnayea75c5f2017-05-31 23:40:33 -07001345 }
David Tolnay1218e122017-06-01 11:13:45 -07001346 Err(LexError) => Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -07001347 }
1348}
1349
Nika Layzellf8d5f212017-12-11 14:07:02 -05001350fn op_char(input: Cursor) -> PResult<char> {
David Tolnay3a592ad2018-04-22 21:20:24 -07001351 if input.starts_with("//") || input.starts_with("/*") {
1352 // Do not accept `/` of a comment as an op.
1353 return Err(LexError);
1354 }
1355
David Tolnayea75c5f2017-05-31 23:40:33 -07001356 let mut chars = input.chars();
1357 let first = match chars.next() {
1358 Some(ch) => ch,
1359 None => {
David Tolnay1218e122017-06-01 11:13:45 -07001360 return Err(LexError);
David Tolnayea75c5f2017-05-31 23:40:33 -07001361 }
1362 };
Alex Crichtonf3888432018-05-16 09:11:05 -07001363 let recognized = "~!@#$%^&*-=+|;:,<.>/?'";
David Tolnayea75c5f2017-05-31 23:40:33 -07001364 if recognized.contains(first) {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001365 Ok((input.advance(first.len_utf8()), first))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001366 } else {
David Tolnay1218e122017-06-01 11:13:45 -07001367 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001368 }
1369}
1370
Alex Crichton1eb96a02018-04-04 13:07:35 -07001371fn doc_comment(input: Cursor) -> PResult<Vec<TokenTree>> {
1372 let mut trees = Vec::new();
1373 let (rest, ((comment, inner), span)) = spanned(input, doc_comment_contents)?;
Alex Crichtonf3888432018-05-16 09:11:05 -07001374 trees.push(TokenTree::Punct(Punct::new('#', Spacing::Alone)));
Alex Crichton1eb96a02018-04-04 13:07:35 -07001375 if inner {
Alex Crichtonf3888432018-05-16 09:11:05 -07001376 trees.push(Punct::new('!', Spacing::Alone).into());
Alex Crichton1eb96a02018-04-04 13:07:35 -07001377 }
1378 let mut stream = vec![
Alex Crichtonf3888432018-05-16 09:11:05 -07001379 TokenTree::Ident(::Ident::new("doc", span)),
1380 TokenTree::Punct(Punct::new('=', Spacing::Alone)),
Alex Crichton1eb96a02018-04-04 13:07:35 -07001381 TokenTree::Literal(::Literal::string(comment)),
1382 ];
1383 for tt in stream.iter_mut() {
1384 tt.set_span(span);
1385 }
David Tolnayf14813f2018-09-08 17:14:07 -07001386 let group = Group::new(Delimiter::Bracket, stream.into_iter().collect());
1387 trees.push(::Group::_new_stable(group).into());
Alex Crichton1eb96a02018-04-04 13:07:35 -07001388 for tt in trees.iter_mut() {
1389 tt.set_span(span);
1390 }
1391 Ok((rest, trees))
1392}
1393
1394named!(doc_comment_contents -> (&str, bool), alt!(
Alex Crichton44bffbc2017-05-19 17:51:59 -07001395 do_parse!(
1396 punct!("//!") >>
Alex Crichton1eb96a02018-04-04 13:07:35 -07001397 s: take_until_newline_or_eof!() >>
1398 ((s, true))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001399 )
1400 |
1401 do_parse!(
1402 option!(whitespace) >>
1403 peek!(tag!("/*!")) >>
Alex Crichton1eb96a02018-04-04 13:07:35 -07001404 s: block_comment >>
1405 ((s, true))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001406 )
1407 |
1408 do_parse!(
1409 punct!("///") >>
1410 not!(tag!("/")) >>
Alex Crichton1eb96a02018-04-04 13:07:35 -07001411 s: take_until_newline_or_eof!() >>
1412 ((s, false))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001413 )
1414 |
1415 do_parse!(
1416 option!(whitespace) >>
1417 peek!(tuple!(tag!("/**"), not!(tag!("*")))) >>
Alex Crichton1eb96a02018-04-04 13:07:35 -07001418 s: block_comment >>
1419 ((s, false))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001420 )
1421));