Debian Codegraph @

third_party/rust/wast/src/token.rs

raw
1 //! Common tokens that implement the [`Parse`] trait which are otherwise not
2 //! associated specifically with the wasm text format per se (useful in other
3 //! contexts too perhaps).
4
5 use crate::annotation;
6 use crate::lexer::Float;
7 use crate::parser::{Cursor, Parse, Parser, Peek, Result};
8 use std::fmt;
9 use std::hash::{Hash, Hasher};
10 use std::str;
11
12 /// A position in the original source stream, used to render errors.
13 #[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq, Hash)]
14 pub struct Span {
15 pub(crate) offset: usize,
16 }
17
18 impl Span {
19 /// Construct a `Span` from a byte offset in the source file.
20 pub fn from_offset(offset: usize) -> Self {
21 Span { offset }
22 }
23
24 /// Returns the line/column information of this span within `text`.
25 /// Line and column numbers are 0-indexed. User presentation is typically
26 /// 1-indexed, but 0-indexing is appropriate for internal use with
27 /// iterators and slices.
28 pub fn linecol_in(&self, text: &str) -> (usize, usize) {
29 let mut cur = 0;
30 // Use split_terminator instead of lines so that if there is a `\r`,
31 // it is included in the offset calculation. The `+1` values below
32 // account for the `\n`.
33 for (i, line) in text.split_terminator('\n').enumerate() {
34 if cur + line.len() + 1 > self.offset {
35 return (i, self.offset - cur);
36 }
37 cur += line.len() + 1;
38 }
39 (text.lines().count(), 0)
40 }
41
42 /// Returns the byte offset of this span.
43 pub fn offset(&self) -> usize {
44 self.offset
45 }
46 }
47
48 /// An identifier in a WebAssembly module, prefixed by `$` in the textual
49 /// format.
50 ///
51 /// An identifier is used to symbolically refer to items in a a wasm module,
52 /// typically via the [`Index`] type.
53 #[derive(Copy, Clone)]
54 pub struct Id<'a> {
55 name: &'a str,
56 gen: u32,
57 span: Span,
58 }
59
60 impl<'a> Id<'a> {
61 /// Construct a new identifier from given string.
62 ///
63 /// Note that `name` can be any arbitrary string according to the
64 /// WebAssembly/annotations proposal.
65 pub fn new(name: &'a str, span: Span) -> Id<'a> {
66 Id { name, gen: 0, span }
67 }
68
69 #[cfg(feature = "wasm-module")]
70 pub(crate) fn gensym(span: Span, gen: u32) -> Id<'a> {
71 Id {
72 name: "gensym",
73 gen,
74 span,
75 }
76 }
77
78 /// Returns the underlying name of this identifier.
79 ///
80 /// The name returned does not contain the leading `$`.
81 pub fn name(&self) -> &'a str {
82 self.name
83 }
84
85 /// Returns span of this identifier in the original source
86 pub fn span(&self) -> Span {
87 self.span
88 }
89
90 #[cfg(feature = "wasm-module")]
91 pub(crate) fn is_gensym(&self) -> bool {
92 self.gen != 0
93 }
94 }
95
96 impl<'a> Hash for Id<'a> {
97 fn hash<H: Hasher>(&self, hasher: &mut H) {
98 self.name.hash(hasher);
99 self.gen.hash(hasher);
100 }
101 }
102
103 impl<'a> PartialEq for Id<'a> {
104 fn eq(&self, other: &Id<'a>) -> bool {
105 self.name == other.name && self.gen == other.gen
106 }
107 }
108
109 impl<'a> Eq for Id<'a> {}
110
111 impl<'a> Parse<'a> for Id<'a> {
112 fn parse(parser: Parser<'a>) -> Result<Self> {
113 parser.step(|c| {
114 if let Some((name, rest)) = c.id()? {
115 return Ok((
116 Id {
117 name,
118 gen: 0,
119 span: c.cur_span(),
120 },
121 rest,
122 ));
123 }
124 Err(c.error("expected an identifier"))
125 })
126 }
127 }
128
129 impl fmt::Debug for Id<'_> {
130 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
131 if self.gen != 0 {
132 f.debug_struct("Id").field("gen", &self.gen).finish()
133 } else {
134 self.name.fmt(f)
135 }
136 }
137 }
138
139 impl Peek for Id<'_> {
140 fn peek(cursor: Cursor<'_>) -> Result<bool> {
141 cursor.peek_id()
142 }
143
144 fn display() -> &'static str {
145 "an identifier"
146 }
147 }
148
149 /// A reference to another item in a wasm module.
150 ///
151 /// This type is used for items referring to other items (such as `call $foo`
152 /// referencing function `$foo`). References can be either an index (u32) or an
153 /// [`Id`] in the textual format.
154 ///
155 /// The emission phase of a module will ensure that `Index::Id` is never used
156 /// and switch them all to `Index::Num`.
157 #[derive(Copy, Clone, Debug)]
158 pub enum Index<'a> {
159 /// A numerical index that this references. The index space this is
160 /// referencing is implicit based on where this [`Index`] is stored.
161 Num(u32, Span),
162 /// A human-readable identifier this references. Like `Num`, the namespace
163 /// this references is based on where this is stored.
164 Id(Id<'a>),
165 }
166
167 impl Index<'_> {
168 /// Returns the source location where this `Index` was defined.
169 pub fn span(&self) -> Span {
170 match self {
171 Index::Num(_, span) => *span,
172 Index::Id(id) => id.span(),
173 }
174 }
175
176 #[cfg(feature = "wasm-module")]
177 pub(crate) fn is_resolved(&self) -> bool {
178 matches!(self, Index::Num(..))
179 }
180 }
181
182 impl<'a> Parse<'a> for Index<'a> {
183 fn parse(parser: Parser<'a>) -> Result<Self> {
184 if parser.peek::<Id>()? {
185 Ok(Index::Id(parser.parse()?))
186 } else if parser.peek::<u32>()? {
187 let (val, span) = parser.parse()?;
188 Ok(Index::Num(val, span))
189 } else {
190 Err(parser.error(format!(
191 "unexpected token, expected an index or an identifier"
192 )))
193 }
194 }
195 }
196
197 impl Peek for Index<'_> {
198 fn peek(cursor: Cursor<'_>) -> Result<bool> {
199 Ok(u32::peek(cursor)? || Id::peek(cursor)?)
200 }
201
202 fn display() -> &'static str {
203 "an index"
204 }
205 }
206
207 impl<'a> From<Id<'a>> for Index<'a> {
208 fn from(id: Id<'a>) -> Index<'a> {
209 Index::Id(id)
210 }
211 }
212
213 impl PartialEq for Index<'_> {
214 fn eq(&self, other: &Index<'_>) -> bool {
215 match (self, other) {
216 (Index::Num(a, _), Index::Num(b, _)) => a == b,
217 (Index::Id(a), Index::Id(b)) => a == b,
218 _ => false,
219 }
220 }
221 }
222
223 impl Eq for Index<'_> {}
224
225 impl Hash for Index<'_> {
226 fn hash<H: Hasher>(&self, hasher: &mut H) {
227 match self {
228 Index::Num(a, _) => {
229 0u8.hash(hasher);
230 a.hash(hasher);
231 }
232 Index::Id(a) => {
233 1u8.hash(hasher);
234 a.hash(hasher);
235 }
236 }
237 }
238 }
239
240 /// Parses `(func $foo)`
241 #[derive(Clone, Debug)]
242 #[allow(missing_docs)]
243 pub struct ItemRef<'a, K> {
244 pub kind: K,
245 pub idx: Index<'a>,
246 }
247
248 impl<'a, K: Parse<'a>> Parse<'a> for ItemRef<'a, K> {
249 fn parse(parser: Parser<'a>) -> Result<Self> {
250 parser.parens(|parser| {
251 let kind = parser.parse::<K>()?;
252 let idx = parser.parse()?;
253 Ok(ItemRef { kind, idx })
254 })
255 }
256 }
257
258 impl<'a, K: Peek> Peek for ItemRef<'a, K> {
259 fn peek(cursor: Cursor<'_>) -> Result<bool> {
260 match cursor.lparen()? {
261 Some(remaining) => K::peek(remaining),
262 None => Ok(false),
263 }
264 }
265
266 fn display() -> &'static str {
267 "an item reference"
268 }
269 }
270
271 /// An `@name` annotation in source, currently of the form `@name "foo"`
272 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
273 pub struct NameAnnotation<'a> {
274 /// The name specified for the item
275 pub name: &'a str,
276 }
277
278 impl<'a> Parse<'a> for NameAnnotation<'a> {
279 fn parse(parser: Parser<'a>) -> Result<Self> {
280 parser.parse::<annotation::name>()?;
281 let name = parser.parse()?;
282 Ok(NameAnnotation { name })
283 }
284 }
285
286 impl<'a> Parse<'a> for Option<NameAnnotation<'a>> {
287 fn parse(parser: Parser<'a>) -> Result<Self> {
288 Ok(if parser.peek2::<annotation::name>()? {
289 Some(parser.parens(|p| p.parse())?)
290 } else {
291 None
292 })
293 }
294 }
295
296 macro_rules! integers {
297 ($($i:ident($u:ident))*) => ($(
298 impl<'a> Parse<'a> for $i {
299 fn parse(parser: Parser<'a>) -> Result<Self> {
300 Ok(parser.parse::<($i, Span)>()?.0)
301 }
302 }
303
304 impl<'a> Parse<'a> for ($i, Span) {
305 fn parse(parser: Parser<'a>) -> Result<Self> {
306 parser.step(|c| {
307 if let Some((i, rest)) = c.integer()? {
308 let (s, base) = i.val();
309 let val = $i::from_str_radix(s, base)
310 .or_else(|_| {
311 $u::from_str_radix(s, base).map(|i| i as $i)
312 });
313 return match val {
314 Ok(n) => Ok(((n, c.cur_span()), rest)),
315 Err(_) => Err(c.error(concat!(
316 "invalid ",
317 stringify!($i),
318 " number: constant out of range",
319 ))),
320 };
321 }
322 Err(c.error(concat!("expected a ", stringify!($i))))
323 })
324 }
325 }
326
327 impl Peek for $i {
328 fn peek(cursor: Cursor<'_>) -> Result<bool> {
329 cursor.peek_integer()
330 }
331
332 fn display() -> &'static str {
333 stringify!($i)
334 }
335 }
336 )*)
337 }
338
339 integers! {
340 u8(u8) u16(u16) u32(u32) u64(u64)
341 i8(u8) i16(u16) i32(u32) i64(u64)
342 }
343
344 impl<'a> Parse<'a> for &'a [u8] {
345 fn parse(parser: Parser<'a>) -> Result<Self> {
346 parser.step(|c| {
347 if let Some((i, rest)) = c.string()? {
348 return Ok((i, rest));
349 }
350 Err(c.error("expected a string"))
351 })
352 }
353 }
354
355 impl Peek for &'_ [u8] {
356 fn peek(cursor: Cursor<'_>) -> Result<bool> {
357 cursor.peek_string()
358 }
359
360 fn display() -> &'static str {
361 "string"
362 }
363 }
364
365 impl<'a> Parse<'a> for &'a str {
366 fn parse(parser: Parser<'a>) -> Result<Self> {
367 str::from_utf8(parser.parse()?)
368 .map_err(|_| parser.error_at(parser.prev_span(), "malformed UTF-8 encoding"))
369 }
370 }
371
372 impl Parse<'_> for String {
373 fn parse(parser: Parser<'_>) -> Result<Self> {
374 Ok(<&str>::parse(parser)?.to_string())
375 }
376 }
377
378 impl Peek for &'_ str {
379 fn peek(cursor: Cursor<'_>) -> Result<bool> {
380 <&[u8]>::peek(cursor)
381 }
382
383 fn display() -> &'static str {
384 <&[u8]>::display()
385 }
386 }
387
388 macro_rules! float {
389 ($($name:ident => {
390 bits: $int:ident,
391 float: $float:ident,
392 exponent_bits: $exp_bits:tt,
393 name: $parse:ident,
394 })*) => ($(
395 /// A parsed floating-point type
396 #[derive(Debug, Copy, Clone)]
397 pub struct $name {
398 /// The raw bits that this floating point number represents.
399 pub bits: $int,
400 }
401
402 impl<'a> Parse<'a> for $name {
403 fn parse(parser: Parser<'a>) -> Result<Self> {
404 parser.step(|c| {
405 let (val, rest) = if let Some((f, rest)) = c.float()? {
406 ($parse(&f), rest)
407 } else if let Some((i, rest)) = c.integer()? {
408 let (s, base) = i.val();
409 (
410 $parse(&Float::Val {
411 hex: base == 16,
412 integral: s.into(),
413 decimal: None,
414 exponent: None,
415 }),
416 rest,
417 )
418 } else {
419 return Err(c.error("expected a float"));
420 };
421 match val {
422 Some(bits) => Ok(($name { bits }, rest)),
423 None => Err(c.error("invalid float value: constant out of range")),
424 }
425 })
426 }
427 }
428
429 fn $parse(val: &Float<'_>) -> Option<$int> {
430 // Compute a few well-known constants about the float representation
431 // given the parameters to the macro here.
432 let width = std::mem::size_of::<$int>() * 8;
433 let neg_offset = width - 1;
434 let exp_offset = neg_offset - $exp_bits;
435 let signif_bits = width - 1 - $exp_bits;
436 let signif_mask = (1 << exp_offset) - 1;
437 let bias = (1 << ($exp_bits - 1)) - 1;
438
439 let (hex, integral, decimal, exponent_str) = match val {
440 // Infinity is when the exponent bits are all set and
441 // the significand is zero.
442 Float::Inf { negative } => {
443 let exp_bits = (1 << $exp_bits) - 1;
444 let neg_bit = *negative as $int;
445 return Some(
446 (neg_bit << neg_offset) |
447 (exp_bits << exp_offset)
448 );
449 }
450
451 // NaN is when the exponent bits are all set and
452 // the significand is nonzero. The default of NaN is
453 // when only the highest bit of the significand is set.
454 Float::Nan { negative, val } => {
455 let exp_bits = (1 << $exp_bits) - 1;
456 let neg_bit = *negative as $int;
457 let signif = match val {
458 Some(val) => $int::from_str_radix(val,16).ok()?,
459 None => 1 << (signif_bits - 1),
460 };
461 // If the significand is zero then this is actually infinity
462 // so we fail to parse it.
463 if signif & signif_mask == 0 {
464 return None;
465 }
466 return Some(
467 (neg_bit << neg_offset) |
468 (exp_bits << exp_offset) |
469 (signif & signif_mask)
470 );
471 }
472
473 // This is trickier, handle this below
474 Float::Val { hex, integral, decimal, exponent } => {
475 (hex, integral, decimal, exponent)
476 }
477 };
478
479 // Rely on Rust's standard library to parse base 10 floats
480 // correctly.
481 if !*hex {
482 let mut s = integral.to_string();
483 if let Some(decimal) = decimal {
484 s.push_str(".");
485 s.push_str(&decimal);
486 }
487 if let Some(exponent) = exponent_str {
488 s.push_str("e");
489 s.push_str(&exponent);
490 }
491 let float = s.parse::<$float>().ok()?;
492 // looks like the `*.wat` format considers infinite overflow to
493 // be invalid.
494 if float.is_infinite() {
495 return None;
496 }
497 return Some(float.to_bits());
498 }
499
500 // Parsing hex floats is... hard! I don't really know what most of
501 // this below does. It was copied from Gecko's implementation in
502 // `WasmTextToBinary.cpp`. Would love comments on this if you have
503 // them!
504 let decimal = decimal.as_ref().map(|s| &**s).unwrap_or("");
505 let negative = integral.starts_with('-');
506 let integral = integral.trim_start_matches('-').trim_start_matches('0');
507
508 // Do a bunch of work up front to locate the first non-zero digit
509 // to determine the initial exponent. There's a number of
510 // adjustments depending on where the digit was found, but the
511 // general idea here is that I'm not really sure why things are
512 // calculated the way they are but it should match Gecko.
513 let decimal_no_leading = decimal.trim_start_matches('0');
514 let decimal_iter = if integral.is_empty() {
515 decimal_no_leading.chars()
516 } else {
517 decimal.chars()
518 };
519 let mut digits = integral.chars()
520 .map(|c| (to_hex(c) as $int, false))
521 .chain(decimal_iter.map(|c| (to_hex(c) as $int, true)));
522 let lead_nonzero_digit = match digits.next() {
523 Some((c, _)) => c,
524 // No digits? Must be `+0` or `-0`, being careful to handle the
525 // sign encoding here.
526 None if negative => return Some(1 << (width - 1)),
527 None => return Some(0),
528 };
529 let mut significand = 0 as $int;
530 let mut exponent = if !integral.is_empty() {
531 1
532 } else {
533 -((decimal.len() - decimal_no_leading.len() + 1) as i32) + 1
534 };
535 let lz = (lead_nonzero_digit as u8).leading_zeros() as i32 - 4;
536 exponent = exponent.checked_mul(4)?.checked_sub(lz + 1)?;
537 let mut significand_pos = (width - (4 - (lz as usize))) as isize;
538 assert!(significand_pos >= 0);
539 significand |= lead_nonzero_digit << significand_pos;
540
541 // Now that we've got an anchor in the string we parse the remaining
542 // digits. Again, not entirely sure why everything is the way it is
543 // here! This is copied frmo gecko.
544 let mut discarded_extra_nonzero = false;
545 for (digit, decimal) in digits {
546 if !decimal {
547 exponent += 4;
548 }
549 if significand_pos > -4 {
550 significand_pos -= 4;
551 }
552
553 if significand_pos >= 0 {
554 significand |= digit << significand_pos;
555 } else if significand_pos > -4 {
556 significand |= digit >> (4 - significand_pos);
557 discarded_extra_nonzero = (digit & !((!0) >> (4 - significand_pos))) != 0;
558 } else if digit != 0 {
559 discarded_extra_nonzero = true;
560 }
561 }
562
563 exponent = exponent.checked_add(match exponent_str {
564 Some(s) => s.parse::<i32>().ok()?,
565 None => 0,
566 })?;
567 debug_assert!(significand != 0);
568
569 let (encoded_exponent, encoded_significand, discarded_significand) =
570 if exponent <= -bias {
571 // Underflow to subnormal or zero.
572 let shift = exp_offset as i32 + exponent + bias;
573 if shift == 0 {
574 (0, 0, significand)
575 } else if shift < 0 || shift >= width as i32 {
576 (0, 0, 0)
577 } else {
578 (
579 0,
580 significand >> (width as i32 - shift),
581 significand << shift,
582 )
583 }
584 } else if exponent <= bias {
585 // Normal (non-zero). The significand's leading 1 is encoded
586 // implicitly.
587 (
588 ((exponent + bias) as $int) << exp_offset,
589 (significand >> (width - exp_offset - 1)) & signif_mask,
590 significand << (exp_offset + 1),
591 )
592 } else {
593 // Overflow to infinity.
594 (
595 ((1 << $exp_bits) - 1) << exp_offset,
596 0,
597 0,
598 )
599 };
600
601 let bits = encoded_exponent | encoded_significand;
602
603 // Apply rounding. If this overflows the significand, it carries
604 // into the exponent bit according to the magic of the IEEE 754
605 // encoding.
606 //
607 // Or rather, the comment above is what Gecko says so it's copied
608 // here too.
609 let msb = 1 << (width - 1);
610 let bits = bits
611 + (((discarded_significand & msb != 0)
612 && ((discarded_significand & !msb != 0) ||
613 discarded_extra_nonzero ||
614 // ties to even
615 (encoded_significand & 1 != 0))) as $int);
616
617 // Just before we return the bits be sure to handle the sign bit we
618 // found at the beginning.
619 let bits = if negative {
620 bits | (1 << (width - 1))
621 } else {
622 bits
623 };
624 // looks like the `*.wat` format considers infinite overflow to
625 // be invalid.
626 if $float::from_bits(bits).is_infinite() {
627 return None;
628 }
629 Some(bits)
630 }
631
632 )*)
633 }
634
635 float! {
636 F32 => {
637 bits: u32,
638 float: f32,
639 exponent_bits: 8,
640 name: strtof,
641 }
642 F64 => {
643 bits: u64,
644 float: f64,
645 exponent_bits: 11,
646 name: strtod,
647 }
648 }
649
650 fn to_hex(c: char) -> u8 {
651 match c {
652 'a'..='f' => c as u8 - b'a' + 10,
653 'A'..='F' => c as u8 - b'A' + 10,
654 _ => c as u8 - b'0',
655 }
656 }
657
658 /// A convenience type to use with [`Parser::peek`](crate::parser::Parser::peek)
659 /// to see if the next token is an s-expression.
660 pub struct LParen {
661 _priv: (),
662 }
663
664 impl Peek for LParen {
665 fn peek(cursor: Cursor<'_>) -> Result<bool> {
666 cursor.peek_lparen()
667 }
668
669 fn display() -> &'static str {
670 "left paren"
671 }
672 }
673
674 /// A convenience type to use with [`Parser::peek`](crate::parser::Parser::peek)
675 /// to see if the next token is the end of an s-expression.
676 pub struct RParen {
677 _priv: (),
678 }
679
680 impl Peek for RParen {
681 fn peek(cursor: Cursor<'_>) -> Result<bool> {
682 cursor.peek_rparen()
683 }
684
685 fn display() -> &'static str {
686 "right paren"
687 }
688 }
689
690 #[cfg(test)]
691 mod tests {
692 #[test]
693 fn hex_strtof() {
694 macro_rules! f {
695 ($a:tt) => (f!(@mk $a, None, None));
696 ($a:tt p $e:tt) => (f!(@mk $a, None, Some($e.into())));
697 ($a:tt . $b:tt) => (f!(@mk $a, Some($b.into()), None));
698 ($a:tt . $b:tt p $e:tt) => (f!(@mk $a, Some($b.into()), Some($e.into())));
699 (@mk $a:tt, $b:expr, $e:expr) => (crate::lexer::Float::Val {
700 hex: true,
701 integral: $a.into(),
702 decimal: $b,
703 exponent: $e
704 });
705 }
706 assert_eq!(super::strtof(&f!("0")), Some(0));
707 assert_eq!(super::strtof(&f!("0" . "0")), Some(0));
708 assert_eq!(super::strtof(&f!("0" . "0" p "2354")), Some(0));
709 assert_eq!(super::strtof(&f!("-0")), Some(1 << 31));
710 assert_eq!(super::strtof(&f!("f32")), Some(0x45732000));
711 assert_eq!(super::strtof(&f!("0" . "f32")), Some(0x3f732000));
712 assert_eq!(super::strtof(&f!("1" . "2")), Some(0x3f900000));
713 assert_eq!(
714 super::strtof(&f!("0" . "00000100000000000" p "-126")),
715 Some(0)
716 );
717 assert_eq!(
718 super::strtof(&f!("1" . "fffff4" p "-106")),
719 Some(0x0afffffa)
720 );
721 assert_eq!(super::strtof(&f!("fffff98" p "-133")), Some(0x0afffffa));
722 assert_eq!(super::strtof(&f!("0" . "081" p "023")), Some(0x48810000));
723 assert_eq!(
724 super::strtof(&f!("1" . "00000100000000000" p "-50")),
725 Some(0x26800000)
726 );
727 }
728 }