From aaf941dbda39029b036f3a9390fe4d3525105774 Mon Sep 17 00:00:00 2001 From: Martin Rueckl Date: Thu, 18 Jan 2024 16:34:58 +0100 Subject: [PATCH] [wast] make constructor of Id public (#1369) --- crates/wast/src/token.rs | 30 +++++++++++++++++++++++++----- 1 file changed, 25 insertions(+), 5 deletions(-) diff --git a/crates/wast/src/token.rs b/crates/wast/src/token.rs index fef4c73062..9dd15f97a8 100644 --- a/crates/wast/src/token.rs +++ b/crates/wast/src/token.rs @@ -2,9 +2,9 @@ //! associated specifically with the wasm text format per se (useful in other //! contexts too perhaps). -use crate::annotation; -use crate::lexer::Float; +use crate::lexer::{Float, Lexer, TokenKind}; use crate::parser::{Cursor, Parse, Parser, Peek, Result}; +use crate::{annotation, Error}; use std::fmt; use std::hash::{Hash, Hasher}; use std::str; @@ -58,8 +58,21 @@ pub struct Id<'a> { } impl<'a> Id<'a> { - fn new(name: &'a str, span: Span) -> Id<'a> { - Id { name, gen: 0, span } + /// Construct a new identifier from given string. + /// + /// Returns an error if the string does not contain a leading `$`, or is not a + /// valid WASM text format identifier. + pub fn new(name: &'a str, span: Span) -> Result> { + let mut _pos: usize = 0; + let tok = Lexer::new(name).parse(&mut _pos)?; + match tok { + Some(tok) if tok.kind == TokenKind::Id => Ok(Id { + name: tok.id(name), + gen: 0, + span, + }), + _ => Err(Error::parse(span, name, "expected an identifier".into())), + } } pub(crate) fn gensym(span: Span, gen: u32) -> Id<'a> { @@ -106,7 +119,14 @@ impl<'a> Parse<'a> for Id<'a> { fn parse(parser: Parser<'a>) -> Result { parser.step(|c| { if let Some((name, rest)) = c.id()? { - return Ok((Id::new(name, c.cur_span()), rest)); + return Ok(( + Id { + name, + gen: 0, + span: c.cur_span(), + }, + rest, + )); } Err(c.error("expected an identifier")) })