Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is the __LINE__ and __FILE__ constants implemented in Ruby?

Tags:

ruby

It seems the __FILE__ and __LINE__ constants are dynamically updated with the current file and line numbers under execution, I am wondering how is the behaviour implemented in Ruby?

I've greped the source code but there are too many noises for __LINE__ and __FILE__ appearance, I am wonder anyone could help me point to the source code and provide a clue to understand its behaviour.

Explanation in either Rubinis or MRI will be fine.

like image 338
steveyang Avatar asked May 18 '13 17:05

steveyang


People also ask

What does __ file __ mean in Ruby?

The value of __FILE__ is a relative path that is created and stored (but never updated) when your file is loaded. This means that if you have any calls to Dir.

What is file in Ruby?

A File is an abstraction of any file object accessible by the program and is closely associated with class IO . File includes the methods of module FileTest as class methods, allowing you to write (for example) File. exist?("foo") .


1 Answers

Both __FILE__ and __LINE__ get replaced by literals directly in the parser:

case keyword__FILE__:
    return NEW_STR(rb_external_str_new_with_enc(ruby_sourcefile, strlen(ruby_sourcefile),
                                                rb_filesystem_encoding()));
case keyword__LINE__:
    return NEW_LIT(INT2FIX(tokline));

In other words, they behave exactly as if you had typed in the resulting string or number yourself.

Note that for __LINE__, this doesn't always behave how you'd expect.

like image 127
hammar Avatar answered Oct 25 '22 08:10

hammar