|
| 1 | +defmodule ElixirScript.Translate.Forms.With do |
| 2 | + @moduledoc false |
| 3 | + alias ESTree.Tools.Builder, as: JS |
| 4 | + alias ElixirScript.Translate.{Function, Clause} |
| 5 | + alias ElixirScript.Translate.Forms.Pattern |
| 6 | + |
| 7 | + |
| 8 | + def compile(args, module_state) do |
| 9 | + result = Enum.reduce(args, %{ expressions: [], arguments: [], module_state: module_state }, fn |
| 10 | + {symbol, _, [pattern, body] }, state when symbol in [:<-, :=] -> |
| 11 | + {ast, module_state} = Function.compile_block(body, state.module_state) |
| 12 | + body = Clause.return_last_statement(ast) |
| 13 | + expr_function = JS.arrow_function_expression(state.arguments, [], JS.block_statement(body)) |
| 14 | + |
| 15 | + { patterns, params, module_state } = Pattern.compile([pattern], module_state) |
| 16 | + |
| 17 | + %{state | arguments: state.arguments ++ params, |
| 18 | + expressions: state.expressions ++ [ JS.array_expression([hd(patterns), expr_function]) ], |
| 19 | + module_state: module_state |
| 20 | + } |
| 21 | + |
| 22 | + [do: expr], state -> |
| 23 | + expr_function = process_block(expr, state.arguments, state.module_state) |
| 24 | + |
| 25 | + %{state | expressions: state.expressions ++ [ expr_function ] } |
| 26 | + [do: do_expr, else: else_expr], state -> |
| 27 | + do_function = process_block(do_expr, state.arguments, state.module_state) |
| 28 | + |
| 29 | + { else_function, _ } = Function.compile({:fn, [], else_expr}, state.module_state) |
| 30 | + |
| 31 | + %{state | expressions: state.expressions ++ [ do_function, else_function ] } |
| 32 | + end) |
| 33 | + |
| 34 | + expressions = result.expressions |
| 35 | + |
| 36 | + js_ast = JS.call_expression( |
| 37 | + JS.member_expression( |
| 38 | + JS.member_expression( |
| 39 | + JS.identifier("Bootstrap"), |
| 40 | + JS.member_expression( |
| 41 | + JS.identifier("Core"), |
| 42 | + JS.identifier("SpecialForms") |
| 43 | + ) |
| 44 | + ), |
| 45 | + JS.identifier("_with") |
| 46 | + ), |
| 47 | + expressions |
| 48 | + ) |
| 49 | + |
| 50 | + { js_ast, module_state } |
| 51 | + |
| 52 | + end |
| 53 | + |
| 54 | + |
| 55 | + defp process_block(body, arguments, module_state) do |
| 56 | + {ast, _} = Function.compile_block(body, module_state) |
| 57 | + |
| 58 | + body = Clause.return_last_statement(ast) |
| 59 | + JS.arrow_function_expression(arguments, [], JS.block_statement(body)) |
| 60 | + end |
| 61 | +end |
0 commit comments