How can I simulate macros in JavaScript?

后端 未结 8 1148
悲哀的现实
悲哀的现实 2020-12-05 10:02

I know that JavaScript doesn\'t support macros (Lisp-style ones) but I was wondering if anyone had a solution to maybe simulate macros? I Googled it, and one of the solution

相关标签:
8条回答
  • 2020-12-05 10:59

    I've written a gameboy emulator in javascript and I simulate macros for cpu emulation this way:

    macro code (the function returns a string with the macro code):

    function CPU_CP_A(R,C) { // this function simulates the CP instruction, 
      return ''+             // sets CPU flags and stores in CCC the number
      'FZ=(RA=='+R+');'+     // of cpu cycles needed
      'FN=1;'+
      'FC=RA<'+R+';'+
      'FH=(RA&0x0F)<('+R+'&0x0F);'+
      'ICC='+C+';';
    }
    

    Using the "macro", so the code is generated "on the fly" and we don't need to make function calls to it or write lots of repeated code for each istruction...

    OP[0xB8]=new Function(CPU_CP_A('RB',4)); // CP B
    OP[0xB9]=new Function(CPU_CP_A('RC',4)); // CP C
    OP[0xBA]=new Function(CPU_CP_A('RD',4)); // CP D
    OP[0xBB]=new Function(CPU_CP_A('RE',4)); // CP E
    OP[0xBC]=new Function('T1=HL>>8;'+CPU_CP_A('T1',4)); // CP H
    OP[0xBD]=new Function('T1=HL&0xFF;'+CPU_CP_A('T1',4)); // CP L
    OP[0xBE]=new Function('T1=MEM[HL];'+CPU_CP_A('T1',8)); // CP (HL)
    OP[0xBF]=new Function(CPU_CP_A('RA',4)); // CP A
    

    Now we can execute emulated code like this:

    OP[MEM[PC]](); // MEM is an array of bytes and PC the program counter
    

    Hope it helps...

    0 讨论(0)
  • 2020-12-05 11:00

    One can also now use ClojureScript to compile clojure to javascript and get macros that way. Note ClojureScript uses Google Closure.

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