Skip to content

Commit aaf941d

Browse files
authored
[wast] make constructor of Id public (#1369)
1 parent c998356 commit aaf941d

File tree

1 file changed

+25
-5
lines changed

1 file changed

+25
-5
lines changed

crates/wast/src/token.rs

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@
22
//! associated specifically with the wasm text format per se (useful in other
33
//! contexts too perhaps).
44
5-
use crate::annotation;
6-
use crate::lexer::Float;
5+
use crate::lexer::{Float, Lexer, TokenKind};
76
use crate::parser::{Cursor, Parse, Parser, Peek, Result};
7+
use crate::{annotation, Error};
88
use std::fmt;
99
use std::hash::{Hash, Hasher};
1010
use std::str;
@@ -58,8 +58,21 @@ pub struct Id<'a> {
5858
}
5959

6060
impl<'a> Id<'a> {
61-
fn new(name: &'a str, span: Span) -> Id<'a> {
62-
Id { name, gen: 0, span }
61+
/// Construct a new identifier from given string.
62+
///
63+
/// Returns an error if the string does not contain a leading `$`, or is not a
64+
/// valid WASM text format identifier.
65+
pub fn new(name: &'a str, span: Span) -> Result<Id<'a>> {
66+
let mut _pos: usize = 0;
67+
let tok = Lexer::new(name).parse(&mut _pos)?;
68+
match tok {
69+
Some(tok) if tok.kind == TokenKind::Id => Ok(Id {
70+
name: tok.id(name),
71+
gen: 0,
72+
span,
73+
}),
74+
_ => Err(Error::parse(span, name, "expected an identifier".into())),
75+
}
6376
}
6477

6578
pub(crate) fn gensym(span: Span, gen: u32) -> Id<'a> {
@@ -106,7 +119,14 @@ impl<'a> Parse<'a> for Id<'a> {
106119
fn parse(parser: Parser<'a>) -> Result<Self> {
107120
parser.step(|c| {
108121
if let Some((name, rest)) = c.id()? {
109-
return Ok((Id::new(name, c.cur_span()), rest));
122+
return Ok((
123+
Id {
124+
name,
125+
gen: 0,
126+
span: c.cur_span(),
127+
},
128+
rest,
129+
));
110130
}
111131
Err(c.error("expected an identifier"))
112132
})

0 commit comments

Comments
 (0)