Bug 18919 – __FILE__ and __LINE__ should work when used in default argument expressions

Status
RESOLVED
Resolution
FIXED
Severity
enhancement
Priority
P4
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2018-05-30T19:54:00Z
Last change time
2024-01-07T22:57:56Z
Keywords
pull
Assigned to
No Owner
Creator
Steven Schveighoffer

Comments

Comment #0 by schveiguy — 2018-05-30T19:54:00Z
Currently, __FILE__ and __LINE__ expand to the *caller's* location if used directly as default parameters in a function: void foo(string file = __FILE__, size_t line = __LINE__) { import std.stdio; writeln(file, " ", line); } void main() { foo(); // line 9 } prints "foo.d 9" But if you wrap those into an expression, it changes the meaning: struct Loc { string file; size_t line; } void foo(Loc loc = Loc(__FILE__, __LINE__)) // line 6 { import std.stdio; writeln(loc.file, " ", loc.line); } void main() { foo(); // line 14 } prints "foo.d 6" There's no reason it shouldn't just forward the original caller's file/line to the expression itself. It violates the principal of least surprise, and the current behavior is pretty near useless. In addition to fixing this, default parameters in expressions called should ALSO forward: Loc defaultLoc(string file = __FILE__, size_t line = __LINE) { return Loc(file, line); } void foo(Loc loc = defaultLoc) { writeln(loc.file, " ", loc.line); } This should print wherever foo is called from. I'd predict 0 code breakage, because anyone trying to use this would be wanting the expected behavior, so they wouldn't use this mechanism.
Comment #1 by pro.mathias.lang — 2020-07-24T06:28:26Z
Just hit this one while trying to be smart. I agree it should work this way.
Comment #2 by dkorpel — 2021-02-05T16:46:34Z
*** Issue 21211 has been marked as a duplicate of this issue. ***
Comment #3 by dlang-bot — 2023-12-30T10:56:35Z
@tim-dlang created dlang/dmd pull request #15968 "Fix issue 18919 - __FILE__ and __LINE__ should work when used in defa…" fixing this issue: - Fix issue 18919 - __FILE__ and __LINE__ should work when used in default argument expressions The parser now always creates AST nodes for default init expressions like __FILE__. They are replaced in resolveLoc. Variable inDefaultArg in Scope is used, so the nodes are not replaced too early. https://github.com/dlang/dmd/pull/15968
Comment #4 by dlang-bot — 2024-01-07T22:57:56Z
dlang/dmd pull request #15968 "Fix issue 18919 - __FILE__ and __LINE__ should work when used in defa…" was merged into master: - b2b81060411ae02d8336cd0aa47265775f29a8b4 by Tim Schendekehl: Fix issue 18919 - __FILE__ and __LINE__ should work when used in default argument expressions The parser now always creates AST nodes for default init expressions like __FILE__. They are replaced in resolveLoc. Variable inDefaultArg in Scope is used, so the nodes are not replaced too early. https://github.com/dlang/dmd/pull/15968