//! Common tokens that implement the [`Parse`] trait which are otherwise not //! associated specifically with the wasm text format per se (useful in other //! contexts too perhaps).
usecrate::annotation; usecrate::lexer::Float; usecrate::parser::{Cursor, Parse, Parser, Peek, Result}; use std::fmt; use std::hash::{Hash, Hasher}; use std::str;
/// A position in the original source stream, used to render errors. #[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq, Hash)] pubstruct Span { pub(crate) offset: usize,
}
impl Span { /// Construct a `Span` from a byte offset in the source file. pubfn from_offset(offset: usize) -> Self {
Span { offset }
}
/// Returns the line/column information of this span within `text`. /// Line and column numbers are 0-indexed. User presentation is typically /// 1-indexed, but 0-indexing is appropriate for internal use with /// iterators and slices. pubfn linecol_in(&self, text: &str) -> (usize, usize) { letmut cur = 0; // Use split_terminator instead of lines so that if there is a `\r`, // it is included in the offset calculation. The `+1` values below // account for the `\n`. for (i, line) in text.split_terminator('\n').enumerate() { if cur + line.len() + 1 > self.offset { return (i, self.offset - cur);
}
cur += line.len() + 1;
}
(text.lines().count(), 0)
}
/// Returns the byte offset of this span. pubfn offset(&self) -> usize { self.offset
}
}
/// An identifier in a WebAssembly module, prefixed by `$` in the textual /// format. /// /// An identifier is used to symbolically refer to items in a a wasm module, /// typically via the [`Index`] type. #[derive(Copy, Clone)] pubstruct Id<'a> {
name: &'a str, gen: u32,
span: Span,
}
impl<'a> Id<'a> { /// Construct a new identifier from given string. /// /// Note that `name` can be any arbitrary string according to the /// WebAssembly/annotations proposal. pubfn new(name: &'a str, span: Span) -> Id<'a> {
Id { name, gen: 0, span }
}
/// Returns the underlying name of this identifier. /// /// The name returned does not contain the leading `$`. pubfn name(&self) -> &'a str { self.name
}
/// Returns span of this identifier in the original source pubfn span(&self) -> Span { self.span
}
/// A reference to another item in a wasm module. /// /// This type is used for items referring to other items (such as `call $foo` /// referencing function `$foo`). References can be either an index (u32) or an /// [`Id`] in the textual format. /// /// The emission phase of a module will ensure that `Index::Id` is never used /// and switch them all to `Index::Num`. #[derive(Copy, Clone, Debug)] pubenum Index<'a> { /// A numerical index that this references. The index space this is /// referencing is implicit based on where this [`Index`] is stored.
Num(u32, Span), /// A human-readable identifier this references. Like `Num`, the namespace /// this references is based on where this is stored.
Id(Id<'a>),
}
impl Index<'_> { /// Returns the source location where this `Index` was defined. pubfn span(&self) -> Span { matchself {
Index::Num(_, span) => *span,
Index::Id(id) => id.span(),
}
}
/// An `@name` annotation in source, currently of the form `@name "foo"` #[derive(Copy, Clone, PartialEq, Eq, Debug)] pubstruct NameAnnotation<'a> { /// The name specified for the item pub name: &'a str,
}
impl<'a> Parse<'a> for NameAnnotation<'a> { fn parse(parser: Parser<'a>) -> Result<Self> {
parser.parse::<annotation::name>()?; let name = parser.parse()?;
Ok(NameAnnotation { name })
}
}
macro_rules! float {
($($name:ident => {
bits: $int:ident,
float: $float:ident,
exponent_bits: $exp_bits:tt,
name: $parse:ident,
})*) => ($( /// A parsed floating-point type #[derive(Debug, Copy, Clone)] pubstruct $name { /// The raw bits that this floating point number represents. pub bits: $int,
}
impl<'a> Parse<'a> for $name { fn parse(parser: Parser<'a>) -> Result<Self> {
parser.step(|c| { let (val, rest) = iflet Some((f, rest)) = c.float()? {
($parse(&f), rest)
} elseiflet Some((i, rest)) = c.integer()? { let (s, base) = i.val();
(
$parse(&Float::Val {
hex: base == 16,
integral: s.into(),
decimal: None,
exponent: None,
}),
rest,
)
} else { return Err(c.error("expected a float"));
}; match val {
Some(bits) => Ok(($name { bits }, rest)),
None => Err(c.error("invalid float value: constant out of range")),
}
})
}
}
fn $parse(val: &Float<'_>) -> Option<$int> { // Compute a few well-known constants about the float representation // given the parameters to the macro here. let width = std::mem::size_of::<$int>() * 8; let neg_offset = width - 1; let exp_offset = neg_offset - $exp_bits; let signif_bits = width - 1 - $exp_bits; let signif_mask = (1 << exp_offset) - 1; let bias = (1 << ($exp_bits - 1)) - 1;
let (hex, integral, decimal, exponent_str) = match val { // Infinity is when the exponent bits are all set and // the significand is zero.
Float::Inf { negative } => { let exp_bits = (1 << $exp_bits) - 1; let neg_bit = *negative as $int; return Some(
(neg_bit << neg_offset) |
(exp_bits << exp_offset)
);
}
// NaN is when the exponent bits are all set and // the significand is nonzero. The default of NaN is // when only the highest bit of the significand is set.
Float::Nan { negative, val } => { let exp_bits = (1 << $exp_bits) - 1; let neg_bit = *negative as $int; let signif = match val {
Some(val) => $int::from_str_radix(val,16).ok()?,
None => 1 << (signif_bits - 1),
}; // If the significand is zero then this is actually infinity // so we fail to parse it. if signif & signif_mask == 0 { return None;
} return Some(
(neg_bit << neg_offset) |
(exp_bits << exp_offset) |
(signif & signif_mask)
);
}
// This is trickier, handle this below
Float::Val { hex, integral, decimal, exponent } => {
(hex, integral, decimal, exponent)
}
};
// Rely on Rust's standard library to parse base 10 floats // correctly. if !*hex { letmut s = integral.to_string(); iflet Some(decimal) = decimal {
s.push_str(".");
s.push_str(&decimal);
} iflet Some(exponent) = exponent_str {
s.push_str("e");
s.push_str(&exponent);
} let float = s.parse::<$float>().ok()?; // looks like the `*.wat` format considers infinite overflow to // be invalid. if float.is_infinite() { return None;
} return Some(float.to_bits());
}
// Parsing hex floats is... hard! I don't really know what most of // this below does. It was copied from Gecko's implementation in // `WasmTextToBinary.cpp`. Would love comments on this if you have // them! let decimal = decimal.as_ref().map(|s| &**s).unwrap_or(""); let negative = integral.starts_with('-'); let integral = integral.trim_start_matches('-').trim_start_matches('0');
// Do a bunch of work up front to locate the first non-zero digit // to determine the initial exponent. There's a number of // adjustments depending on where the digit was found, but the // general idea here is that I'm not really sure why things are // calculated the way they are but it should match Gecko. let decimal_no_leading = decimal.trim_start_matches('0'); let decimal_iter = if integral.is_empty() {
decimal_no_leading.chars()
} else {
decimal.chars()
}; letmut digits = integral.chars()
.map(|c| (to_hex(c) as $int, false))
.chain(decimal_iter.map(|c| (to_hex(c) as $int, true))); let lead_nonzero_digit = match digits.next() {
Some((c, _)) => c, // No digits? Must be `+0` or `-0`, being careful to handle the // sign encoding here.
None if negative => return Some(1 << (width - 1)),
None => return Some(0),
}; letmut significand = 0as $int; letmut exponent = if !integral.is_empty() { 1
} else {
-((decimal.len() - decimal_no_leading.len() + 1) as i32) + 1
}; let lz = (lead_nonzero_digit as u8).leading_zeros() as i32 - 4;
exponent = exponent.checked_mul(4)?.checked_sub(lz + 1)?; letmut significand_pos = (width - (4 - (lz as usize))) as isize;
assert!(significand_pos >= 0);
significand |= lead_nonzero_digit << significand_pos;
// Now that we've got an anchor in the string we parse the remaining // digits. Again, not entirely sure why everything is the way it is // here! This is copied frmo gecko. letmut discarded_extra_nonzero = false; for (digit, decimal) in digits { if !decimal {
exponent += 4;
} if significand_pos > -4 {
significand_pos -= 4;
}
let (encoded_exponent, encoded_significand, discarded_significand) = if exponent <= -bias { // Underflow to subnormal or zero. let shift = exp_offset as i32 + exponent + bias; if shift == 0 {
(0, 0, significand)
} elseif shift < 0 || shift >= width as i32 {
(0, 0, 0)
} else {
( 0,
significand >> (width as i32 - shift),
significand << shift,
)
}
} elseif exponent <= bias { // Normal (non-zero). The significand's leading 1 is encoded // implicitly.
(
((exponent + bias) as $int) << exp_offset,
(significand >> (width - exp_offset - 1)) & signif_mask,
significand << (exp_offset + 1),
)
} else { // Overflow to infinity.
(
((1 << $exp_bits) - 1) << exp_offset, 0, 0,
)
};
let bits = encoded_exponent | encoded_significand;
// Apply rounding. If this overflows the significand, it carries // into the exponent bit according to the magic of the IEEE 754 // encoding. // // Or rather, the comment above is what Gecko says so it's copied // here too. let msb = 1 << (width - 1); let bits = bits
+ (((discarded_significand & msb != 0)
&& ((discarded_significand & !msb != 0) ||
discarded_extra_nonzero || // ties to even
(encoded_significand & 1 != 0))) as $int);
// Just before we return the bits be sure to handle the sign bit we // found at the beginning. let bits = if negative {
bits | (1 << (width - 1))
} else {
bits
}; // looks like the `*.wat` format considers infinite overflow to // be invalid. if $float::from_bits(bits).is_infinite() { return None;
}
Some(bits)
}
fn to_hex(c: char) -> u8 { match c { 'a'..='f' => c as u8 - b'a' + 10, 'A'..='F' => c as u8 - b'A' + 10,
_ => c as u8 - b'0',
}
}
/// A convenience type to use with [`Parser::peek`](crate::parser::Parser::peek) /// to see if the next token is an s-expression. pubstruct LParen {
_priv: (),
}
/// A convenience type to use with [`Parser::peek`](crate::parser::Parser::peek) /// to see if the next token is the end of an s-expression. pubstruct RParen {
_priv: (),
}
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.