Skip to content

Feat switch case #172

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/ast.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
mod arg;
mod case;
mod const_expr;
mod costume;
mod enum_;
Expand All @@ -24,6 +25,7 @@ mod value;
mod var;

pub use arg::*;
pub use case::*;
pub use const_expr::*;
pub use costume::*;
pub use enum_::*;
Expand Down
17 changes: 17 additions & 0 deletions src/ast/case.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
use logos::Span;
use serde::{
Deserialize,
Serialize,
};

use crate::ast::{
Expr,
Stmt,
};

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Case {
pub value: Box<Expr>,
pub body: Vec<Stmt>,
pub span: Span,
}
14 changes: 14 additions & 0 deletions src/ast/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,3 +130,17 @@ impl From<ConstExpr> for Expr {
}
}
}

impl PartialEq for Expr {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
// Simple expressions that can be compared
(Expr::Value { value: v1, .. }, Expr::Value { value: v2, .. }) => v1 == v2,
(Expr::Name(n1), Expr::Name(n2)) => n1 == n2,
(Expr::Arg(n1), Expr::Arg(n2)) => n1 == n2,

// Complex expressions always return false
_ => false,
}
}
}
23 changes: 23 additions & 0 deletions src/ast/name.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,3 +66,26 @@ impl Name {
}
}
}

impl PartialEq for Name {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Name::Name { name: name1, .. }, Name::Name { name: name2, .. }) => name1 == name2,
(
Name::DotName {
lhs: lhs1,
rhs: rhs1,
..
},
Name::DotName {
lhs: lhs2,
rhs: rhs2,
..
},
) => lhs1 == lhs2 && rhs1 == rhs2,
_ => false,
}
}
}

impl Eq for Name {}
9 changes: 8 additions & 1 deletion src/ast/stmt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,15 @@ use super::{
Value,
};
use crate::{
ast::Case,
blocks::{
BinOp,
Block,
},
misc::SmolStr,
};

#[derive(Debug, Serialize, Deserialize)]
#[derive(Debug, Serialize, Deserialize, Clone)]
pub enum Stmt {
Repeat {
times: Box<Expr>,
Expand Down Expand Up @@ -92,6 +93,11 @@ pub enum Stmt {
value: Box<Expr>,
visited: bool,
},
Switch {
value: Box<Expr>,
cases: Vec<Case>,
span: Span,
},
}

impl Stmt {
Expand All @@ -114,6 +120,7 @@ impl Stmt {
Stmt::ProcCall { span, .. } => span.clone(),
Stmt::FuncCall { span, .. } => span.clone(),
Stmt::Return { value, .. } => value.span(),
Stmt::Switch { span, .. } => span.clone(),
}
}

Expand Down
19 changes: 19 additions & 0 deletions src/ast/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -192,3 +192,22 @@ pub enum ListIndex {
Index(usize),
All,
}

impl PartialEq for Value {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Value::Boolean(a), Value::Boolean(b)) => a == b,
(Value::Number(a), Value::Number(b)) => {
// Handle NaN case - NaN != NaN in IEEE 754
if a.is_nan() && b.is_nan() {
true
} else {
a == b
}
}
(Value::String(a), Value::String(b)) => a == b,
// Different variants are not equal
_ => false,
}
}
}
2 changes: 2 additions & 0 deletions src/codegen/sb3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,7 @@ impl Stmt {
Stmt::ProcCall { .. } => "procedures_call",
Stmt::FuncCall { .. } => "procedures_call",
Stmt::Return { .. } => "data_setvariableto",
Stmt::Switch { .. } => "",
}
}
}
Expand Down Expand Up @@ -1302,6 +1303,7 @@ where T: Write + Seek
args,
),
Stmt::Return { .. } => panic!(),
Stmt::Switch { .. } => unreachable!(),
}
}

Expand Down
5 changes: 5 additions & 0 deletions src/diagnostic/diagnostic_kind.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ pub enum DiagnosticKind {
field_name: SmolStr,
},
EmptyStruct(SmolStr),
DuplicateSwitchCasePattern,
// Warnings
FollowedByUnreachableCode,
UnrecognizedKey(SmolStr),
Expand Down Expand Up @@ -221,6 +222,9 @@ impl DiagnosticKind {
format!("struct {struct_name} is missing field {field_name}")
}
DiagnosticKind::EmptyStruct(name) => format!("struct {name} is empty"),
DiagnosticKind::DuplicateSwitchCasePattern => {
"duplicate switch case pattern".to_string()
}
}
}

Expand Down Expand Up @@ -377,6 +381,7 @@ impl From<&DiagnosticKind> for Level {
| DiagnosticKind::MissingField { .. }
| DiagnosticKind::StructDoesNotHaveField { .. }
| DiagnosticKind::EmptyStruct(_)
| DiagnosticKind::DuplicateSwitchCasePattern
| DiagnosticKind::InvalidCostumeName(_)
| DiagnosticKind::InvalidBackdropName(_) => Level::Error,

Expand Down
6 changes: 6 additions & 0 deletions src/lexer/token.rs
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,10 @@ pub enum Token {
Enum,
#[token("struct")]
Struct,
#[token("switch")]
Switch,
#[token("case")]
Case,
#[token("true")]
True,
#[token("false")]
Expand Down Expand Up @@ -342,6 +346,8 @@ impl Display for Token {
Token::As => write!(f, "as"),
Token::Enum => write!(f, "enum"),
Token::Struct => write!(f, "struct"),
Token::Switch => write!(f, "switch"),
Token::Case => write!(f, "case"),
Token::True => write!(f, "true"),
Token::False => write!(f, "false"),
Token::List => write!(f, "list"),
Expand Down
15 changes: 15 additions & 0 deletions src/parser/grammar.lalrpop
Original file line number Diff line number Diff line change
Expand Up @@ -348,6 +348,19 @@ Stmt: Stmt = {
<l:@L> SET_ROTATION_STYLE_LEFT_RIGHT <r:@R> ";" => Stmt::Block { block: Block::SetRotationStyleLeftRight, span: l..r, args: vec![], kwargs: Default::default() },
<l:@L> SET_ROTATION_STYLE_ALL_AROUND <r:@R> ";" => Stmt::Block { block: Block::SetRotationStyleAllAround, span: l..r, args: vec![], kwargs: Default::default() },
<l:@L> SET_ROTATION_STYLE_DO_NOT_ROTATE <r:@R> ";" => Stmt::Block { block: Block::SetRotationStyleDoNotRotate, span: l..r, args: vec![], kwargs: Default::default() },
<l:@L> SWITCH <r:@R> <value:BoxedIfExpr> "{" <cases:Case*> "}" => Stmt::Switch {
value,
cases,
span: l..r
}
}

Case: Case = {
<l:@L> CASE <value:BoxedIfExpr> <r:@R> <body:Stmts> => Case {
value,
body,
span: l..r
}
}

Elif: Stmt = {
Expand Down Expand Up @@ -708,5 +721,7 @@ extern {
SET_ROTATION_STYLE_DO_NOT_ROTATE => Token::SetRotationStyleDoNotRotate,
SET_LAYER_ORDER => Token::SetLayerOrder,
VAR => Token::Var,
SWITCH => Token::Switch,
CASE => Token::Case,
}
}
1 change: 1 addition & 0 deletions src/visitor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ pub mod pass1;
pub mod pass2;
pub mod pass3;
pub mod pass4;
mod switchcase;
mod transformations;
11 changes: 11 additions & 0 deletions src/visitor/pass1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,17 @@ fn visit_stmt(stmt: &mut Stmt, s: &mut S) -> Vec<Stmt> {
}
}
}
Stmt::Switch {
value,
cases,
span: _,
} => {
visit_expr(value, &mut before, s);
for case in cases {
visit_expr(&mut case.value, &mut before, s);
visit_stmts(&mut case.body, s);
}
}
}
if let Some(replace) = replace {
*stmt = replace;
Expand Down
13 changes: 13 additions & 0 deletions src/visitor/pass2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ use crate::{
SpriteDiagnostics,
},
misc::SmolStr,
visitor::switchcase::switchcase,
};

#[derive(Copy, Clone)]
Expand Down Expand Up @@ -193,6 +194,7 @@ fn visit_stmts(stmts: &mut Vec<Stmt>, s: S, d: D, top_level: bool) {
visit_stmt_return(value)
}
}
Stmt::Switch { value, cases, span } => Some(vec![switchcase(value, cases, span, d)]),
_ => None,
};
if let Some(replace) = replace {
Expand Down Expand Up @@ -309,6 +311,17 @@ fn visit_stmt(stmt: &mut Stmt, s: S, d: D) {
}
}
Stmt::Return { value, .. } => visit_expr(value, s, d),
Stmt::Switch {
value,
cases,
span: _,
} => {
visit_expr(value, s, d);
for case in cases {
visit_expr(&mut case.value, s, d);
visit_stmts(&mut case.body, s, d, false);
}
}
}
}

Expand Down
11 changes: 11 additions & 0 deletions src/visitor/pass3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,17 @@ fn visit_stmt(stmt: &Stmt, s: &mut S) {
value: _,
visited: _,
} => {}
Stmt::Switch {
value,
cases,
span: _,
} => {
visit_expr(value, s);
for case in cases {
visit_expr(&case.value, s);
visit_stmts(&case.body, s);
}
}
}
}

Expand Down
Loading