fork download
  1. #include <iostream>
  2.  
  3. #define MAX_REG 4
  4.  
  5. /*
  6. instruction numbers:
  7. 0 - Halts
  8. 1 - Loads
  9. 2 - Add
  10. 3 - Print
  11. Program Structure
  12.  **bits:
  13. 15 - 12 -> Instruction Number
  14. 11 - 8 -> Register to use
  15. 7 - 0 -> Immediate Value
  16. */
  17. template<typename U>
  18. void print( U && a )
  19. {
  20. std::cout << a << std::endl;
  21. }
  22.  
  23. template< typename T, typename ...U>
  24. void print( T && a, U &&...b )
  25. {
  26. std::cout << a;
  27. print( std::forward<U>( b )... );
  28. }
  29.  
  30. template< typename T, typename ...U>
  31. void emitLn( T && a, U &&...b )
  32. {
  33. print( std::forward<T>( a ), std::forward<U>( b )... );
  34. }
  35.  
  36. int main()
  37. {
  38. int vm_registers[MAX_REG] = { 0 };
  39. int const program_code[] = { 0x109F, 0x11C8, 0x2201, 0x3200, 0x0000 };
  40. int instruction_number, reg_0, reg_1, reg_2;
  41.  
  42. int instruction_pointer = 0, immediate_value = 0;
  43. auto fetch = [&instruction_pointer, &program_code]{
  44. return program_code[instruction_pointer++];
  45. };
  46. auto decode = [&]( uint16_t instrNumber ) mutable -> void {
  47. instruction_number = ( instrNumber & 0xF000 ) >> 12;
  48. reg_0 = ( instrNumber & 0xF00 ) >> 8;
  49. reg_1 = ( instrNumber & 0xF0 ) >> 4;
  50. reg_2 = ( instrNumber & 0xF );
  51. immediate_value = ( instrNumber & 0xFF );
  52. };
  53. auto eval = [&]() mutable -> void{
  54. switch( instruction_number ){
  55. case 0:
  56. emitLn( "halt" );
  57. break;
  58. case 1:
  59. emitLn( "loadi r", reg_0, " #", immediate_value );
  60. vm_registers[reg_0] = immediate_value;
  61. break;
  62. case 2:
  63. emitLn( "add r", reg_0, " r", reg_1, " r", reg_2 );
  64. vm_registers[reg_0] = vm_registers[reg_1] + vm_registers[reg_2];
  65. break;
  66. case 3:
  67. emitLn( "print r", reg_0, "; //" , vm_registers[reg_0] );
  68. break;
  69. }
  70. };
  71. int const code_count = sizeof( program_code ) / sizeof( int );
  72.  
  73. [&]()->void{
  74. while( instruction_pointer < code_count ){
  75. auto instrNumber = fetch();
  76. decode( instrNumber );
  77. eval();
  78. }
  79. }();
  80. return 0;
  81. }
Success #stdin #stdout 0s 3412KB
stdin
Standard input is empty
stdout
loadi r0 #159
loadi r1 #200
add r2 r0 r1
print r2; //359
halt