blob: c4298d60d32ee670d9fac9ed30cd2d8ac16f0719 [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 {
David Tolnay6c3b0702019-04-22 16:48:34 -070038 // Create a dummy file & add it to the source map
39 SOURCE_MAP.with(|cm| {
Nika Layzella9dbc182017-12-30 14:50:13 -050040 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> {
David Tolnay6c3b0702019-04-22 16:48:34 -070059 // Create a dummy file & add it to the source map
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! {
David Tolnay6c3b0702019-04-22 16:48:34 -0700228 static SOURCE_MAP: RefCell<SourceMap> = RefCell::new(SourceMap {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500229 // 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)]
David Tolnay6c3b0702019-04-22 16:48:34 -0700298struct SourceMap {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500299 files: Vec<FileInfo>,
300}
301
David Tolnay3b1f7d22019-01-28 12:22:11 -0800302#[cfg(span_locations)]
David Tolnay6c3b0702019-04-22 16:48:34 -0700303impl SourceMap {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500304 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 {
David Tolnayf0814122019-07-19 11:53:55 -0700317 lo,
David Tolnayb28f38a2018-03-31 22:02:29 +0200318 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(),
David Tolnayf0814122019-07-19 11:53:55 -0700324 span,
325 lines,
Nika Layzellf8d5f212017-12-11 14:07:02 -0500326 });
327
David Tolnay3b1f7d22019-01-28 12:22:11 -0800328 #[cfg(not(procmacro2_semver_exempt))]
David Tolnayf0814122019-07-19 11:53:55 -0700329 self.files.push(FileInfo { span, lines });
David Tolnay3b1f7d22019-01-28 12:22:11 -0800330 let _ = name;
331
Nika Layzellf8d5f212017-12-11 14:07:02 -0500332 span
333 }
334
335 fn fileinfo(&self, span: Span) -> &FileInfo {
336 for file in &self.files {
337 if file.span_within(span) {
338 return file;
339 }
340 }
341 panic!("Invalid span with no related FileInfo!");
342 }
343}
344
David Tolnay034205f2018-04-22 16:45:28 -0700345#[derive(Clone, Copy, PartialEq, Eq)]
David Tolnayddfca052017-12-31 10:41:24 -0500346pub struct Span {
David Tolnay3b1f7d22019-01-28 12:22:11 -0800347 #[cfg(span_locations)]
David Tolnayddfca052017-12-31 10:41:24 -0500348 lo: u32,
David Tolnay3b1f7d22019-01-28 12:22:11 -0800349 #[cfg(span_locations)]
David Tolnayddfca052017-12-31 10:41:24 -0500350 hi: u32,
351}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700352
353impl Span {
David Tolnay3b1f7d22019-01-28 12:22:11 -0800354 #[cfg(not(span_locations))]
Alex Crichton44bffbc2017-05-19 17:51:59 -0700355 pub fn call_site() -> Span {
David Tolnay79105e52017-12-31 11:03:04 -0500356 Span {}
357 }
358
David Tolnay3b1f7d22019-01-28 12:22:11 -0800359 #[cfg(span_locations)]
David Tolnay79105e52017-12-31 11:03:04 -0500360 pub fn call_site() -> Span {
361 Span { lo: 0, hi: 0 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700362 }
Alex Crichtone6085b72017-11-21 07:24:25 -0800363
David Tolnay3b1f7d22019-01-28 12:22:11 -0800364 #[cfg(procmacro2_semver_exempt)]
Alex Crichtone6085b72017-11-21 07:24:25 -0800365 pub fn def_site() -> Span {
David Tolnay79105e52017-12-31 11:03:04 -0500366 Span::call_site()
Nika Layzellf8d5f212017-12-11 14:07:02 -0500367 }
368
David Tolnay3b1f7d22019-01-28 12:22:11 -0800369 #[cfg(procmacro2_semver_exempt)]
David Tolnay4e8e3972018-01-05 18:10:22 -0800370 pub fn resolved_at(&self, _other: Span) -> Span {
371 // Stable spans consist only of line/column information, so
372 // `resolved_at` and `located_at` only select which span the
373 // caller wants line/column information from.
374 *self
375 }
376
David Tolnay3b1f7d22019-01-28 12:22:11 -0800377 #[cfg(procmacro2_semver_exempt)]
David Tolnay4e8e3972018-01-05 18:10:22 -0800378 pub fn located_at(&self, other: Span) -> Span {
379 other
380 }
381
David Tolnay1ebe3972018-01-02 20:14:20 -0800382 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500383 pub fn source_file(&self) -> SourceFile {
David Tolnay6c3b0702019-04-22 16:48:34 -0700384 SOURCE_MAP.with(|cm| {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500385 let cm = cm.borrow();
386 let fi = cm.fileinfo(*self);
387 SourceFile {
David Tolnay9cd3b4c2018-11-11 16:47:32 -0800388 path: Path::new(&fi.name).to_owned(),
Nika Layzellf8d5f212017-12-11 14:07:02 -0500389 }
390 })
391 }
392
David Tolnay3b1f7d22019-01-28 12:22:11 -0800393 #[cfg(span_locations)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500394 pub fn start(&self) -> LineColumn {
David Tolnay6c3b0702019-04-22 16:48:34 -0700395 SOURCE_MAP.with(|cm| {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500396 let cm = cm.borrow();
397 let fi = cm.fileinfo(*self);
398 fi.offset_line_column(self.lo as usize)
399 })
400 }
401
David Tolnay3b1f7d22019-01-28 12:22:11 -0800402 #[cfg(span_locations)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500403 pub fn end(&self) -> LineColumn {
David Tolnay6c3b0702019-04-22 16:48:34 -0700404 SOURCE_MAP.with(|cm| {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500405 let cm = cm.borrow();
406 let fi = cm.fileinfo(*self);
407 fi.offset_line_column(self.hi as usize)
408 })
409 }
410
David Tolnay1ebe3972018-01-02 20:14:20 -0800411 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500412 pub fn join(&self, other: Span) -> Option<Span> {
David Tolnay6c3b0702019-04-22 16:48:34 -0700413 SOURCE_MAP.with(|cm| {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500414 let cm = cm.borrow();
415 // If `other` is not within the same FileInfo as us, return None.
416 if !cm.fileinfo(*self).span_within(other) {
417 return None;
418 }
419 Some(Span {
420 lo: cmp::min(self.lo, other.lo),
421 hi: cmp::max(self.hi, other.hi),
422 })
423 })
Alex Crichtone6085b72017-11-21 07:24:25 -0800424 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700425}
426
David Tolnay034205f2018-04-22 16:45:28 -0700427impl fmt::Debug for Span {
428 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
429 #[cfg(procmacro2_semver_exempt)]
430 return write!(f, "bytes({}..{})", self.lo, self.hi);
431
432 #[cfg(not(procmacro2_semver_exempt))]
433 write!(f, "Span")
434 }
435}
436
David Tolnayfd8cdc82019-01-19 19:23:59 -0800437pub fn debug_span_field_if_nontrivial(debug: &mut fmt::DebugStruct, span: Span) {
438 if cfg!(procmacro2_semver_exempt) {
439 debug.field("span", &span);
440 }
441}
442
Alex Crichtonf3888432018-05-16 09:11:05 -0700443#[derive(Clone)]
David Tolnayf14813f2018-09-08 17:14:07 -0700444pub struct Group {
445 delimiter: Delimiter,
446 stream: TokenStream,
447 span: Span,
448}
449
450impl Group {
451 pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
452 Group {
David Tolnayf0814122019-07-19 11:53:55 -0700453 delimiter,
454 stream,
David Tolnayf14813f2018-09-08 17:14:07 -0700455 span: Span::call_site(),
456 }
457 }
458
459 pub fn delimiter(&self) -> Delimiter {
460 self.delimiter
461 }
462
463 pub fn stream(&self) -> TokenStream {
464 self.stream.clone()
465 }
466
467 pub fn span(&self) -> Span {
468 self.span
469 }
470
David Tolnay3b1f7d22019-01-28 12:22:11 -0800471 #[cfg(procmacro2_semver_exempt)]
David Tolnayf14813f2018-09-08 17:14:07 -0700472 pub fn span_open(&self) -> Span {
473 self.span
474 }
475
David Tolnay3b1f7d22019-01-28 12:22:11 -0800476 #[cfg(procmacro2_semver_exempt)]
David Tolnayf14813f2018-09-08 17:14:07 -0700477 pub fn span_close(&self) -> Span {
478 self.span
479 }
480
481 pub fn set_span(&mut self, span: Span) {
482 self.span = span;
483 }
484}
485
486impl fmt::Display for Group {
487 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
488 let (left, right) = match self.delimiter {
489 Delimiter::Parenthesis => ("(", ")"),
490 Delimiter::Brace => ("{", "}"),
491 Delimiter::Bracket => ("[", "]"),
492 Delimiter::None => ("", ""),
493 };
494
495 f.write_str(left)?;
496 self.stream.fmt(f)?;
497 f.write_str(right)?;
498
499 Ok(())
500 }
501}
502
503impl fmt::Debug for Group {
504 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
505 let mut debug = fmt.debug_struct("Group");
506 debug.field("delimiter", &self.delimiter);
507 debug.field("stream", &self.stream);
508 #[cfg(procmacro2_semver_exempt)]
509 debug.field("span", &self.span);
510 debug.finish()
511 }
512}
513
514#[derive(Clone)]
Alex Crichtonf3888432018-05-16 09:11:05 -0700515pub struct Ident {
David Tolnayc2309ca2018-06-02 15:47:57 -0700516 sym: String,
Alex Crichtonb2c94622018-04-04 07:36:41 -0700517 span: Span,
Alex Crichtonf3888432018-05-16 09:11:05 -0700518 raw: bool,
David Tolnay041bcd42017-06-03 09:18:04 -0700519}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700520
Alex Crichtonf3888432018-05-16 09:11:05 -0700521impl Ident {
522 fn _new(string: &str, raw: bool, span: Span) -> Ident {
David Tolnay637eef42019-04-20 13:36:18 -0700523 validate_ident(string);
David Tolnay489c6422018-04-07 08:37:28 -0700524
Alex Crichtonf3888432018-05-16 09:11:05 -0700525 Ident {
David Tolnayc2309ca2018-06-02 15:47:57 -0700526 sym: string.to_owned(),
David Tolnayf0814122019-07-19 11:53:55 -0700527 span,
528 raw,
David Tolnay041bcd42017-06-03 09:18:04 -0700529 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700530 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700531
Alex Crichtonf3888432018-05-16 09:11:05 -0700532 pub fn new(string: &str, span: Span) -> Ident {
533 Ident::_new(string, false, span)
534 }
535
536 pub fn new_raw(string: &str, span: Span) -> Ident {
537 Ident::_new(string, true, span)
538 }
539
Alex Crichtonb2c94622018-04-04 07:36:41 -0700540 pub fn span(&self) -> Span {
541 self.span
542 }
543
544 pub fn set_span(&mut self, span: Span) {
545 self.span = span;
546 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700547}
548
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000549#[inline]
550fn is_ident_start(c: char) -> bool {
David Tolnay03b43da2018-06-02 15:25:57 -0700551 ('a' <= c && c <= 'z')
552 || ('A' <= c && c <= 'Z')
553 || c == '_'
554 || (c > '\x7f' && UnicodeXID::is_xid_start(c))
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000555}
556
557#[inline]
558fn is_ident_continue(c: char) -> bool {
David Tolnay03b43da2018-06-02 15:25:57 -0700559 ('a' <= c && c <= 'z')
560 || ('A' <= c && c <= 'Z')
561 || c == '_'
562 || ('0' <= c && c <= '9')
563 || (c > '\x7f' && UnicodeXID::is_xid_continue(c))
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000564}
565
David Tolnay637eef42019-04-20 13:36:18 -0700566fn validate_ident(string: &str) {
Alex Crichtonf3888432018-05-16 09:11:05 -0700567 let validate = string;
David Tolnay489c6422018-04-07 08:37:28 -0700568 if validate.is_empty() {
Alex Crichtonf3888432018-05-16 09:11:05 -0700569 panic!("Ident is not allowed to be empty; use Option<Ident>");
David Tolnay489c6422018-04-07 08:37:28 -0700570 }
571
572 if validate.bytes().all(|digit| digit >= b'0' && digit <= b'9') {
Alex Crichtonf3888432018-05-16 09:11:05 -0700573 panic!("Ident cannot be a number; use Literal instead");
David Tolnay489c6422018-04-07 08:37:28 -0700574 }
575
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000576 fn ident_ok(string: &str) -> bool {
David Tolnay489c6422018-04-07 08:37:28 -0700577 let mut chars = string.chars();
578 let first = chars.next().unwrap();
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000579 if !is_ident_start(first) {
David Tolnay489c6422018-04-07 08:37:28 -0700580 return false;
581 }
582 for ch in chars {
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000583 if !is_ident_continue(ch) {
David Tolnay489c6422018-04-07 08:37:28 -0700584 return false;
585 }
586 }
587 true
588 }
589
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000590 if !ident_ok(validate) {
Alex Crichtonf3888432018-05-16 09:11:05 -0700591 panic!("{:?} is not a valid Ident", string);
David Tolnay489c6422018-04-07 08:37:28 -0700592 }
593}
594
David Tolnayc0b0f2e2018-09-02 17:56:08 -0700595impl PartialEq for Ident {
596 fn eq(&self, other: &Ident) -> bool {
597 self.sym == other.sym && self.raw == other.raw
598 }
599}
600
601impl<T> PartialEq<T> for Ident
602where
603 T: ?Sized + AsRef<str>,
604{
605 fn eq(&self, other: &T) -> bool {
606 let other = other.as_ref();
607 if self.raw {
608 other.starts_with("r#") && self.sym == other[2..]
609 } else {
610 self.sym == other
611 }
612 }
613}
614
Alex Crichtonf3888432018-05-16 09:11:05 -0700615impl fmt::Display for Ident {
David Tolnay8ad3e3e2017-06-03 16:45:00 -0700616 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Alex Crichtonf3888432018-05-16 09:11:05 -0700617 if self.raw {
618 "r#".fmt(f)?;
619 }
David Tolnayc2309ca2018-06-02 15:47:57 -0700620 self.sym.fmt(f)
Alex Crichtonf3888432018-05-16 09:11:05 -0700621 }
622}
623
624impl fmt::Debug for Ident {
David Tolnayd8fcdb82018-06-02 15:43:53 -0700625 // Ident(proc_macro), Ident(r#union)
626 #[cfg(not(procmacro2_semver_exempt))]
627 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
628 let mut debug = f.debug_tuple("Ident");
629 debug.field(&format_args!("{}", self));
630 debug.finish()
631 }
632
633 // Ident {
634 // sym: proc_macro,
635 // span: bytes(128..138)
636 // }
637 #[cfg(procmacro2_semver_exempt)]
Alex Crichtonf3888432018-05-16 09:11:05 -0700638 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
639 let mut debug = f.debug_struct("Ident");
David Tolnayd8fcdb82018-06-02 15:43:53 -0700640 debug.field("sym", &format_args!("{}", self));
David Tolnay034205f2018-04-22 16:45:28 -0700641 debug.field("span", &self.span);
642 debug.finish()
David Tolnay8ad3e3e2017-06-03 16:45:00 -0700643 }
644}
645
David Tolnay034205f2018-04-22 16:45:28 -0700646#[derive(Clone)]
Alex Crichtonb2c94622018-04-04 07:36:41 -0700647pub struct Literal {
648 text: String,
649 span: Span,
650}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700651
Alex Crichtona914a612018-04-04 07:48:44 -0700652macro_rules! suffixed_numbers {
653 ($($name:ident => $kind:ident,)*) => ($(
654 pub fn $name(n: $kind) -> Literal {
655 Literal::_new(format!(concat!("{}", stringify!($kind)), n))
656 }
657 )*)
658}
659
660macro_rules! unsuffixed_numbers {
661 ($($name:ident => $kind:ident,)*) => ($(
662 pub fn $name(n: $kind) -> Literal {
663 Literal::_new(n.to_string())
664 }
665 )*)
666}
667
Alex Crichton852d53d2017-05-19 19:25:08 -0700668impl Literal {
Alex Crichtonb2c94622018-04-04 07:36:41 -0700669 fn _new(text: String) -> Literal {
670 Literal {
David Tolnayf0814122019-07-19 11:53:55 -0700671 text,
Alex Crichtonb2c94622018-04-04 07:36:41 -0700672 span: Span::call_site(),
673 }
674 }
675
Alex Crichtona914a612018-04-04 07:48:44 -0700676 suffixed_numbers! {
677 u8_suffixed => u8,
678 u16_suffixed => u16,
679 u32_suffixed => u32,
680 u64_suffixed => u64,
David Tolnay1596a8c2019-07-19 11:45:26 -0700681 u128_suffixed => u128,
Alex Crichtona914a612018-04-04 07:48:44 -0700682 usize_suffixed => usize,
683 i8_suffixed => i8,
684 i16_suffixed => i16,
685 i32_suffixed => i32,
686 i64_suffixed => i64,
David Tolnay1596a8c2019-07-19 11:45:26 -0700687 i128_suffixed => i128,
Alex Crichtona914a612018-04-04 07:48:44 -0700688 isize_suffixed => isize,
689
690 f32_suffixed => f32,
691 f64_suffixed => f64,
692 }
693
694 unsuffixed_numbers! {
695 u8_unsuffixed => u8,
696 u16_unsuffixed => u16,
697 u32_unsuffixed => u32,
698 u64_unsuffixed => u64,
David Tolnay1596a8c2019-07-19 11:45:26 -0700699 u128_unsuffixed => u128,
Alex Crichtona914a612018-04-04 07:48:44 -0700700 usize_unsuffixed => usize,
701 i8_unsuffixed => i8,
702 i16_unsuffixed => i16,
703 i32_unsuffixed => i32,
704 i64_unsuffixed => i64,
Alex Crichton69385662018-11-08 06:30:04 -0800705 i128_unsuffixed => i128,
David Tolnay1596a8c2019-07-19 11:45:26 -0700706 isize_unsuffixed => isize,
Alex Crichton69385662018-11-08 06:30:04 -0800707 }
708
Alex Crichtona914a612018-04-04 07:48:44 -0700709 pub fn f32_unsuffixed(f: f32) -> Literal {
710 let mut s = f.to_string();
711 if !s.contains(".") {
712 s.push_str(".0");
Alex Crichton76a5cc82017-05-23 07:01:44 -0700713 }
Alex Crichtona914a612018-04-04 07:48:44 -0700714 Literal::_new(s)
715 }
716
717 pub fn f64_unsuffixed(f: f64) -> Literal {
718 let mut s = f.to_string();
719 if !s.contains(".") {
720 s.push_str(".0");
721 }
722 Literal::_new(s)
723 }
724
725 pub fn string(t: &str) -> Literal {
David Tolnaye4482f42019-04-22 16:15:14 -0700726 let mut text = String::with_capacity(t.len() + 2);
727 text.push('"');
728 for c in t.chars() {
729 if c == '\'' {
730 // escape_default turns this into "\'" which is unnecessary.
731 text.push(c);
732 } else {
733 text.extend(c.escape_default());
734 }
735 }
736 text.push('"');
737 Literal::_new(text)
Alex Crichtona914a612018-04-04 07:48:44 -0700738 }
739
740 pub fn character(t: char) -> Literal {
David Tolnaye4482f42019-04-22 16:15:14 -0700741 let mut text = String::new();
742 text.push('\'');
743 if t == '"' {
744 // escape_default turns this into '\"' which is unnecessary.
745 text.push(t);
746 } else {
747 text.extend(t.escape_default());
748 }
749 text.push('\'');
750 Literal::_new(text)
Alex Crichton76a5cc82017-05-23 07:01:44 -0700751 }
752
Alex Crichton9c2fb0a2017-05-26 08:49:31 -0700753 pub fn byte_string(bytes: &[u8]) -> Literal {
Alex Crichton852d53d2017-05-19 19:25:08 -0700754 let mut escaped = "b\"".to_string();
755 for b in bytes {
756 match *b {
757 b'\0' => escaped.push_str(r"\0"),
758 b'\t' => escaped.push_str(r"\t"),
759 b'\n' => escaped.push_str(r"\n"),
760 b'\r' => escaped.push_str(r"\r"),
761 b'"' => escaped.push_str("\\\""),
762 b'\\' => escaped.push_str("\\\\"),
David Tolnayb28f38a2018-03-31 22:02:29 +0200763 b'\x20'...b'\x7E' => escaped.push(*b as char),
Alex Crichton852d53d2017-05-19 19:25:08 -0700764 _ => escaped.push_str(&format!("\\x{:02X}", b)),
765 }
766 }
767 escaped.push('"');
Alex Crichtonb2c94622018-04-04 07:36:41 -0700768 Literal::_new(escaped)
Alex Crichton76a5cc82017-05-23 07:01:44 -0700769 }
Alex Crichton9c2fb0a2017-05-26 08:49:31 -0700770
Alex Crichtonb2c94622018-04-04 07:36:41 -0700771 pub fn span(&self) -> Span {
772 self.span
Alex Crichton31316622017-05-26 12:54:47 -0700773 }
774
Alex Crichtonb2c94622018-04-04 07:36:41 -0700775 pub fn set_span(&mut self, span: Span) {
776 self.span = span;
Alex Crichton31316622017-05-26 12:54:47 -0700777 }
Alex Crichton852d53d2017-05-19 19:25:08 -0700778}
779
Alex Crichton44bffbc2017-05-19 17:51:59 -0700780impl fmt::Display for Literal {
781 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Alex Crichtonb2c94622018-04-04 07:36:41 -0700782 self.text.fmt(f)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700783 }
784}
785
David Tolnay034205f2018-04-22 16:45:28 -0700786impl fmt::Debug for Literal {
787 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
788 let mut debug = fmt.debug_struct("Literal");
789 debug.field("lit", &format_args!("{}", self.text));
790 #[cfg(procmacro2_semver_exempt)]
791 debug.field("span", &self.span);
792 debug.finish()
793 }
794}
795
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700796fn token_stream(mut input: Cursor) -> PResult<TokenStream> {
Alex Crichton1eb96a02018-04-04 13:07:35 -0700797 let mut trees = Vec::new();
798 loop {
799 let input_no_ws = skip_whitespace(input);
800 if input_no_ws.rest.len() == 0 {
David Tolnay48ea5042018-04-23 19:17:35 -0700801 break;
Alex Crichton1eb96a02018-04-04 13:07:35 -0700802 }
803 if let Ok((a, tokens)) = doc_comment(input_no_ws) {
804 input = a;
805 trees.extend(tokens);
David Tolnay48ea5042018-04-23 19:17:35 -0700806 continue;
Alex Crichton1eb96a02018-04-04 13:07:35 -0700807 }
808
809 let (a, tt) = match token_tree(input_no_ws) {
810 Ok(p) => p,
811 Err(_) => break,
812 };
813 trees.push(tt);
814 input = a;
815 }
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700816 Ok((input, TokenStream { inner: trees }))
Alex Crichton1eb96a02018-04-04 13:07:35 -0700817}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700818
David Tolnay3b1f7d22019-01-28 12:22:11 -0800819#[cfg(not(span_locations))]
Alex Crichton1eb96a02018-04-04 13:07:35 -0700820fn spanned<'a, T>(
821 input: Cursor<'a>,
822 f: fn(Cursor<'a>) -> PResult<'a, T>,
823) -> PResult<'a, (T, ::Span)> {
824 let (a, b) = f(skip_whitespace(input))?;
David Tolnay3b1f7d22019-01-28 12:22:11 -0800825 Ok((a, ((b, ::Span::_new_stable(Span::call_site())))))
David Tolnayddfca052017-12-31 10:41:24 -0500826}
827
David Tolnay3b1f7d22019-01-28 12:22:11 -0800828#[cfg(span_locations)]
Alex Crichton1eb96a02018-04-04 13:07:35 -0700829fn spanned<'a, T>(
830 input: Cursor<'a>,
831 f: fn(Cursor<'a>) -> PResult<'a, T>,
832) -> PResult<'a, (T, ::Span)> {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500833 let input = skip_whitespace(input);
834 let lo = input.off;
Alex Crichton1eb96a02018-04-04 13:07:35 -0700835 let (a, b) = f(input)?;
836 let hi = a.off;
David Tolnayf0814122019-07-19 11:53:55 -0700837 let span = ::Span::_new_stable(Span { lo, hi });
Alex Crichton1eb96a02018-04-04 13:07:35 -0700838 Ok((a, (b, span)))
839}
840
841fn token_tree(input: Cursor) -> PResult<TokenTree> {
842 let (rest, (mut tt, span)) = spanned(input, token_kind)?;
843 tt.set_span(span);
844 Ok((rest, tt))
Nika Layzellf8d5f212017-12-11 14:07:02 -0500845}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700846
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700847named!(token_kind -> TokenTree, alt!(
David Tolnayf14813f2018-09-08 17:14:07 -0700848 map!(group, |g| TokenTree::Group(::Group::_new_stable(g)))
Alex Crichton44bffbc2017-05-19 17:51:59 -0700849 |
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700850 map!(literal, |l| TokenTree::Literal(::Literal::_new_stable(l))) // must be before symbol
Alex Crichton44bffbc2017-05-19 17:51:59 -0700851 |
Alex Crichtonf3888432018-05-16 09:11:05 -0700852 map!(op, TokenTree::Punct)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700853 |
Alex Crichtonf3888432018-05-16 09:11:05 -0700854 symbol_leading_ws
Alex Crichton44bffbc2017-05-19 17:51:59 -0700855));
856
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700857named!(group -> Group, alt!(
Alex Crichton44bffbc2017-05-19 17:51:59 -0700858 delimited!(
859 punct!("("),
860 token_stream,
861 punct!(")")
David Tolnayf14813f2018-09-08 17:14:07 -0700862 ) => { |ts| Group::new(Delimiter::Parenthesis, ts) }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700863 |
864 delimited!(
865 punct!("["),
866 token_stream,
867 punct!("]")
David Tolnayf14813f2018-09-08 17:14:07 -0700868 ) => { |ts| Group::new(Delimiter::Bracket, ts) }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700869 |
870 delimited!(
871 punct!("{"),
872 token_stream,
873 punct!("}")
David Tolnayf14813f2018-09-08 17:14:07 -0700874 ) => { |ts| Group::new(Delimiter::Brace, ts) }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700875));
876
Alex Crichtonf3888432018-05-16 09:11:05 -0700877fn symbol_leading_ws(input: Cursor) -> PResult<TokenTree> {
878 symbol(skip_whitespace(input))
879}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700880
Alex Crichtonf3888432018-05-16 09:11:05 -0700881fn symbol(input: Cursor) -> PResult<TokenTree> {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700882 let mut chars = input.char_indices();
David Tolnaya202d502017-06-01 12:26:55 -0700883
Alex Crichtonf3888432018-05-16 09:11:05 -0700884 let raw = input.starts_with("r#");
David Tolnaya13d1422018-03-31 21:27:48 +0200885 if raw {
886 chars.next();
887 chars.next();
888 }
889
Alex Crichton44bffbc2017-05-19 17:51:59 -0700890 match chars.next() {
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000891 Some((_, ch)) if is_ident_start(ch) => {}
David Tolnay1218e122017-06-01 11:13:45 -0700892 _ => return Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -0700893 }
894
David Tolnay214c94c2017-06-01 12:42:56 -0700895 let mut end = input.len();
Alex Crichton44bffbc2017-05-19 17:51:59 -0700896 for (i, ch) in chars {
Nicholas Nethercotee3cb3532018-05-28 20:11:58 +1000897 if !is_ident_continue(ch) {
David Tolnay214c94c2017-06-01 12:42:56 -0700898 end = i;
899 break;
Alex Crichton44bffbc2017-05-19 17:51:59 -0700900 }
901 }
902
David Tolnaya13d1422018-03-31 21:27:48 +0200903 let a = &input.rest[..end];
Alex Crichtonf3888432018-05-16 09:11:05 -0700904 if a == "r#_" {
David Tolnay214c94c2017-06-01 12:42:56 -0700905 Err(LexError)
906 } else {
Alex Crichtonf3888432018-05-16 09:11:05 -0700907 let ident = if raw {
908 ::Ident::_new_raw(&a[2..], ::Span::call_site())
909 } else {
910 ::Ident::new(a, ::Span::call_site())
911 };
912 Ok((input.advance(end), ident.into()))
David Tolnay214c94c2017-06-01 12:42:56 -0700913 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700914}
915
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700916fn literal(input: Cursor) -> PResult<Literal> {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700917 let input_no_ws = skip_whitespace(input);
918
919 match literal_nocapture(input_no_ws) {
David Tolnay1218e122017-06-01 11:13:45 -0700920 Ok((a, ())) => {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700921 let start = input.len() - input_no_ws.len();
922 let len = input_no_ws.len() - a.len();
923 let end = start + len;
David Tolnay3d9d6ad2018-05-18 10:51:55 -0700924 Ok((a, Literal::_new(input.rest[start..end].to_string())))
Alex Crichton44bffbc2017-05-19 17:51:59 -0700925 }
David Tolnay1218e122017-06-01 11:13:45 -0700926 Err(LexError) => Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -0700927 }
928}
929
930named!(literal_nocapture -> (), alt!(
931 string
932 |
933 byte_string
934 |
935 byte
936 |
937 character
938 |
939 float
940 |
941 int
Alex Crichton44bffbc2017-05-19 17:51:59 -0700942));
943
944named!(string -> (), alt!(
945 quoted_string
946 |
947 preceded!(
948 punct!("r"),
949 raw_string
950 ) => { |_| () }
951));
952
953named!(quoted_string -> (), delimited!(
954 punct!("\""),
955 cooked_string,
956 tag!("\"")
957));
958
Nika Layzellf8d5f212017-12-11 14:07:02 -0500959fn cooked_string(input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -0700960 let mut chars = input.char_indices().peekable();
961 while let Some((byte_offset, ch)) = chars.next() {
962 match ch {
963 '"' => {
Nika Layzellf8d5f212017-12-11 14:07:02 -0500964 return Ok((input.advance(byte_offset), ()));
Alex Crichton44bffbc2017-05-19 17:51:59 -0700965 }
966 '\r' => {
967 if let Some((_, '\n')) = chars.next() {
968 // ...
969 } else {
970 break;
971 }
972 }
David Tolnayb28f38a2018-03-31 22:02:29 +0200973 '\\' => match chars.next() {
974 Some((_, 'x')) => {
975 if !backslash_x_char(&mut chars) {
976 break;
Alex Crichton44bffbc2017-05-19 17:51:59 -0700977 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700978 }
David Tolnayb28f38a2018-03-31 22:02:29 +0200979 Some((_, 'n')) | Some((_, 'r')) | Some((_, 't')) | Some((_, '\\'))
980 | Some((_, '\'')) | Some((_, '"')) | Some((_, '0')) => {}
981 Some((_, 'u')) => {
982 if !backslash_u(&mut chars) {
983 break;
984 }
985 }
986 Some((_, '\n')) | Some((_, '\r')) => {
987 while let Some(&(_, ch)) = chars.peek() {
988 if ch.is_whitespace() {
989 chars.next();
990 } else {
991 break;
992 }
993 }
994 }
995 _ => break,
996 },
Alex Crichton44bffbc2017-05-19 17:51:59 -0700997 _ch => {}
998 }
999 }
David Tolnay1218e122017-06-01 11:13:45 -07001000 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001001}
1002
1003named!(byte_string -> (), alt!(
1004 delimited!(
1005 punct!("b\""),
1006 cooked_byte_string,
1007 tag!("\"")
1008 ) => { |_| () }
1009 |
1010 preceded!(
1011 punct!("br"),
1012 raw_string
1013 ) => { |_| () }
1014));
1015
Nika Layzellf8d5f212017-12-11 14:07:02 -05001016fn cooked_byte_string(mut input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001017 let mut bytes = input.bytes().enumerate();
1018 'outer: while let Some((offset, b)) = bytes.next() {
1019 match b {
1020 b'"' => {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001021 return Ok((input.advance(offset), ()));
Alex Crichton44bffbc2017-05-19 17:51:59 -07001022 }
1023 b'\r' => {
1024 if let Some((_, b'\n')) = bytes.next() {
1025 // ...
1026 } else {
1027 break;
1028 }
1029 }
David Tolnayb28f38a2018-03-31 22:02:29 +02001030 b'\\' => match bytes.next() {
1031 Some((_, b'x')) => {
1032 if !backslash_x_byte(&mut bytes) {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001033 break;
1034 }
Alex Crichton44bffbc2017-05-19 17:51:59 -07001035 }
David Tolnayb28f38a2018-03-31 22:02:29 +02001036 Some((_, b'n')) | Some((_, b'r')) | Some((_, b't')) | Some((_, b'\\'))
1037 | Some((_, b'0')) | Some((_, b'\'')) | Some((_, b'"')) => {}
1038 Some((newline, b'\n')) | Some((newline, b'\r')) => {
1039 let rest = input.advance(newline + 1);
1040 for (offset, ch) in rest.char_indices() {
1041 if !ch.is_whitespace() {
1042 input = rest.advance(offset);
1043 bytes = input.bytes().enumerate();
1044 continue 'outer;
1045 }
1046 }
1047 break;
1048 }
1049 _ => break,
1050 },
Alex Crichton44bffbc2017-05-19 17:51:59 -07001051 b if b < 0x80 => {}
1052 _ => break,
1053 }
1054 }
David Tolnay1218e122017-06-01 11:13:45 -07001055 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001056}
1057
Nika Layzellf8d5f212017-12-11 14:07:02 -05001058fn raw_string(input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001059 let mut chars = input.char_indices();
1060 let mut n = 0;
1061 while let Some((byte_offset, ch)) = chars.next() {
1062 match ch {
1063 '"' => {
1064 n = byte_offset;
1065 break;
1066 }
1067 '#' => {}
David Tolnay1218e122017-06-01 11:13:45 -07001068 _ => return Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -07001069 }
1070 }
1071 for (byte_offset, ch) in chars {
1072 match ch {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001073 '"' if input.advance(byte_offset + 1).starts_with(&input.rest[..n]) => {
1074 let rest = input.advance(byte_offset + 1 + n);
David Tolnayb28f38a2018-03-31 22:02:29 +02001075 return Ok((rest, ()));
Alex Crichton44bffbc2017-05-19 17:51:59 -07001076 }
1077 '\r' => {}
1078 _ => {}
1079 }
1080 }
David Tolnay1218e122017-06-01 11:13:45 -07001081 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001082}
1083
1084named!(byte -> (), do_parse!(
1085 punct!("b") >>
1086 tag!("'") >>
1087 cooked_byte >>
1088 tag!("'") >>
1089 (())
1090));
1091
Nika Layzellf8d5f212017-12-11 14:07:02 -05001092fn cooked_byte(input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001093 let mut bytes = input.bytes().enumerate();
1094 let ok = match bytes.next().map(|(_, b)| b) {
David Tolnayb28f38a2018-03-31 22:02:29 +02001095 Some(b'\\') => match bytes.next().map(|(_, b)| b) {
1096 Some(b'x') => backslash_x_byte(&mut bytes),
1097 Some(b'n') | Some(b'r') | Some(b't') | Some(b'\\') | Some(b'0') | Some(b'\'')
1098 | Some(b'"') => true,
1099 _ => false,
1100 },
Alex Crichton44bffbc2017-05-19 17:51:59 -07001101 b => b.is_some(),
1102 };
1103 if ok {
1104 match bytes.next() {
Alex Crichton8c030332018-01-16 08:07:36 -08001105 Some((offset, _)) => {
1106 if input.chars().as_str().is_char_boundary(offset) {
1107 Ok((input.advance(offset), ()))
1108 } else {
1109 Err(LexError)
1110 }
1111 }
Nika Layzellf8d5f212017-12-11 14:07:02 -05001112 None => Ok((input.advance(input.len()), ())),
Alex Crichton44bffbc2017-05-19 17:51:59 -07001113 }
1114 } else {
David Tolnay1218e122017-06-01 11:13:45 -07001115 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001116 }
1117}
1118
1119named!(character -> (), do_parse!(
1120 punct!("'") >>
1121 cooked_char >>
1122 tag!("'") >>
1123 (())
1124));
1125
Nika Layzellf8d5f212017-12-11 14:07:02 -05001126fn cooked_char(input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001127 let mut chars = input.char_indices();
1128 let ok = match chars.next().map(|(_, ch)| ch) {
David Tolnayb28f38a2018-03-31 22:02:29 +02001129 Some('\\') => match chars.next().map(|(_, ch)| ch) {
1130 Some('x') => backslash_x_char(&mut chars),
1131 Some('u') => backslash_u(&mut chars),
1132 Some('n') | Some('r') | Some('t') | Some('\\') | Some('0') | Some('\'') | Some('"') => {
1133 true
Alex Crichton44bffbc2017-05-19 17:51:59 -07001134 }
David Tolnayb28f38a2018-03-31 22:02:29 +02001135 _ => false,
1136 },
Alex Crichton44bffbc2017-05-19 17:51:59 -07001137 ch => ch.is_some(),
1138 };
1139 if ok {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001140 match chars.next() {
1141 Some((idx, _)) => Ok((input.advance(idx), ())),
1142 None => Ok((input.advance(input.len()), ())),
1143 }
Alex Crichton44bffbc2017-05-19 17:51:59 -07001144 } else {
David Tolnay1218e122017-06-01 11:13:45 -07001145 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001146 }
1147}
1148
1149macro_rules! next_ch {
1150 ($chars:ident @ $pat:pat $(| $rest:pat)*) => {
1151 match $chars.next() {
1152 Some((_, ch)) => match ch {
1153 $pat $(| $rest)* => ch,
1154 _ => return false,
1155 },
1156 None => return false
1157 }
1158 };
1159}
1160
1161fn backslash_x_char<I>(chars: &mut I) -> bool
David Tolnayb28f38a2018-03-31 22:02:29 +02001162where
1163 I: Iterator<Item = (usize, char)>,
Alex Crichton44bffbc2017-05-19 17:51:59 -07001164{
1165 next_ch!(chars @ '0'...'7');
1166 next_ch!(chars @ '0'...'9' | 'a'...'f' | 'A'...'F');
1167 true
1168}
1169
1170fn backslash_x_byte<I>(chars: &mut I) -> bool
David Tolnayb28f38a2018-03-31 22:02:29 +02001171where
1172 I: Iterator<Item = (usize, u8)>,
Alex Crichton44bffbc2017-05-19 17:51:59 -07001173{
1174 next_ch!(chars @ b'0'...b'9' | b'a'...b'f' | b'A'...b'F');
1175 next_ch!(chars @ b'0'...b'9' | b'a'...b'f' | b'A'...b'F');
1176 true
1177}
1178
1179fn backslash_u<I>(chars: &mut I) -> bool
David Tolnayb28f38a2018-03-31 22:02:29 +02001180where
1181 I: Iterator<Item = (usize, char)>,
Alex Crichton44bffbc2017-05-19 17:51:59 -07001182{
1183 next_ch!(chars @ '{');
1184 next_ch!(chars @ '0'...'9' | 'a'...'f' | 'A'...'F');
David Tolnay8d109342017-12-25 18:24:45 -05001185 loop {
1186 let c = next_ch!(chars @ '0'...'9' | 'a'...'f' | 'A'...'F' | '_' | '}');
1187 if c == '}' {
1188 return true;
1189 }
Alex Crichton44bffbc2017-05-19 17:51:59 -07001190 }
Alex Crichton44bffbc2017-05-19 17:51:59 -07001191}
1192
Nika Layzellf8d5f212017-12-11 14:07:02 -05001193fn float(input: Cursor) -> PResult<()> {
David Tolnay744a6b82017-06-01 11:34:29 -07001194 let (rest, ()) = float_digits(input)?;
1195 for suffix in &["f32", "f64"] {
1196 if rest.starts_with(suffix) {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001197 return word_break(rest.advance(suffix.len()));
David Tolnay744a6b82017-06-01 11:34:29 -07001198 }
1199 }
1200 word_break(rest)
1201}
Alex Crichton44bffbc2017-05-19 17:51:59 -07001202
Nika Layzellf8d5f212017-12-11 14:07:02 -05001203fn float_digits(input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001204 let mut chars = input.chars().peekable();
1205 match chars.next() {
1206 Some(ch) if ch >= '0' && ch <= '9' => {}
David Tolnay1218e122017-06-01 11:13:45 -07001207 _ => return Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -07001208 }
1209
1210 let mut len = 1;
1211 let mut has_dot = false;
1212 let mut has_exp = false;
1213 while let Some(&ch) = chars.peek() {
1214 match ch {
1215 '0'...'9' | '_' => {
1216 chars.next();
1217 len += 1;
1218 }
1219 '.' => {
1220 if has_dot {
1221 break;
1222 }
1223 chars.next();
David Tolnayb28f38a2018-03-31 22:02:29 +02001224 if chars
1225 .peek()
1226 .map(|&ch| ch == '.' || UnicodeXID::is_xid_start(ch))
1227 .unwrap_or(false)
1228 {
David Tolnay1218e122017-06-01 11:13:45 -07001229 return Err(LexError);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001230 }
1231 len += 1;
1232 has_dot = true;
1233 }
1234 'e' | 'E' => {
1235 chars.next();
1236 len += 1;
1237 has_exp = true;
1238 break;
1239 }
1240 _ => break,
1241 }
1242 }
1243
Nika Layzellf8d5f212017-12-11 14:07:02 -05001244 let rest = input.advance(len);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001245 if !(has_dot || has_exp || rest.starts_with("f32") || rest.starts_with("f64")) {
David Tolnay1218e122017-06-01 11:13:45 -07001246 return Err(LexError);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001247 }
1248
1249 if has_exp {
1250 let mut has_exp_value = false;
1251 while let Some(&ch) = chars.peek() {
1252 match ch {
1253 '+' | '-' => {
1254 if has_exp_value {
1255 break;
1256 }
1257 chars.next();
1258 len += 1;
1259 }
1260 '0'...'9' => {
1261 chars.next();
1262 len += 1;
1263 has_exp_value = true;
1264 }
1265 '_' => {
1266 chars.next();
1267 len += 1;
1268 }
1269 _ => break,
1270 }
1271 }
1272 if !has_exp_value {
David Tolnay1218e122017-06-01 11:13:45 -07001273 return Err(LexError);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001274 }
1275 }
1276
Nika Layzellf8d5f212017-12-11 14:07:02 -05001277 Ok((input.advance(len), ()))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001278}
1279
Nika Layzellf8d5f212017-12-11 14:07:02 -05001280fn int(input: Cursor) -> PResult<()> {
David Tolnay744a6b82017-06-01 11:34:29 -07001281 let (rest, ()) = digits(input)?;
1282 for suffix in &[
David Tolnay48ea5042018-04-23 19:17:35 -07001283 "isize", "i8", "i16", "i32", "i64", "i128", "usize", "u8", "u16", "u32", "u64", "u128",
David Tolnay744a6b82017-06-01 11:34:29 -07001284 ] {
1285 if rest.starts_with(suffix) {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001286 return word_break(rest.advance(suffix.len()));
David Tolnay744a6b82017-06-01 11:34:29 -07001287 }
1288 }
1289 word_break(rest)
1290}
Alex Crichton44bffbc2017-05-19 17:51:59 -07001291
Nika Layzellf8d5f212017-12-11 14:07:02 -05001292fn digits(mut input: Cursor) -> PResult<()> {
Alex Crichton44bffbc2017-05-19 17:51:59 -07001293 let base = if input.starts_with("0x") {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001294 input = input.advance(2);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001295 16
1296 } else if input.starts_with("0o") {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001297 input = input.advance(2);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001298 8
1299 } else if input.starts_with("0b") {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001300 input = input.advance(2);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001301 2
1302 } else {
1303 10
1304 };
1305
Alex Crichton44bffbc2017-05-19 17:51:59 -07001306 let mut len = 0;
1307 let mut empty = true;
1308 for b in input.bytes() {
1309 let digit = match b {
1310 b'0'...b'9' => (b - b'0') as u64,
1311 b'a'...b'f' => 10 + (b - b'a') as u64,
1312 b'A'...b'F' => 10 + (b - b'A') as u64,
1313 b'_' => {
1314 if empty && base == 10 {
David Tolnay1218e122017-06-01 11:13:45 -07001315 return Err(LexError);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001316 }
1317 len += 1;
1318 continue;
1319 }
1320 _ => break,
1321 };
1322 if digit >= base {
David Tolnay1218e122017-06-01 11:13:45 -07001323 return Err(LexError);
Alex Crichton44bffbc2017-05-19 17:51:59 -07001324 }
Alex Crichton44bffbc2017-05-19 17:51:59 -07001325 len += 1;
1326 empty = false;
1327 }
1328 if empty {
David Tolnay1218e122017-06-01 11:13:45 -07001329 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001330 } else {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001331 Ok((input.advance(len), ()))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001332 }
1333}
1334
Alex Crichtonf3888432018-05-16 09:11:05 -07001335fn op(input: Cursor) -> PResult<Punct> {
David Tolnayea75c5f2017-05-31 23:40:33 -07001336 let input = skip_whitespace(input);
1337 match op_char(input) {
Alex Crichtonf3888432018-05-16 09:11:05 -07001338 Ok((rest, '\'')) => {
1339 symbol(rest)?;
1340 Ok((rest, Punct::new('\'', Spacing::Joint)))
1341 }
David Tolnay1218e122017-06-01 11:13:45 -07001342 Ok((rest, ch)) => {
David Tolnayea75c5f2017-05-31 23:40:33 -07001343 let kind = match op_char(rest) {
Alex Crichton1a7f7622017-07-05 17:47:15 -07001344 Ok(_) => Spacing::Joint,
1345 Err(LexError) => Spacing::Alone,
David Tolnayea75c5f2017-05-31 23:40:33 -07001346 };
Alex Crichtonf3888432018-05-16 09:11:05 -07001347 Ok((rest, Punct::new(ch, kind)))
David Tolnayea75c5f2017-05-31 23:40:33 -07001348 }
David Tolnay1218e122017-06-01 11:13:45 -07001349 Err(LexError) => Err(LexError),
Alex Crichton44bffbc2017-05-19 17:51:59 -07001350 }
1351}
1352
Nika Layzellf8d5f212017-12-11 14:07:02 -05001353fn op_char(input: Cursor) -> PResult<char> {
David Tolnay3a592ad2018-04-22 21:20:24 -07001354 if input.starts_with("//") || input.starts_with("/*") {
1355 // Do not accept `/` of a comment as an op.
1356 return Err(LexError);
1357 }
1358
David Tolnayea75c5f2017-05-31 23:40:33 -07001359 let mut chars = input.chars();
1360 let first = match chars.next() {
1361 Some(ch) => ch,
1362 None => {
David Tolnay1218e122017-06-01 11:13:45 -07001363 return Err(LexError);
David Tolnayea75c5f2017-05-31 23:40:33 -07001364 }
1365 };
Alex Crichtonf3888432018-05-16 09:11:05 -07001366 let recognized = "~!@#$%^&*-=+|;:,<.>/?'";
David Tolnayea75c5f2017-05-31 23:40:33 -07001367 if recognized.contains(first) {
Nika Layzellf8d5f212017-12-11 14:07:02 -05001368 Ok((input.advance(first.len_utf8()), first))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001369 } else {
David Tolnay1218e122017-06-01 11:13:45 -07001370 Err(LexError)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001371 }
1372}
1373
Alex Crichton1eb96a02018-04-04 13:07:35 -07001374fn doc_comment(input: Cursor) -> PResult<Vec<TokenTree>> {
1375 let mut trees = Vec::new();
1376 let (rest, ((comment, inner), span)) = spanned(input, doc_comment_contents)?;
Alex Crichtonf3888432018-05-16 09:11:05 -07001377 trees.push(TokenTree::Punct(Punct::new('#', Spacing::Alone)));
Alex Crichton1eb96a02018-04-04 13:07:35 -07001378 if inner {
Alex Crichtonf3888432018-05-16 09:11:05 -07001379 trees.push(Punct::new('!', Spacing::Alone).into());
Alex Crichton1eb96a02018-04-04 13:07:35 -07001380 }
1381 let mut stream = vec![
Alex Crichtonf3888432018-05-16 09:11:05 -07001382 TokenTree::Ident(::Ident::new("doc", span)),
1383 TokenTree::Punct(Punct::new('=', Spacing::Alone)),
Alex Crichton1eb96a02018-04-04 13:07:35 -07001384 TokenTree::Literal(::Literal::string(comment)),
1385 ];
1386 for tt in stream.iter_mut() {
1387 tt.set_span(span);
1388 }
David Tolnayf14813f2018-09-08 17:14:07 -07001389 let group = Group::new(Delimiter::Bracket, stream.into_iter().collect());
1390 trees.push(::Group::_new_stable(group).into());
Alex Crichton1eb96a02018-04-04 13:07:35 -07001391 for tt in trees.iter_mut() {
1392 tt.set_span(span);
1393 }
1394 Ok((rest, trees))
1395}
1396
1397named!(doc_comment_contents -> (&str, bool), alt!(
Alex Crichton44bffbc2017-05-19 17:51:59 -07001398 do_parse!(
1399 punct!("//!") >>
Alex Crichton1eb96a02018-04-04 13:07:35 -07001400 s: take_until_newline_or_eof!() >>
1401 ((s, true))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001402 )
1403 |
1404 do_parse!(
1405 option!(whitespace) >>
1406 peek!(tag!("/*!")) >>
Alex Crichton1eb96a02018-04-04 13:07:35 -07001407 s: block_comment >>
1408 ((s, true))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001409 )
1410 |
1411 do_parse!(
1412 punct!("///") >>
1413 not!(tag!("/")) >>
Alex Crichton1eb96a02018-04-04 13:07:35 -07001414 s: take_until_newline_or_eof!() >>
1415 ((s, false))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001416 )
1417 |
1418 do_parse!(
1419 option!(whitespace) >>
1420 peek!(tuple!(tag!("/**"), not!(tag!("*")))) >>
Alex Crichton1eb96a02018-04-04 13:07:35 -07001421 s: block_comment >>
1422 ((s, false))
Alex Crichton44bffbc2017-05-19 17:51:59 -07001423 )
1424));