Execute Brain****/J: Difference between revisions

m
Fixed syntax highlighting.
No edit summary
m (Fixed syntax highlighting.)
 
(2 intermediate revisions by one other user not shown)
Line 1:
<syntaxhighlight lang="j">require'general/misc/prompt' NB. was require'misc' in j602
<lang J>require'misc'
 
NB. operations
Line 17:
 
NB. buffered io
require'misc'
OBUF=:IBUF=:''
flush=:] [ 3 :0
Line 47 ⟶ 46:
right=: [:/:~/ [:;"1 (#:1 2) <@I.@E."1/ nesting
next=: (1 + 1 { ])`1:`]}
traceNext=: (1 + 1 { ])`1:`]} ([ smoutput) NB. version of next for debugging crashes
 
NB. interpreter
OPCODES=: '><+-.,[]'
OPS=: inc`dec`INC`DEC`OUT`ACC`FIXME`FIXME`NOP
PASS1=: OPS {~ OPCODES i. ([-.-.)&OPCODES
compile=:3 :0
src=. ([-.-.)&OPCODES y
Line 64 ⟶ 61:
step=: [ next ] evoke~ pc { [
 
trace=: [: flush step^:(pc < #@[)^:a:
run=: [: flush step^:(pc < #@[)^:_
 
execute=: 2 }. compile@] run 0 0,0: :[</langsyntaxhighlight>
 
Here is hello world:
 
<langsyntaxhighlight Jlang="j">hello=: 0 :0
+++++ +++++ initialize counter (cell #0) to 10
[ use loop to set the next four cells to 70/100/30/10
Line 93 ⟶ 89:
> + . print '!'
> . print '\n'
)</langsyntaxhighlight>
 
Example use:
<langsyntaxhighlight Jlang="j"> execute hello
Hello World!
 
0 87 100 33 10</langsyntaxhighlight>
 
execute compiles the program, generates an initial state of a blank tape with the data and instruction pointers both being zero, runs the program and then returns as its result the final state of the tape.
Line 107 ⟶ 103:
Or, here is the addDigit program from wikipedia, with explicit compilation and run as separate operations:
 
<langsyntaxhighlight Jlang="j"> (compile ',>++++++[<-------->-],[<+>-]<.') run 0 0
 
23
5
0 30 53 0</langsyntaxhighlight>
 
Here, 2 and 3 were provided as input, and 5 was displayed as the result.
Line 119 ⟶ 115:
Note this implementation encodes branch targets into the compiled code, and that <code>compile</code> assumes that <code>[</code> and <code>]</code> are balanced. Unbalanced brackets are not supported (and will cause the first instruction of the program to be replaced with an unspecified branch instruction).
 
You can also use <code>trace=: [: flush step^:(pc < #@[)^:a:</code>, instead of <code>run</code>. <code>trace</code> takes the same arguments as run, but will return every state the tape went through, instead of the final state. This is mostly interested for understanding the behavior of small programs.
 
When investigating a bug, you can use:
 
<syntaxhighlight lang="j">next=: (1 + 1 { ])`1:`]} ([ smoutput)</syntaxhighlight>
<lang J>next=: traceNext</lang>
 
This means that programs when run (or traced) will display each tape state after it has been generated, which means that when the program crashes you will have displayed a tape state shortly before the crash.
9,476

edits