2

I have seen some opinions that Rust and M# may opt for compile-time reflection because run-time reflection is expensive and increases the size of binaries. I could not find any good comparison so far, just some opinions that run-time reflection is "rarely a good idea". It seems that languages exploring the concept of built-in compile-time reflection are all still in development.

Sources I have read so far:

Community
  • 1
  • 1
Den
  • 1,827
  • 3
  • 25
  • 46
  • 1
    I would make a slight clarification of what I said in the last mentioned source: *conceptually*, I believe run-time reflection to be inferior to compile-time reflection. I say this as one who is primarily a Python developer, though I write quite a lot of Rust in my own time now. In practice, most languages do not have sufficiently powerful compile-time semantics and so most times compile-time reflection will not be enough. – Chris Morgan Jun 08 '14 at 16:08
  • 1
    I think you are likely to get answers here for which a Sufficiently Powerful Compiler could in fact allow you to use compile-time reflection. I am not convinced this is a particularly good question for Stack Overflow, but let’s see how it goes. I’ll be standing by to refute any claims, if I can! – Chris Morgan Jun 08 '14 at 16:09
  • @ChrisMorgan I had my doubts, but I feel this question could be answered conclusively along the lines of: "dynamically load a binary and then instantiate _any_ type marked with certain annotation and then somehow process all fields of said instances marked with another annotation". The answer would have practical implications for a narrow type of projects (mainly frameworks I guess: ORMs, plugin-powered editors (aka Unity3d) etc.). – Den Jun 08 '14 at 19:15
  • That’s not something that needs what I would consider run-time reflection. Consider how the Rust compiler supports loading external syntax extensions—that is done by finding the library file to `dlopen`, loading from a predetermined location the function that was marked inside it at compile time, and then calling it. There is no reflection beyond that, for it uses trait objects. Traits and trait objects (dynamic dispatch) obviate the necessity of this run‐time reflection, and so all that is still needed is the ability to link to a dynamically determined library. – Chris Morgan Jun 09 '14 at 01:05

1 Answers1

1

Here's some Ruby:

m = STDIN.gets.chomp

puts Object.respond_to?(m)

Not really possible to do that at compile time. I mean, with CTFE, you could technically run this code at compile time, but as part of a running program, it won't really work.

Another fun one:

$m = STDIN.gets.chomp

class Object
   define_method $m do
     puts "zomg"
   end
end

class Foo; end

Foo.new.send($m)

This prints "zomg".

Steve Klabnik
  • 14,521
  • 4
  • 58
  • 99