#![deny(missing_docs)]
#![cfg_attr(docsrs, feature(doc_cfg))]
use std::borrow::Cow;
use std::fmt;
use std::path::{Path, PathBuf};
use std::str;
use wast::core::EncodeOptions;
use wast::lexer::{Lexer, TokenKind};
use wast::parser::{self, ParseBuffer};
#[doc(inline)]
pub use wast::core::GenerateDwarf;
pub fn parse_file(file: impl AsRef<Path>) -> Result<Vec<u8>> {
Parser::new().parse_file(file)
}
pub fn parse_bytes(bytes: &[u8]) -> Result<Cow<'_, [u8]>> {
Parser::new().parse_bytes(None, bytes)
}
pub fn parse_str(wat: impl AsRef<str>) -> Result<Vec<u8>> {
Parser::default().parse_str(None, wat)
}
#[derive(Default)]
pub struct Parser {
#[cfg(feature = "dwarf")]
generate_dwarf: Option<GenerateDwarf>,
_private: (),
}
impl Parser {
pub fn new() -> Parser {
Parser::default()
}
#[cfg(feature = "dwarf")]
pub fn generate_dwarf(&mut self, generate: GenerateDwarf) -> &mut Self {
self.generate_dwarf = Some(generate);
self
}
pub fn parse_file(&self, path: impl AsRef<Path>) -> Result<Vec<u8>> {
self._parse_file(path.as_ref())
}
fn _parse_file(&self, file: &Path) -> Result<Vec<u8>> {
let contents = std::fs::read(file).map_err(|err| Error {
kind: Box::new(ErrorKind::Io {
err,
file: Some(file.to_owned()),
}),
})?;
match self.parse_bytes(Some(file), &contents) {
Ok(Cow::Borrowed(bytes)) => {
assert_eq!(bytes.len(), contents.len());
assert_eq!(bytes.as_ptr(), contents.as_ptr());
Ok(contents)
}
Ok(Cow::Owned(bytes)) => Ok(bytes),
Err(mut e) => {
e.set_path(file);
Err(e)
}
}
}
pub fn parse_bytes<'a>(&self, path: Option<&Path>, bytes: &'a [u8]) -> Result<Cow<'a, [u8]>> {
if bytes.starts_with(b"\0asm") {
return Ok(bytes.into());
}
match str::from_utf8(bytes) {
Ok(s) => self._parse_str(path, s).map(|s| s.into()),
Err(_) => Err(Error {
kind: Box::new(ErrorKind::Custom {
msg: "input bytes aren't valid utf-8".to_string(),
file: path.map(|p| p.to_owned()),
}),
}),
}
}
pub fn parse_str(&self, path: Option<&Path>, wat: impl AsRef<str>) -> Result<Vec<u8>> {
self._parse_str(path, wat.as_ref())
}
fn _parse_str(&self, path: Option<&Path>, wat: &str) -> Result<Vec<u8>> {
let mut _buf = ParseBuffer::new(wat).map_err(|e| Error::cvt(e, wat, path))?;
#[cfg(feature = "dwarf")]
_buf.track_instr_spans(self.generate_dwarf.is_some());
let mut ast = parser::parse::<wast::Wat>(&_buf).map_err(|e| Error::cvt(e, wat, path))?;
let mut _opts = EncodeOptions::default();
#[cfg(feature = "dwarf")]
if let Some(style) = self.generate_dwarf {
_opts.dwarf(path.unwrap_or("<input>.wat".as_ref()), wat, style);
}
_opts
.encode_wat(&mut ast)
.map_err(|e| Error::cvt(e, wat, path))
}
}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum Detect {
WasmText,
WasmBinary,
Unknown,
}
impl Detect {
pub fn from_bytes(bytes: impl AsRef<[u8]>) -> Detect {
if bytes.as_ref().starts_with(b"\0asm") {
return Detect::WasmBinary;
}
let text = match std::str::from_utf8(bytes.as_ref()) {
Ok(s) => s,
Err(_) => return Detect::Unknown,
};
let lexer = Lexer::new(text);
let mut iter = lexer.iter(0);
while let Some(next) = iter.next() {
match next.map(|t| t.kind) {
Ok(TokenKind::Whitespace)
| Ok(TokenKind::BlockComment)
| Ok(TokenKind::LineComment) => {}
Ok(TokenKind::LParen) => return Detect::WasmText,
_ => break,
}
}
Detect::Unknown
}
pub fn is_wasm(&self) -> bool {
match self {
Detect::WasmText | Detect::WasmBinary => true,
Detect::Unknown => false,
}
}
}
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug)]
pub struct Error {
kind: Box<ErrorKind>,
}
#[derive(Debug)]
enum ErrorKind {
Wast(wast::Error),
Io {
err: std::io::Error,
file: Option<PathBuf>,
},
Custom {
msg: String,
file: Option<PathBuf>,
},
}
impl Error {
fn cvt<E: Into<wast::Error>>(e: E, contents: &str, path: Option<&Path>) -> Error {
let mut err = e.into();
if let Some(path) = path {
err.set_path(path);
}
err.set_text(contents);
Error {
kind: Box::new(ErrorKind::Wast(err)),
}
}
pub fn set_path<P: AsRef<Path>>(&mut self, file: P) {
let file = file.as_ref();
match &mut *self.kind {
ErrorKind::Wast(e) => e.set_path(file),
ErrorKind::Custom { file: f, .. } => *f = Some(file.to_owned()),
ErrorKind::Io { file: f, .. } => *f = Some(file.to_owned()),
}
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &*self.kind {
ErrorKind::Wast(err) => err.fmt(f),
ErrorKind::Custom { msg, file, .. } => match file {
Some(file) => {
write!(f, "failed to parse `{}`: {}", file.display(), msg)
}
None => msg.fmt(f),
},
ErrorKind::Io { err, file, .. } => match file {
Some(file) => {
write!(f, "failed to read from `{}`", file.display())
}
None => err.fmt(f),
},
}
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &*self.kind {
ErrorKind::Wast(_) => None,
ErrorKind::Custom { .. } => None,
ErrorKind::Io { err, .. } => Some(err),
}
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_set_path() {
let mut e = parse_bytes(&[0xFF]).unwrap_err();
e.set_path("foo");
assert_eq!(
e.to_string(),
"failed to parse `foo`: input bytes aren't valid utf-8"
);
let e = parse_file("_does_not_exist_").unwrap_err();
assert!(
e.to_string()
.starts_with("failed to read from `_does_not_exist_`")
);
let mut e = parse_bytes("()".as_bytes()).unwrap_err();
e.set_path("foo");
assert_eq!(
e.to_string(),
"expected valid module field\n --> foo:1:2\n |\n 1 | ()\n | ^"
);
}
}