Skip to content

Commit

Permalink
Make return statements legal in block expressions
Browse files Browse the repository at this point in the history
  • Loading branch information
frostburn committed Jun 18, 2024
1 parent 066c7c5 commit 0a7f0bc
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 1 deletion.
11 changes: 11 additions & 0 deletions documentation/advanced-dsl.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,17 @@ Blocks are valid expressions and evaluate to arrays. They have the lowest preced
(* $ = [10, 20, 30] *)
```

#### Block expression return value
Use a `return` statement inside a block expression to evaluate to the returned value.
```ocaml
const foo = {
const bar = 2
const baz = 3
return bar + baz
}
(* const foo = 5 *)
```

### Parent scale
The current scale of the parent block can be accessed using `$$`.

Expand Down
12 changes: 12 additions & 0 deletions src/parser/__tests__/expression.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2460,6 +2460,18 @@ describe('SonicWeave expression evaluator', () => {
expect(interval.value).toBeInstanceOf(TimeReal);
expect(interval.valueOf()).toBeCloseTo(1.000000745, 10);
});

it('allows return from block expressions', () => {
const foo = evaluate(`
const foo = ({
const ba = "ba"
return ba "r"
throw "not executed"
})
foo
`);
expect(foo).toBe('bar');
});
});

describe('Poor grammar / Fun with "<"', () => {
Expand Down
4 changes: 3 additions & 1 deletion src/parser/expression.ts
Original file line number Diff line number Diff line change
Expand Up @@ -429,7 +429,9 @@ export class ExpressionVisitor {
const scale = this.currentScale;
subVisitor.mutables.set('$$', scale);
const interrupt = subVisitor.executeStatements(node.body);
if (interrupt) {
if (interrupt?.type === 'ReturnStatement') {
return interrupt.value;
} else if (interrupt) {
throw new Error('Illegal interupt.');
}
return subVisitor.currentScale;
Expand Down

0 comments on commit 0a7f0bc

Please sign in to comment.