Merge pull request #55 from ryangjchandler/feature/global-statement

This commit is contained in:
Ryan Chandler 2022-09-13 00:47:52 +01:00 committed by GitHub
commit 980b1c1d9c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 39 additions and 0 deletions

View File

@ -828,6 +828,7 @@ impl Lexer {
#[allow(dead_code)]
fn identifier_to_keyword(ident: &str) -> Option<TokenKind> {
Some(match ident {
"global" => TokenKind::Global,
"match" => TokenKind::Match,
"abstract" => TokenKind::Abstract,
"array" => TokenKind::Array,

View File

@ -9,6 +9,7 @@ pub enum OpenTagKind {
#[derive(Debug, PartialEq, Clone)]
pub enum TokenKind {
Global,
Abstract,
Ampersand,
And,
@ -300,6 +301,7 @@ impl Display for TokenKind {
Self::Variable(var) => &var[..],
Self::Yield => "yield",
Self::While => "while",
Self::Global => "global",
_ => todo!("format token: {:?}", self),
}
)

View File

@ -297,6 +297,9 @@ pub enum Statement {
Block {
body: Block,
},
Global {
vars: Vec<Identifier>,
},
Noop,
}

View File

@ -169,6 +169,19 @@ impl Parser {
self.skip_comments();
let statement = match &self.current.kind {
TokenKind::Global => {
self.next();
let mut vars = vec![];
while self.current.kind != TokenKind::SemiColon {
vars.push(self.var()?.into());
self.optional_comma()?;
}
self.semi()?;
Statement::Global { vars }
}
TokenKind::Static if matches!(self.peek.kind, TokenKind::Variable(_)) => {
self.next();
@ -3305,6 +3318,26 @@ mod tests {
);
}
#[test]
fn global_statements() {
assert_ast(
"<?php global $a;",
&[Statement::Global {
vars: vec!["a".into()],
}],
);
}
#[test]
fn multiple_global_vars_in_statement() {
assert_ast(
"<?php global $a, $b;",
&[Statement::Global {
vars: vec!["a".into(), "b".into()],
}],
);
}
fn assert_ast(source: &str, expected: &[Statement]) {
let mut lexer = Lexer::new(None);
let tokens = lexer.tokenize(source).unwrap();