Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <div id='content'>
  <pre style='flex: 1;' id="output"></pre>
  <div style='flex: 2;'>
    <textarea id="program" >
MOV I, NEXT     ;0 index to loop counter
.D 10           ;1
ADD [I], NEXT   ;2 decrement loop counter
.D -1           ;3
CMP [I], NEXT   ;4 compare to zero
.D 0            ;5
IFGT ADD PC, NEXT ;6 if it was greater than zero, jump back to decrement
.D -6           ;7
ADD PC, NEXT    ;8 jump over data
.D 1            ;9
.D 3            ;10 data: loop counter
ADD A,A         ;11 nop
ADD A,A         ;12 nop
    </textarea>
  </div>
  <div style='flex 1;'>output <button id="clr_btn">clr</button><br><textarea id="output_buffer"></textarea></div>

  <pre id="test_results"></pre>
</div>
<p>TODO: add a way to halt; code editor with line numbers; enforce bit widths</p>

<!--

MOV I, NEXT     ;0 index to loop counter
.D 10           ;1
ADD [I], NEXT   ;2 decrement loop counter
.D -1           ;3
CMP [I], NEXT   ;4 compare to zero
.D 0            ;5
IFGT ADD PC, NEXT ;6 if it was greater than zero, jump back 4
.D -4           ;7
ADD PC, 2       ;8
.D 2            ;9
.D 3            ;10 data: loop counter

MOV I, 16       ;6  index to string pointer
MOV I, [I]      ;7  index to pointer value
MOV A, [I]      ;8  get character from string
CMP A, 0        ;9  compare character to NULL
IFEQ ADD PC, 6  ;10 if equal to null, jump out of loop
MOV I, 999      ;11 index to memory mapped output buffer
MOV [I], A      ;12 write character out
MOV I, 16       ;13 index back to pointer
ADD [I], 1      ;14 increment pointer
ADD PC, -9      ;15 jump back to do next character


.D 17           ;16 string pointer
.D 104          ;17 first character of string
.D 101
.D 108
.D 108
.D 111
.D 32
.D 119
.D 111
.D 114
.D 108
.D 100
.D 0
!-->
              
            
!

CSS

              
                * {
  background-color: #222;
  color: white;
}

#content {
  display: flex;
  width: 100%;
  border: solid thin gray;
  align-items: stretch;
  
}

#output {
  width: 100%;
  margin: 0;
}

#program {
  width: calc( 100% - 2px );
  height: calc( 100% - 2px );
}

#output_buffer {
  width: calc( 100% - 2px );
  height: calc( 100% - 2px );
}

* {
   border: solid thin gray;
}

              
            
!

JS

              
                function log(msg) {
  document.getElementById("output").innerText += msg + "\n";
}
function clear() {
  document.getElementById("output").innerText = ''
}

run_program();
document.getElementById("program").addEventListener('input', (ev) => {
  clear()
  run_program()
})

function run_program() {
  const text = document.getElementById("program").value;
  const raw_lines = text.split("\n");
  const lines = raw_lines.filter(line => line.trim().length !== 0);

  let state = { A: 0, I: 0, PC: 0, GT: false, LT: false, EQ: false, ram: make_empty_ram(lines.length)}
  
  // step through each line and if its a data directive, set the value in ram to that
  let index = 0
  lines.forEach((line) => {
    if(line.match(/^\.D/)) {
      state.ram[index] = Number.parseInt(line.match(/(?:\.D\s+)(-?\d+)/)[1])
      index += 1
    } else if(isMacro(line)) {
      index += expandMacro(line, state.ram, index)
    } else {
      state.ram[index] = line.trim()
      index += 1
    }
  })
  
  let count = 0
  let success = true
  while( count < 500 && state.PC < lines.length && success) {
    success = parse_line(lines[state.PC], state)
    count += 1
  }
  log(state_to_string(state))
}

function isMacro(line) {
  if(line.match(/^LDA/)) { 
    return true
  }
  return false
}

function expandMacro(line, ram, index) {
  if(line.match(/^LDA/)) {
    const [match, target] = line.match(/^LDA\s(.+)/)
    ram[index] = `MOV I, ${target}`
    ram[index + 1] = 'MOV A, [I]'
    return 2
  }
  return 0
}

function parse_line(line, state) {
  // CONDITION_OR_NIL COMMAND DST_OR_LEFT COMMA SRC_RIGHT_OR_IMM
  const match_attempt = line.trim().match(/(IFGT|IFLT|IFEQ)?\s*(MOV|ADD|CMP|NOR)\s+(A|I|PC|\[I\])\s*,\s*(A|PC|\[I\]|NEXT)/)
  if( !match_attempt) {
    log(`ERROR: could not match: ${line}`)
    return false
  }
  const [entire_match, conditional, command, destination, source] = match_attempt
    
  do_instruction(conditional, command, destination, source, state)
  log(`${entire_match}\t;${state_to_string(state)}`)
  return true
}

function state_to_string(state) {
  return `A:${state.A} I:${state.I} PC:${state.PC}` +
    ` GT:${state.GT?1:0} EQ:${state.EQ?1:0} LT:${state.LT?1:0}` //+
    //` \tRAM:${state.ram.join(',')}`
}

function make_empty_ram(len) {
  return new Array(len).fill(0)
}

/* 
commands
MOV dst, src
MOV dst, imm
ADD dst, src
ADD dst, imm
NOR dst, src
NOR dst, imm
CMP left, right
CMP left, imm

all commands may be preceded by one of:
IFGT
IFLT
IFEQ

parameters:
dst & left, one of: A, I, [I], PC
src & right, one of: A, [I], PC
imm: sign extended integer

machine state:
memory, array of 8bit numbers
registers: A, I, and PC
flags: GT, LT, and EQ

grammar:
CONDITION_OR_NIL COMMAND DST_OR_LEFT COMMA SRC_RIGHT_OR_IMM
*/
const grmr = [
  ['IFGT', 'IFLT', 'IFEQ', ''],
  ['MOV', 'ADD', 'NOR', 'CMP'],
  ['A', 'I', '[I]', 'PC'],
  [','],
  ['A', '[I]', 'PC', 'NEXT']
]

function do_instruction(conditional, command, destination, source, state) {
  if(conditional) {
    // if its a conditional and it fails, then we need to advance the PC (ie: do a NOP)
    // return if condition isn't met
    if(conditional == 'IFGT' && !state.GT) {
      state.PC += (source == 'NEXT') ? 2 : 1
      return;
    }
    if(conditional == 'IFLT' && !state.LT) {
      state.PC += (source == 'NEXT') ? 2 : 1
      return;
    }
    if(conditional == 'IFEQ' && !state.EQ) {
      state.PC += (source == 'NEXT') ? 2 : 1
      return;
    }
  }
  // either its a normal command or a successful conditional
  state.PC += 1

  const src = make_src( source, state)
  const dest = make_dest( destination, state)
  do_command( command, dest, src, state)
  
  // if source is NEXT, we need to skip over that too
  if(source == 'NEXT') {
    state.PC += 1
  }
}

function make_src(source, state) {
  if( source == 'A' ||
      source == 'PC' ) {
    return { get: () => state[source]}
  } else if( source == '[I]') {
    return { get: () => read_ram(state) }
  } else { // immediate 
    //return { get: () => Number.parseInt(source)}
    return { get: () => ram_at_PC(state) }
  }
}

function make_dest(destination, state) {
  if( destination == 'A' ||
      destination == 'I' ||
      destination == 'PC' ) {
    return { get: () => state[destination], set: (v) => {state[destination] = v}}
  } else if( destination == '[I]') {
    return { get: () => read_ram(state),
             set: (v) => write_ram(state, v)
           }
  }
}

function to_address(x) {
  return x // not sure why i needed this method
}

function read_ram(state) {
  // TODO catch MMIO here!
  return state.ram[to_address(state.I)]
}

function ram_at_PC(state) {
  return state.ram[to_address(state.PC)]
}

function write_ram(state, val) {
  // Memory mapped IO:
  // address 999 is 'output ascii character'
  if(state.I == 999) {
    document.getElementById("output_buffer").value += String.fromCharCode(val)
    return
  }
  state.ram[to_address(state.I)] = val
}

function do_command(command, dest, src, state) {
  // using the src and dest objects, do the work
  const src_val = src.get()
  const dest_val = dest.get()
  if(command == 'MOV') {
    dest.set(src_val)
  } else if (command == 'ADD') {
    dest.set(dest_val + src_val)
  } else if (command == 'NOR') {
    dest.set( ~(dest_val | src_val))
  } else { // command is CMP
    state.GT = dest_val > src_val
    state.LT = dest_val < src_val
    state.EQ = dest_val == src_val
  }
}

// clear output_buffer button
document.getElementById("clr_btn").addEventListener('click', (ev) => {
  document.getElementById("output_buffer").value = "" 
})

              
            
!
999px

Console