Skip to content

Add "for each" loop and c-style for loop #76

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
Binary file added docs/assets/for.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/assets/foreach.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
20 changes: 20 additions & 0 deletions docs/language/control-flow.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,26 @@ until condition == true {

![](../assets/until.png){width="200"}

## for each loop

```goboscript
for x in n {
# code
}
```

![](../assets/foreach.png){width="200"}

## for loop

```goboscript
for x = 0; x > n; x++ {
# code
}
```

![](../assets/for.png){width="100"}

## forever loop

```goboscript
Expand Down
2 changes: 1 addition & 1 deletion editors/code/syntaxes/goboscript.tmGrammar.yml
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ patterns:
- name: keyword
match: "\\b(costumes|sounds|global|list|nowarp|onflag|onkey|onbackdrop|onloudness|ontimer|on|onclone)\\b"
- name: keyword.control
match: "\\b(if|else|elif|until|forever|repeat|delete|at|add|to|insert|true|false|as|struct|enum|return)\\b"
match: "\\b(if|else|elif|until|for|forever|repeat|delete|at|add|to|insert|true|false|as|struct|enum|return)\\b"
- name: keyword
match: "\\b(error|warn|breakpoint|local|not|and|or|in|length|round|abs|floor|ceil|sqrt|sin|cos|tan|asin|acos|atan|ln|log|antiln|antilog)\\b"
- name: support.function.builtin
Expand Down
2 changes: 1 addition & 1 deletion editors/notepad++/goboscript.udl.xml
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
<Keywords name="Folders in comment, open"></Keywords>
<Keywords name="Folders in comment, middle"></Keywords>
<Keywords name="Folders in comment, close"></Keywords>
<Keywords name="Keywords1">costumes sounds local proc func return nowarp if else elif until forever repeat list cloud struct enum</Keywords>
<Keywords name="Keywords1">costumes sounds local proc func return nowarp if else elif until for forever repeat list cloud struct enum</Keywords>
<Keywords name="Keywords2">%define&#x000D;&#x000A;%if&#x000D;&#x000A;%else&#x000D;&#x000A;%endif&#x000D;&#x000A;%include&#x000D;&#x000A;%undef</Keywords>
<Keywords name="Keywords3">true false</Keywords>
<Keywords name="Keywords4">$</Keywords>
Expand Down
2 changes: 1 addition & 1 deletion editors/sublime/goboscript.sublime-syntax
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ contexts:
match: "\\b(costumes|sounds|global|variables|lists|nowarp|onflag|onkey|onbackdrop|onloudness|ontimer|on|onclone)\\b"

- scope: keyword.control
match: "\\b(if|else|elif|until|forever|repeat|delete|at|add|to|insert)\\b"
match: "\\b(if|else|elif|until|for|forever|repeat|delete|at|add|to|insert)\\b"

- scope: keyword
match: "\\b(error|warn|breakpoint|local|not|and|or|in|length|round|abs|floor|ceil|sqrt|sin|cos|tan|asin|acos|atan|ln|log|antiln|antilog)\\b"
Expand Down
13 changes: 13 additions & 0 deletions src/ast/stmt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,19 @@ pub enum Stmt {
times: Box<Expr>,
body: Vec<Stmt>,
},
ForEach {
name: Name,
times: Box<Expr>,
body: Vec<Stmt>,
},
For {
name: Name,
value: Box<Expr>,
type_: Type,
cond: Box<Expr>,
incr: Box<Stmt>,
body: Vec<Stmt>,
},
Forever {
body: Vec<Stmt>,
span: Span,
Expand Down
26 changes: 24 additions & 2 deletions src/codegen/sb3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,8 @@ impl Stmt {
fn opcode(&self, s: S) -> &'static str {
match self {
Stmt::Repeat { .. } => "control_repeat",
Stmt::ForEach { .. } => "control_for_each",
Stmt::For { .. } => "control_repeat_until",
Stmt::Forever { .. } => "control_forever",
Stmt::Branch { else_body, .. } => {
if else_body.is_empty() {
Expand Down Expand Up @@ -965,18 +967,20 @@ where T: Write + Seek
self.stmts(s, d, &event.body, next_id, Some(this_id))
}

pub fn stmts(
pub fn stmts_with_next(
&mut self,
s: S,
d: D,
stmts: &[Stmt],
mut this_id: NodeID,
last_id: Option<NodeID>,
mut parent_id: Option<NodeID>,
) -> io::Result<()> {
for (i, stmt) in stmts.iter().enumerate() {
let is_last = i == stmts.len() - 1;
if is_last || stmt.is_terminator() {
self.stmt(s, d, stmt, this_id, None, parent_id)?;
let next_id = last_id;
self.stmt(s, d, stmt, this_id, next_id, parent_id)?;
if !is_last {
d.report(DiagnosticKind::FollowedByUnreachableCode, stmt.span());
}
Expand All @@ -990,6 +994,17 @@ where T: Write + Seek
Ok(())
}

pub fn stmts(
&mut self,
s: S,
d: D,
stmts: &[Stmt],
this_id: NodeID,
parent_id: Option<NodeID>,
) -> io::Result<()> {
self.stmts_with_next(s, d, stmts, this_id, None, parent_id)
}

pub fn stmt(
&mut self,
s: S,
Expand All @@ -1006,6 +1021,13 @@ where T: Write + Seek
)?;
match stmt {
Stmt::Repeat { times, body } => self.repeat(s, d, this_id, times, body),
Stmt::ForEach { name, times, body } => self.foreach(s, d, this_id, name, times, body),
Stmt::For {
cond,
incr,
body,
..
} => self.r#for(s, d, this_id, cond, incr, body),
Stmt::Forever { body, span } => self.forever(s, d, this_id, body, span),
Stmt::Branch {
cond,
Expand Down
54 changes: 54 additions & 0 deletions src/codegen/stmt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,60 @@ where T: Write + Seek
self.stmts(s, d, body, body_id, Some(this_id))
}

pub fn foreach(
&mut self,
s: S,
d: D,
this_id: NodeID,
name: &Name,
times: &Expr,
body: &[Stmt],
) -> io::Result<()> {
let times_id = self.id.new_id();
let body_id = self.id.new_id();
self.begin_inputs()?;
self.input(s, d, "VALUE", times, times_id)?;
self.substack("SUBSTACK", (!body.is_empty()).then_some(body_id))?;
self.end_obj()?; // inputs
match s.qualify_name(d, name) {
Some(QualifiedName::Var(qualified_name, _)) => {
self.single_field_id("VARIABLE", &qualified_name)?
}
Some(QualifiedName::List(..)) => {
d.report(
DiagnosticKind::UnrecognizedVariable(name.basename().clone()),
&name.span(),
);
}
None => {}
}
self.end_obj()?; // node
self.expr(s, d, times, times_id, this_id)?;
self.stmts(s, d, body, body_id, Some(this_id))
}

pub fn r#for(
&mut self,
s: S,
d: D,
this_id: NodeID,
cond: &Expr,
incr: &Stmt,
body: &[Stmt],
) -> io::Result<()> {
let cond_id = self.id.new_id();
let incr_id = self.id.new_id();
let body_id = self.id.new_id();
self.begin_inputs()?;
self.input(s, d, "CONDITION", cond, cond_id)?;
self.substack("SUBSTACK", Some((!body.is_empty()).then_some(body_id).unwrap_or(incr_id)))?;
self.end_obj()?; // inputs
self.end_obj()?; // node
self.expr(s, d, cond, cond_id, this_id)?;
self.stmts_with_next(s, d, body, body_id, Some(incr_id), Some(this_id))?;
self.stmt(s, d, incr, incr_id, None, Some(body_id))
}

pub fn forever(
&mut self,
s: S,
Expand Down
2 changes: 2 additions & 0 deletions src/lexer/token.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,8 @@ pub enum Token {
Elif,
#[token("until")]
Until,
#[token("for")]
For,
#[token("forever")]
Forever,
#[token("repeat")]
Expand Down
21 changes: 21 additions & 0 deletions src/parser/grammar.lalrpop
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,23 @@ Stmt: Stmt = {
Stmt::Branch { cond, if_body, else_body: vec![else_body] }
},
REPEAT <times:BoxedIfExpr> <body:Stmts> => Stmt::Repeat { times, body },
FOR <l:@L> <name:NAME> <r:@R> IN <times:BoxedIfExpr> <body:Stmts> => {
Stmt::ForEach {
name: Name::Name { name, span: l..r },
times,
body,
}
},
FOR <type_:Type> <l:@L> <name:NAME> <r:@R> "=" <value:BoxedExpr> ";" <cond:BoxedIfExpr> ";" <incr:BoxedStmt> <body:Stmts> => {
Stmt::For {
name: Name::Name { name, span: l..r },
value,
type_,
cond,
incr,
body,
}
},
<l:@L> FOREVER <r:@R> <body:Stmts> => Stmt::Forever { body, span: l..r },
UNTIL <cond:BoxedIfExpr> <body:Stmts> => Stmt::Until { cond, body },
<type_:Type> <l:@L> <name:NAME> <r:@R> "=" <value:BoxedExpr> ";" => {
Expand Down Expand Up @@ -297,6 +314,9 @@ Elif: Stmt = {
},
}

#[inline]
BoxedStmt: Box<Stmt> = <stmt:Stmt> => Box::new(stmt);

#[inline]
BoxedExpr: Box<Expr> = <expr:Expr> => Box::new(expr);

Expand Down Expand Up @@ -593,6 +613,7 @@ extern {
ELSE => Token::Else,
ELIF => Token::Elif,
UNTIL => Token::Until,
FOR => Token::For,
FOREVER => Token::Forever,
REPEAT => Token::Repeat,
"," => Token::Comma,
Expand Down
2 changes: 2 additions & 0 deletions src/visitor/pass0.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,8 @@ fn visit_stmts(stmts: &mut Vec<Stmt>, v: &mut V) {
fn visit_stmt(stmt: &mut Stmt, v: &mut V) {
match stmt {
Stmt::Repeat { body, .. } => visit_stmts(body, v),
Stmt::ForEach { body, .. } => visit_stmts(body, v),
Stmt::For { body, .. } => visit_stmts(body, v),
Stmt::Forever { body, .. } => visit_stmts(body, v),
Stmt::Branch {
if_body, else_body, ..
Expand Down
24 changes: 24 additions & 0 deletions src/visitor/pass1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,30 @@ fn visit_stmt(stmt: &mut Stmt, s: &mut S) -> Vec<Stmt> {
visit_expr(times, &mut before, s);
visit_stmts(body, s);
}
Stmt::ForEach { times, body, .. } => {
visit_expr(times, &mut before, s);
visit_stmts(body, s);
}
Stmt::For {
name,
value,
type_,
cond,
incr,
body,
} => {
before.push(Stmt::SetVar {
name: name.clone(),
value: value.clone(),
type_: type_.clone(),
is_local: false,
is_cloud: false,
});
visit_expr(value, &mut before, s);
visit_expr(cond, &mut before, s);
visit_stmt(incr, s);
visit_stmts(body, s);
}
Stmt::Forever { body, span: _ } => visit_stmts(body, s),
Stmt::Branch {
cond,
Expand Down
16 changes: 16 additions & 0 deletions src/visitor/pass2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,22 @@ fn visit_stmt(stmt: &mut Stmt, s: S, d: D) {
visit_expr(times, s, d, false);
visit_stmts(body, s, d, false);
}
Stmt::ForEach { times, body, .. } => {
visit_expr(times, s, d, false);
visit_stmts(body, s, d, false);
}
Stmt::For {
value,
cond,
incr,
body,
..
} => {
visit_expr(value, s, d, false);
visit_expr(cond, s, d, true);
visit_stmt(incr, s, d);
visit_stmts(body, s, d, false);
}
Stmt::Forever { body, span: _ } => {
visit_stmts(body, s, d, false);
}
Expand Down