Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
Handle case/when
  • Loading branch information
kddnewton committed Nov 18, 2022
commit db88d3309390f061c62fa2896bd8d07d9ab81f61
47 changes: 47 additions & 0 deletions lib/syntax_tree/visitor/compiler.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1324,6 +1324,49 @@ def visit_call(node)
builder.send(node.message.value.to_sym, argc, flag, block_iseq)
end

def visit_case(node)
visit(node.value) if node.value

clauses = []
else_clause = nil

current = node.consequent

while current
clauses << current

if (current = current.consequent).is_a?(Else)
else_clause = current
break
end
end

branches =
clauses.map do |clause|
visit(clause.arguments)
builder.topn(1)
builder.send(:===, 1, VM_CALL_FCALL | VM_CALL_ARGS_SIMPLE)
[clause, builder.branchif(:label_00)]
end

builder.pop

if else_clause
visit(else_clause)
else
builder.putnil
end

builder.leave

branches.each_with_index do |(clause, branchif), index|
builder.leave if index != 0
branchif[1] = builder.label
builder.pop
visit(clause)
end
end

def visit_class(node)
name = node.constant.constant.value.to_sym
class_iseq =
Expand Down Expand Up @@ -2148,6 +2191,10 @@ def visit_vcall(node)
builder.send(node.value.value.to_sym, 0, flag)
end

def visit_when(node)
visit(node.statements)
end

def visit_while(node)
jumps = []

Expand Down
2 changes: 2 additions & 0 deletions test/compiler_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,8 @@ class CompilerTest < Minitest::Test
"until foo do bar end",
"for i in [1, 2, 3] do i end",
"foo ? bar : baz",
"case foo when bar then 1 end",
"case foo when bar then 1 else 2 end",
# Constructed values
"foo..bar",
"foo...bar",
Expand Down