Programming language for self-modifying code?

后端 未结 14 1778
别那么骄傲
别那么骄傲 2020-12-23 13:05
  • I am recently thinking about writing self-modifying programs, I think it may be powerful and fun. So I am currently looking for a language that allows
相关标签:
14条回答
  • 2020-12-23 13:30

    Common Lisp was designed with this sort of thing in mind. You could also try Smalltalk, where using reflection to modify running code is not unknown.

    In both of these languages you are likely to be replacing an entire function or an entire method, not a single line of code. Smalltalk methods tend to be more fine-grained than Lisp functions, so that may be a good place to begin.

    0 讨论(0)
  • 2020-12-23 13:32

    Many languages allow you to eval code at runtime.

    • Lisp
    • Perl
    • Python
    • PHP
    • Ruby
    • Groovy (via GroovyShell)
    0 讨论(0)
  • 2020-12-23 13:33

    I sometimes, although very rarely do self-modifying code in Ruby.

    Sometimes you have a method where you don't really know whether the data you are using (e.g. some lazy cache) is properly initialized or not. So, you have to check at the beginning of your method whether the data is properly initialized and then maybe initialize it. But you really only have to do that initialization once, but you check for it every single time.

    So, sometimes I write a method which does the initialization and then replaces itself with a version that doesn't include the initialization code.

    class Cache
      def [](key)
        @backing_store ||= self.expensive_initialization
    
        def [](key)
          @backing_store[key]
        end
    
        @backing_store[key]
      end
    end
    

    But honestly, I don't think that's worth it. In fact, I'm embarrassed to admit that I have never actually benchmarked to see whether that one conditional actually makes any difference. (On a modern Ruby implementation with an aggressively optimizing profile-feedback-driven JIT compiler probably not.)

    Note that, depending on how you define "self-modifying code", this may or may not be what you want. You are replacing some part of the currently executing program, so …

    EDIT: Now that I think about it, that optimization doesn't make much sense. The expensive initialization is only executed once anyway. The only thing that modification avoids, is the conditional. It would be better to take an example where the check itself is expensive, but I can't think of one.

    However, I thought of a cool example of self-modifying code: the Maxine JVM. Maxine is a Research VM (it's technically not actually allowed to be called a "JVM" because its developers don't run the compatibility testsuites) written completely in Java. Now, there are plenty of JVMs written in itself, but Maxine is the only one I know of that also runs in itself. This is extremely powerful. For example, the JIT compiler can JIT compile itself to adapt it to the type of code that it is JIT compiling.

    A very similar thing happens in the Klein VM which is a VM for the Self Programming Language.

    In both cases, the VM can optimize and recompile itself at runtime.

    0 讨论(0)
  • 2020-12-23 13:35

    I wrote Python class Code that enables you to add and delete new lines of code to the object, print the code and excecute it. Class Code shown at the end.

    Example: if the x == 1, the code changes its value to x = 2 and then deletes the whole block with the conditional that checked for that condition.

    #Initialize Variables
    x = 1
    
    #Create Code
    code = Code()
    code + 'global x, code' #Adds a new Code instance code[0] with this line of code => internally             code.subcode[0]
    code + "if x == 1:"     #Adds a new Code instance code[1] with this line of code => internally code.subcode[1]
    code[1] + "x = 2"       #Adds a new Code instance 0 under code[1] with this line of code => internally code.subcode[1].subcode[0]
    code[1] + "del code[1]" #Adds a new Code instance 0 under code[1] with this line of code => internally code.subcode[1].subcode[1]
    

    After the code is created you can print it:

    #Prints
    print "Initial Code:"
    print code
    print "x = " + str(x)
    

    Output:

    Initial Code:
    
    global x, code
    if x == 1:
        x = 2
        del code[1]
    
    x = 1
    

    Execute the cade by calling the object: code()

    print "Code after execution:"
    code() #Executes code
    print code
    print "x = " + str(x)
    

    Output 2:

    Code after execution:
    
    global x, code
    
    x = 2
    

    As you can see, the code changed the variable x to the value 2 and deleted the whole if block. This might be useful to avoid checking for conditions once they are met. In real-life, this case-scenario could be handled by a coroutine system, but this self modifying code experiment is just for fun.

    class Code:
    
        def __init__(self,line = '',indent = -1):
    
            if indent < -1:
                raise NameError('Invalid {} indent'.format(indent))
    
            self.strindent = ''
            for i in xrange(indent):
                self.strindent = '    ' + self.strindent
    
            self.strsubindent = '    ' + self.strindent
    
            self.line = line
            self.subcode = []
            self.indent = indent
    
    
        def __add__(self,other):
    
            if other.__class__ is str:
                other_code = Code(other,self.indent+1)
                self.subcode.append(other_code)
                return self
    
            elif other.__class__ is Code:
                self.subcode.append(other)
                return self
    
        def __sub__(self,other):
    
            if other.__class__ is str:
                for code in self.subcode:
                    if code.line == other:
                        self.subcode.remove(code)
                        return self
    
    
            elif other.__class__ is Code:
                self.subcode.remove(other)
    
    
        def __repr__(self):
            rep = self.strindent + self.line + '\n'
            for code in self.subcode: rep += code.__repr__()
            return rep
    
        def __call__(self):
            print 'executing code'
            exec(self.__repr__())
            return self.__repr__()
    
    
        def __getitem__(self,key):
            if key.__class__ is str:
                    for code in self.subcode:
                        if code.line is key:
                            return code
            elif key.__class__ is int:
                return self.subcode[key]
    
        def __delitem__(self,key):
            if key.__class__ is str:
                for i in range(len(self.subcode)):
                    code = self.subcode[i]
                    if code.line is key:
                        del self.subcode[i]
            elif key.__class__ is int:
                del self.subcode[key]
    
    0 讨论(0)
  • 2020-12-23 13:36

    In Lua, you can "hook" existing code, which allows you to attach arbitrary code to function calls. It goes something like this:

    local oldMyFunction = myFunction
    myFunction = function(arg)
        if arg.blah then return oldMyFunction(arg) end
        else
            --do whatever
        end
    end
    

    You can also simply plow over functions, which sort of gives you self modifying code.

    0 讨论(0)
  • 2020-12-23 13:40

    Dlang's LLVM implementation contains the @dynamicCompile and @dynamicCompileConst function attributes, allowing you to compile according to the native host's the instruction set at compile-time, and change compile-time constants in runtime through recompilation.

    https://forum.dlang.org/thread/bskpxhrqyfkvaqzoospx@forum.dlang.org

    0 讨论(0)
提交回复
热议问题