Advertisement
HwapX

Brainfuck Interpreter

Dec 10th, 2012
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class BFI
  2.     cell_max = 128
  3.     cell_min = -128
  4.     cell_start = 0
  5.     stack = []
  6.     stack_max = 2048
  7.     sp = 0
  8.     code = ''
  9.     cp = 0
  10.     loops = []
  11.     output = ''
  12.     comment = ''
  13.    
  14.     constructor: ->
  15.  
  16.     reset:->
  17.         stack = []
  18.         sp = 0
  19.         loops = []
  20.         output = ''
  21.         comment = ''
  22.         cp = 0
  23.         return
  24.    
  25.     load:(c)->
  26.         code = c
  27.         @reset()
  28.         return
  29.  
  30.     next:->
  31.         if cp >= code.length then return -1
  32.  
  33.         if sp == stack.length then stack.push(cell_start)
  34.  
  35.         switch code.charAt(cp)
  36.             when '+'
  37.                 stack[sp]++
  38.                 if stack[sp] > cell_max then stack[sp] = cell_min
  39.             when '-'
  40.                 stack[sp]--
  41.                 if stack[sp] < cell_min then stack[sp] = cell_max
  42.             when '>'
  43.                 sp++
  44.                 if sp > stack_max then sp = 0
  45.             when '<'
  46.                 sp--
  47.                 if sp < 0 then sp = stack_max
  48.             when '['
  49.                 if not stack[sp] then cp = loopEnd()
  50.                 loops.push(cp)
  51.             when ']'
  52.                 if not loops.length then throw "Found ] when no loop is open - " + cp
  53.                 cp = loops.pop() - 1
  54.             when '.'
  55.                 output += String.fromCharCode(stack[sp])
  56.             when ','
  57.                 stack[sp] = input()
  58.             else
  59.                 comment += code.charAt(cp)
  60.         return cp++
  61.  
  62.     run:(c)->
  63.         if c then @load(c)
  64.         while @next() != -1
  65.             continue
  66.         return output
  67.  
  68.     @run:(c)->
  69.         bfi = new BFI()
  70.         return bfi.run(c);
  71.        
  72.  
  73.     input = ->
  74.         if str = prompt('Input only one char') then return str.charCodeAt(0)
  75.         return 0
  76.  
  77.     loopEnd = ->
  78.         skip = 0
  79.         for i in [(cp + 1)..code.length]
  80.             switch code.charAt(i)
  81.                 when '[' then skip++
  82.                 when ']'
  83.                     if not skip then return i
  84.                     skip--
  85.         throw "end of loop not found - " + cp
  86.  
  87. alert(BFI.run('+++++++++[>++++++++<-]>.+.'))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement