Skip to content

Commit

Permalink
fix(throw): compile last throw expression as throw statement not `ret…
Browse files Browse the repository at this point in the history
…urn throw ...`
  • Loading branch information
kollhof committed Mar 2, 2020
1 parent 1cbf789 commit a2129e0
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 9 deletions.
17 changes: 13 additions & 4 deletions src/transform/__snapshots__/throw.test.js.snap
Original file line number Diff line number Diff line change
@@ -1,8 +1,17 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`throw transforms throw 1`] = `
"const foo = bar || throw err(\`spam\`);
Object.assign(module.exports, {
foo
});"
"bar => {
const ˆvalue_1 = true;
ifvalue_1 === has_err(bar)) {
throw err(\`spam\`);
}
{
return bar;
}
};
Object.assign(module.exports, {});"
`;
16 changes: 12 additions & 4 deletions src/transform/js/do-expression.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {
assignmentExpression, returnStatement, callExpression,
arrowFunctionExpression
arrowFunctionExpression,
expressionStatement
} from '@babel/types';
import {lets, assign, undef} from '../../types';

Expand Down Expand Up @@ -40,9 +41,16 @@ function* last_expressions(path) {

const replace_with_return = (path)=> {
for (const expr of last_expressions(path)) {
expr.replaceWith(
returnStatement(expr.node.expression)
);
if (expr.node.expression.operator === 'throw') {
// no `return throw ...`
expr.replaceWith(
expressionStatement(expr.node.expression)
);
} else {
expr.replaceWith(
returnStatement(expr.node.expression)
);
}

// TODO: no need for e.g. breaks after a return
const sibl = expr.getSibling(expr.key+1);
Expand Down
5 changes: 4 additions & 1 deletion src/transform/throw.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@ describe('throw', ()=> {
it('transforms throw', ()=> {
expect(
fink2js(`
foo = bar || throw err('spam')
fn bar:
match true:
has_err(bar): throw err('spam')
else: bar
`)
).toMatchSnapshot();
});
Expand Down

0 comments on commit a2129e0

Please sign in to comment.