Skip to content

Commit 1739fd8

Browse files
committed
Add emitters for s(:__LINE__) and s(:__FILE__)
A few years ago, parser added a flag whereby parser will parse __LINE__ and __FILE__ as actual nodes rather than literals. This commit adds emitters to Unparser so that these special non-literal line and file nodes can be unparsed. See whitequark/parser@997a834 Closes mbj#69
1 parent b7f745a commit 1739fd8

File tree

3 files changed

+27
-2
lines changed

3 files changed

+27
-2
lines changed

lib/unparser.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ def self.unparse(node, comment_array = [])
5050
require 'unparser/emitter/literal/range'
5151
require 'unparser/emitter/literal/dynamic_body'
5252
require 'unparser/emitter/literal/execute_string'
53+
require 'unparser/emitter/meta'
5354
require 'unparser/emitter/send'
5455
require 'unparser/emitter/send/unary'
5556
require 'unparser/emitter/send/binary'

lib/unparser/emitter/meta.rb

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
module Unparser
2+
class Emitter
3+
# Namespace class for meta emitters
4+
class Meta < self
5+
include Terminated
6+
7+
handle(:__FILE__, :__LINE__)
8+
9+
def dispatch
10+
write(node.type.to_s) # (e.g. literally write '__FILE__' or '__LINE__')
11+
end
12+
end # Meta
13+
end # Emitter
14+
end # Unparser

spec/unit/unparser_spec.rb

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -323,8 +323,18 @@ def foo(bar:, baz: "value")
323323

324324
context 'magic keywords' do
325325
assert_generates '__ENCODING__', 'Encoding::UTF_8'
326-
assert_generates '__FILE__', '"(string)"'
327-
assert_generates '__LINE__', '1'
326+
327+
# These two assertions don't actually need to be wrapped in this block since `true` is the default,
328+
# but it is helpful to contrast with the assertions farther down.
329+
with_builder_options(emit_file_line_as_literals: true) do
330+
assert_generates '__FILE__', '"(string)"'
331+
assert_generates '__LINE__', '1'
332+
end
333+
334+
with_builder_options(emit_file_line_as_literals: false) do
335+
assert_source '__FILE__'
336+
assert_source '__LINE__'
337+
end
328338
end
329339

330340
context 'assignment' do

0 commit comments

Comments
 (0)