Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 2nd, 2012  |  syntax: None  |  size: 1.87 KB  |  hits: 12  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. #!/usr/bin/env ruby
  2.  
  3. class MRISC
  4.   def run(code)
  5.     tokens = code.gsub(/(\*.*?\*)|[^a-z0-9,-;@\._]/,'').split(';')
  6.     @vars,stack,i = {:_pc=>-1,:_oc=>0},[],0
  7.     tokens.map!{|t| t.chars.first=='@' ? (@vars[t.to_sym]=i-1;nil) : (i+=1;t.split(',').map{|e|numeric?(e) ? e.to_i : e.to_sym})}.compact!
  8.     while @vars[:_pc] < tokens.size-1
  9.       @vars[:_pc] += 1
  10.       @vars[:_oc] += 1
  11.       @vars[:_ss] = stack.size
  12.       raise 'too many operations!' if @vars[:_oc] > 9999
  13.       cmd,a,b,c = tokens[@vars[:_pc]]
  14.       case cmd
  15.         when :let; set(a,b)
  16.         when :out; puts get(a)
  17.         when :dbg; puts a
  18.         when :add; set(a,get(a)+get(b))
  19.         when :sub; set(a,get(a)-get(b))
  20.         when :mul; set(a,get(a)*get(b))
  21.         when :mod; set(a,get(a)%get(b))
  22.         when :div; set(a,get(a)/get(b))
  23.         when :jmp; @vars[:_pc]=get(a)
  24.         when :jis; @vars[:_pc]=get(c) if get(a)<get(b)
  25.         when :jig; @vars[:_pc]=get(c) if get(a)>get(b)
  26.         when :jie; @vars[:_pc]=get(c) if get(a)==get(b)
  27.         when :jiu; @vars[:_pc]=get(c) if get(a)!=get(b)
  28.         when :end; @vars[:_pc]=tokens.size
  29.         when :pus; stack.push(get(a))
  30.         when :pop; set(a,stack.pop)
  31.         else raise "unknown command '#{cmd}' at #{tokens[@vars[:_pc]].join(',')}"
  32.       end
  33.     end
  34.     @vars
  35.   end
  36.  
  37.   private
  38.   def get(s); (@vars.key?(s) ? @vars[s] : numeric?(s) ? s : 0).to_i; end
  39.   def set(s,v); @vars[s] = get(v); end
  40.   def numeric?(n); true if Float(n) rescue false; end
  41. end
  42.  
  43. MRISC.new.run('
  44. *=== Main ===*
  45. let,a,3;            *arg 1 and result*
  46. let,b,5;            *arg 2*
  47. let,@rj,_pc;        *return address*
  48. add,@rj,2;
  49. jmp,@power;         *subroutine call*
  50. out,a;              *print result*
  51. end;
  52. *=== Subroutines ===*
  53. @power;             *calculates pow(a,b) result in a. uses tmp*
  54.   let,tmp,a;
  55.   @power1;
  56.     mul,a,tmp;
  57.     sub,b,1;
  58.     jig,b,1,@power1;
  59.   jmp,@rj;          *return from subroutine*
  60. ')