From: "zverok (Victor Shepelev) via ruby-core" Date: 2025-01-12T08:20:20+00:00 Subject: [ruby-core:120621] [Ruby master Bug#21026] `def __FILE__.a; end` should be a syntax error Issue #21026 has been updated by zverok (Victor Shepelev). As far as I understand (though it is an intuitive understanding, not backed by looking into particular implementation), `__FILE__` and `__LINE__` are handled at the parsing stage, behaving in (almost) all situations like there was just a corresponding literal in the code. Say, with `-W:deprecated`, this code: ```ruby def __FILE__.a end ``` will dutifully emit (as if it would be just a literal) ``` warning: literal string will be frozen in the future ``` ...and with `# frozen_string_literal: true` pragma, it will fail with ``` can't define singleton (TypeError) ``` So, as I said, it is _almost_ like it would be a literal string... Except that with a literal string this code would be yelled at by the parser as an impossible (which doesn���t happen with `__FILE__` because, I think, of the order of substitution for it to the ���real��� literal): ```ruby def 'test.rb'.a end ``` ``` test.rb:1: syntax errors found (SyntaxError) > 1 | def 'test.rb'.a | ^ expected a delimiter to close the parameters | ^ unexpected string literal; expected a method name ``` ---------------------------------------- Bug #21026: `def __FILE__.a; end` should be a syntax error https://bugs.ruby-lang.org/issues/21026#change-111450 * Author: Earlopain (Earlopain _) * Status: Open * ruby -v: ruby 3.4.1 (2024-12-25 revision 48d4efcb85) +PRISM [x86_64-linux] * Backport: 3.1: UNKNOWN, 3.2: UNKNOWN, 3.3: UNKNOWN, 3.4: UNKNOWN ---------------------------------------- Constants like `__FILE__`, `__LINE__` and `__ENCODING__` are literals and as such you shouldn't be able to defined singleton methods on them. It already doesn't seem to actually do anything: ```rb def __FILE__.a end __FILE__.a #=> undefined method 'a' for an instance of String (NoMethodError) ``` Wrapping it in brackets correctly reports a syntax error: ```rb code.rb:1: syntax error found (SyntaxError) > 1 | def (__FILE__).a | ^~~~~~~~ cannot define singleton method for literals 2 | end ``` The behavior is consistent between prism and parse.y `__ENCODING__` is frozen and so will result in a runtime error. Same for `__LINE__`, and also `__FILE__` with frozen string literals. -- https://bugs.ruby-lang.org/ ______________________________________________ ruby-core mailing list -- ruby-core@ml.ruby-lang.org To unsubscribe send an email to ruby-core-leave@ml.ruby-lang.org ruby-core info -- https://ml.ruby-lang.org/mailman3/lists/ruby-core.ml.ruby-lang.org/