Skip to content

Commit

Permalink
Warn duplication of __ENCODING__ on the hash
Browse files Browse the repository at this point in the history
```
$ ruby -e 'h = { __ENCODING__ => 1, __ENCODING__ => 2 }'
-e:1: warning: key #<Encoding:UTF-8> is duplicated and overwritten on line 1
```
  • Loading branch information
yui-knk committed Feb 12, 2024
1 parent f41d8f3 commit 8a34586
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 0 deletions.
4 changes: 4 additions & 0 deletions parse.y
Expand Up @@ -90,6 +90,7 @@ hash_literal_key_p(VALUE k)
case NODE_SYM:
case NODE_LINE:
case NODE_FILE:
case NODE_ENCODING:
return true;
default:
return false;
Expand Down Expand Up @@ -193,6 +194,8 @@ node_cdhash_cmp(VALUE val, VALUE lit)
return node_val->nd_loc.beg_pos.lineno != node_lit->nd_loc.beg_pos.lineno;
case NODE_FILE:
return rb_parser_string_hash_cmp(RNODE_FILE(node_val)->path, RNODE_FILE(node_lit)->path);
case NODE_ENCODING:
return RNODE_ENCODING(node_val)->enc != RNODE_ENCODING(node_lit)->enc;
default:
rb_bug("unexpected node: %s, %s", ruby_node_name(type_val), ruby_node_name(type_lit));
}
Expand Down Expand Up @@ -15461,6 +15464,7 @@ nd_type_st_key_enable_p(NODE *node)
case NODE_SYM:
case NODE_LINE:
case NODE_FILE:
case NODE_ENCODING:
return true;
default:
return false;
Expand Down
1 change: 1 addition & 0 deletions test/ruby/test_literal.rb
Expand Up @@ -498,6 +498,7 @@ def test_hash_duplicated_key
'//',
'__LINE__',
'__FILE__',
'__ENCODING__',
) do |key|
assert_warning(/key #{Regexp.quote(eval(key).inspect)} is duplicated/) { eval("{#{key} => :bar, #{key} => :foo}") }
end
Expand Down

0 comments on commit 8a34586

Please sign in to comment.