assemblykeywordbytecodeinline-assemblyinterpreted-language

Is there any interpreted language exposing its bytecode (or any IR)


I'm curious to know if any language exists that gives the programmer the possibility to 'emit' bytecode in the middle of the source code. To be more clear, is there any interpreted language that has a facility similar to the asm keyword for c/c++ ?


Solution

  • I'm not sure if this counts, but in Forth you can traditionally do this. You can leave the compiler with [ at any point and manipulate the byte code and compiler state as you like before resuming compilation with ]. The word , directly emits the word on the stack into the byte code. For example, the following word pushes 6 × 7 on the stack; comments are delimited with parentheses:

    : answer               ( create a word answer, start the compiler )
    [                      ( stop the compiler )
    6 7 *                  ( compute 6 × 7 )
    ' LIT                  ( push the word LIT (push literal) on the stack )
    ,                      ( append it to the machine code )
    ,                      ( append 6 × 7 to the machine code )
    ]                      ( resume compilation )
    ;                      ( finish the definition of answer )
    

    This code works the same as if you wrote

    : answer 42 ;
    

    which is compiled to the byte code

    LIT 42 EXIT
    

    The word LIT takes the next word from the byte code stream and pushes it on the stack, EXIT returns from the current byte code function.