refactor: abstract string part parsing

This commit is contained in:
Ryan Chandler 2022-12-04 09:24:34 +00:00
parent 6e13626ac7
commit 79a9b07b3c
No known key found for this signature in database
GPG Key ID: F113BCADDB3B0CCA

View File

@ -967,6 +967,7 @@ impl Parser {
e
}
TokenKind::StringPart(_) => self.interpolated_string(state)?,
TokenKind::StartHeredoc(_) => self.interpolated_string(state)?,
TokenKind::True => {
let e = Expression::Bool { value: true };
state.next();
@ -1477,12 +1478,27 @@ impl Parser {
let mut parts = Vec::new();
while state.current.kind != TokenKind::DoubleQuote {
match &state.current.kind {
TokenKind::StringPart(s) => {
if s.len() > 0 {
parts.push(StringPart::Const(s.clone()));
if let Some(part) = self.interpolated_string_part(state)? {
parts.push(part);
}
}
state.next();
Ok(Expression::InterpolatedString { parts })
}
fn interpolated_string_part(&self, state: &mut State) -> ParseResult<Option<StringPart>> {
Ok(match &state.current.kind {
TokenKind::StringPart(s) => {
let part = if s.len() > 0 {
Some(StringPart::Const(s.clone()))
} else {
None
};
state.next();
part
}
TokenKind::DollarLeftBrace => {
state.next();
@ -1515,14 +1531,14 @@ impl Parser {
Expression::DynamicVariable { name: Box::new(e) }
}
};
parts.push(StringPart::Expr(Box::new(e)));
Some(StringPart::Expr(Box::new(e)))
}
TokenKind::LeftBrace => {
// "{$expr}"
state.next();
let e = self.expression(state, Precedence::Lowest)?;
expect_token!([TokenKind::RightBrace], state, "`}`");
parts.push(StringPart::Expr(Box::new(e)));
Some(StringPart::Expr(Box::new(e)))
}
TokenKind::Variable(var) => {
// "$expr", "$expr[0]", "$expr[name]", "$expr->a"
@ -1595,17 +1611,12 @@ impl Parser {
}
_ => var,
};
parts.push(StringPart::Expr(Box::new(e)));
Some(StringPart::Expr(Box::new(e)))
}
_ => {
return expected_token_err!(["`${`", "`{$", "`\"`", "a variable"], state);
}
}
}
state.next();
Ok(Expression::InterpolatedString { parts })
})
}
}