parser: add support for static scope variables

This commit is contained in:
Ryan Chandler 2022-08-10 00:21:24 +01:00
parent e7e4a361d5
commit f226316d44
No known key found for this signature in database
GPG Key ID: F113BCADDB3B0CCA
2 changed files with 33 additions and 1 deletions

View File

@ -131,9 +131,18 @@ pub enum UseKind {
Const, Const,
} }
#[derive(Debug, PartialEq, Clone, Serialize)]
pub struct StaticVar {
pub var: Expression,
pub default: Option<Expression>,
}
#[derive(Debug, PartialEq, Clone, Serialize)] #[derive(Debug, PartialEq, Clone, Serialize)]
pub enum Statement { pub enum Statement {
InlineHtml(String), InlineHtml(String),
Static {
vars: Vec<StaticVar>,
},
While { While {
condition: Expression, condition: Expression,
body: Block, body: Block,

View File

@ -1,6 +1,6 @@
use std::{vec::IntoIter, fmt::{Display}}; use std::{vec::IntoIter, fmt::{Display}};
use trunk_lexer::{Token, TokenKind, Span}; use trunk_lexer::{Token, TokenKind, Span};
use crate::{Program, Statement, Block, Expression, ast::{ArrayItem, Use, MethodFlag, ClassFlag, ElseIf, UseKind, MagicConst, BackedEnumType, ClosureUse, Arg}, Identifier, Type, MatchArm, Catch, Case}; use crate::{Program, Statement, Block, Expression, ast::{ArrayItem, Use, MethodFlag, ClassFlag, ElseIf, UseKind, MagicConst, BackedEnumType, ClosureUse, Arg, StaticVar}, Identifier, Type, MatchArm, Catch, Case};
type ParseResult<T> = Result<T, ParseError>; type ParseResult<T> = Result<T, ParseError>;
@ -136,6 +136,29 @@ impl Parser {
self.skip_comments(); self.skip_comments();
let statement = match &self.current.kind { let statement = match &self.current.kind {
TokenKind::Static if matches!(self.peek.kind, TokenKind::Variable(_)) => {
self.next();
let mut vars = vec![];
while self.current.kind != TokenKind::SemiColon {
let var = Expression::Variable { name: self.var()? };
let mut default = None;
if self.current.kind == TokenKind::Equals {
expect!(self, TokenKind::Equals, "expected =");
default = Some(self.expression(0)?);
}
self.optional_comma()?;
vars.push(StaticVar { var, default })
}
self.semi()?;
Statement::Static { vars }
},
TokenKind::InlineHtml(html) => { TokenKind::InlineHtml(html) => {
let s = Statement::InlineHtml(html.to_string()); let s = Statement::InlineHtml(html.to_string());
self.next(); self.next();