Writing a (dis-)assembler for 8-bit code in D - blog posts

Petar Petar
Tue Apr 20 15:26:28 UTC 2021


On Tuesday, 20 April 2021 at 13:38:37 UTC, Brian wrote:
>
>> `static foreach` has a lot of potential to shorten your 
>> assembler code.
>> ```D
>> sw: switch (op)
>> {   //iterates over the array at compile time
>>     static foreach(opStr; ["nop", "lxi", "stax", "inx", "inr", 
>> "dcr", "mvi", <...>])
>>     {	case opStr:
>>         mixin(opStr)(); //inserts a call to function with name 
>> opStr.
>>         break sw; //breaks out of the switch statement
>>     }
>>
>>     default: err("unknown opcode: " ~ op);
>> }
>> ```
>>
>> Even better is if you make a global array of opCodes and pass 
>> that to `static foreach`. The opcode array needs to be 
>> available in compile time, so mark it `enum` instead of 
>> `immutable`, like: `enum opcodes = ["nop", "lxi", "stax", 
>> <...>];`
>
> I should spend some time looking at mixins. The rest you have 
> there makes intuitive sense looking at it. (Crazy question: is 
> there a way to dump internal state after semantic analysis?)

Not sure if that's quite what you want, but you can use 
[`pragma(msg, typeOrValueKnownAtCompileTime)`][1] [²][2] to print 
stuff at CT.

The following program:

```d
void main()
{
     string op;
	sw: switch (op)
     {
         static foreach(opStr; ["nop", "lxi", "stax", "inx", 
"inr", "dcr", "mvi"])
         {	case opStr:
             pragma(msg, "Inside case: '", opStr, "'");
             break sw;
         }
         default: return;
     }
}
```

Prints during compilation:

```
Inside case: 'nop'
Inside case: 'lxi'
Inside case: 'stax'
Inside case: 'inx'
Inside case: 'inr'
Inside case: 'dcr'
Inside case: 'mvi'
```

(Try online: https://run.dlang.io/is/czbSXe)

If you want read an in-depth explanation regarding the fine 
distinction between `static` compile-time code and "dynamic" 
compile-time code, you can check this wiki page:
https://wiki.dlang.org/User:Quickfur/Compile-time_vs._compile-time

[1]: https://dlang.org/spec/pragma.html#msg
[2]: http://ddili.org/ders/d.en/pragma.html

P.S. As Paul mentioned, you can also use the `-vcg-ast` compiler 
switch (not sure if other compilers than dmd support it): 
https://run.dlang.io/is/AHHwAs


More information about the Digitalmars-d mailing list