Skip to content

Commit

Permalink
Support NODE_LVAR
Browse files Browse the repository at this point in the history
And fix NODE_BLOCK can't generate correct Array
  • Loading branch information
S-H-GAMELINKS committed Aug 14, 2024
1 parent e320ab9 commit 1f49291
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 7 deletions.
28 changes: 21 additions & 7 deletions ext/mjollnir/mjollnir.c
Original file line number Diff line number Diff line change
Expand Up @@ -56,12 +56,11 @@ static VALUE
node_block_to_hash(const NODE *node)
{
VALUE result = rb_ary_new();
NODE *nd_head = RNODE_BLOCK(node)->nd_head;
NODE *nd_end = RNODE_BLOCK(node)->nd_end;

while (RNODE_BLOCK(node)->nd_next && nd_head != nd_end) {
rb_ary_push(result, ast_to_values(Qnil, nd_head));
nd_head = RNODE_BLOCK(node)->nd_next;
const NODE *current_node = node;

while (current_node) {
rb_ary_push(result, ast_to_values(Qnil, RNODE_BLOCK(current_node)->nd_head));
current_node = RNODE_BLOCK(current_node)->nd_next;
}

return result;
Expand All @@ -76,6 +75,14 @@ left_assign_to_hash(const NODE *node)
return result;
}

static VALUE
node_lvar_to_hash(const NODE *node)
{
VALUE result = rb_hash_new();
rb_hash_aset(result, rb_str_new2("vid"), ID2SYM(RNODE_LVAR(node)->nd_vid));
return result;
}

static VALUE
literal_node_to_hash(const NODE *node)
{
Expand Down Expand Up @@ -143,13 +150,20 @@ ast_to_values(VALUE hash, const NODE *node)
return result;
}
case NODE_BLOCK: {
return node_block_to_hash(node);
VALUE result = rb_hash_new();
rb_hash_aset(result, rb_str_new2("NODE_BLOCK"), node_block_to_hash(node));
return result;
}
case NODE_LASGN: {
VALUE result = rb_hash_new();
rb_hash_aset(result, rb_str_new2("NODE_LASGN"), left_assign_to_hash(node));
return result;
}
case NODE_LVAR: {
VALUE result = rb_hash_new();
rb_hash_aset(result, rb_str_new2("NODE_LVAR"), node_lvar_to_hash(node));
return result;
}
case NODE_LIST: {
VALUE result = rb_hash_new();
rb_hash_aset(result, rb_str_new2("NODE_LIST"), list_node_to_hash(node));
Expand Down
43 changes: 43 additions & 0 deletions test/mjollnir/parse_lvar_test.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# frozen_string_literal: true

require 'test_helper'

class ParseLvarTest < Minitest::Test
def test_parse_lvar
result = Mjollnir.parse(<<~CODE)
v = 117
p v
CODE

expected = {
'NODE_SCOPE' => {
'NODE_BLOCK' => [
{
'NODE_LASGN' => {
'id' => :v,
'value' => {
'NODE_INTEGER' => 117
}
}
},
{
'NODE_FCALL' => {
'mid' => :p,
'args' => {
'NODE_LIST' => [
{
'NODE_LVAR' => {
'vid' => :v
}
}
]
}
}
}
]
}
}

assert_equal expected, result
end
end

0 comments on commit 1f49291

Please sign in to comment.