RSP0 and PSP0 now constants. Closes #4.
[forth.jl.git] / src / forth.jl
index 7c0fea8..fb7121c 100644 (file)
@@ -36,16 +36,14 @@ primNames = Array{ASCIIString,1}()
 # Built-in variables
 
 nextVarAddr = 1
-RSP0 = nextVarAddr; nextVarAddr += 1
-PSP0 = nextVarAddr; nextVarAddr += 1
 HERE = nextVarAddr; nextVarAddr += 1
 LATEST = nextVarAddr; nextVarAddr += 1
 
-mem[RSP0] = nextVarAddr              # bottom of RS
-mem[PSP0] = mem[RSP0] + size_RS      # bottom of PS
-TIB = mem[PSP0] + size_PS            # address of terminal input buffer
-mem[HERE] = TIB + size_TIB           # location of bottom of dictionary
-mem[LATEST] = 0                      # no previous definition
+RSP0 = nextVarAddr                  # bottom of RS
+PSP0 = RSP0 + size_RS               # bottom of PS
+TIB = PSP0 + size_PS                # address of terminal input buffer
+mem[HERE] = TIB + size_TIB          # location of bottom of dictionary
+mem[LATEST] = 0                     # no previous definition
 
 DICT = mem[HERE] # Save bottom of dictionary as constant
 
@@ -56,7 +54,7 @@ type Reg
     IP::Int64   # Instruction pointer
     W::Int64    # Working register
 end
-reg = Reg(mem[RSP0], mem[PSP0], 0, 0)
+reg = Reg(RSP0, PSP0, 0, 0)
 
 # Stack manipulation functions
 
@@ -66,8 +64,8 @@ type ReturnStackUnderflow <: Exception end
 Base.showerror(io::IO, ex::ParamStackUnderflow) = print(io, "Parameter stack underflow.")
 Base.showerror(io::IO, ex::ReturnStackUnderflow) = print(io, "Return stack underflow.")
 
-getRSDepth() = reg.RSP - mem[RSP0]
-getPSDepth() = reg.PSP - mem[PSP0]
+getRSDepth() = reg.RSP - RSP0
+getPSDepth() = reg.PSP - PSP0
 
 function ensurePSDepth(depth::Int64)
     if getPSDepth()<depth
@@ -108,6 +106,7 @@ end
 # Handy functions for adding/retrieving strings to/from memory.
 
 getString(addr::Int64, len::Int64) = ASCIIString([Char(c) for c in mem[addr:(addr+len-1)]])
+
 function putString(str::ASCIIString, addr::Int64)
     mem[addr:(addr+length(str)-1)] = [Int64(c) for c in str]
 end
@@ -116,12 +115,18 @@ end
 
 function defPrim(f::Function; name="nameless")
     push!(primitives, f)
-    push!(primNames, replace(replace(name, "\004", "EOF"), "\n", "\\n"))
+    push!(primNames, replace(name, "\004", "EOF"))
 
     return -length(primitives)
 end
 
-callPrim(addr::Int64) = primitives[-addr]()
+function callPrim(addr::Int64)
+    if addr >=0 || -addr>length(primitives)
+        error("Attempted to execute non-existent primitive at address $addr.")
+    else
+        primitives[-addr]()
+    end
+end
 getPrimName(addr::Int64) = primNames[-addr]
 
 # Word creation functions
@@ -230,8 +235,9 @@ end)
 
 HERE_CFA = defExistingVar("HERE", HERE)
 LATEST_CFA = defExistingVar("LATEST", LATEST)
-PSP0_CFA = defExistingVar("PSP0", PSP0)
-RSP0_CFA = defExistingVar("RSP0", RSP0)
+
+PSP0_CFA = defConst("PSP0", PSP0)
+RSP0_CFA = defConst("RSP0", RSP0)
 
 defConst("DOCOL", DOCOL)
 defConst("DOCON", DOCON)
@@ -560,7 +566,7 @@ RSPFETCH = defPrimWord("RSP@", () -> begin
 end)
 
 RSPSTORE = defPrimWord("RSP!", () -> begin
-    RSP = popPS()
+    reg.RSP = popPS()
     return NEXT
 end)
 
@@ -577,7 +583,7 @@ PSPFETCH = defPrimWord("PSP@", () -> begin
 end)
 
 PSPSTORE = defPrimWord("PSP!", () -> begin
-    PSP = popPS()
+    reg.PSP = popPS()
     return NEXT
 end)
 
@@ -598,7 +604,14 @@ end)
 sources = Array{Any,1}()
 currentSource() = sources[length(sources)]
 
-EOF_CFA = defConst("EOF", 4)
+EOF = defPrimWord("\x04", () -> begin
+    close(pop!(sources))
+    if !isempty(sources)
+        return NEXT
+    else
+        return 0
+    end
+end)
 
 EMIT = defPrimWord("EMIT", () -> begin
     print(Char(popPS()))
@@ -616,7 +629,7 @@ EXPECT = defPrimWord("EXPECT", () -> begin
         putString(line[1:mem[SPAN]], addr)
     else
         mem[SPAN] = 1
-        mem[addr] = EOF
+        mem[addr] = 4 # eof
     end
 
     return NEXT
@@ -679,7 +692,7 @@ TOCFA = defPrimWord(">CFA", () -> begin
     return NEXT
 end)
 
-TODFA = defWord(">DFA", [TOCFA, INCR, EXIT])
+TOPFA = defWord(">PFA", [TOCFA, INCR, EXIT])
 
 # Branching
 
@@ -721,8 +734,9 @@ end)
 # Outer interpreter
 
 TRACE = defPrimWord("TRACE", () -> begin
-    print("RS: "); printRS()
+    println("reg.W: $(reg.W) reg.IP: $(reg.IP)")
     print("PS: "); printPS()
+    print("RS: "); printRS()
     print("[paused]")
     readline()
 
@@ -749,7 +763,7 @@ NUMTIB, NUMTIB_CFA = defNewVar("#TIB", 0)
 TOIN, TOIN_CFA = defNewVar(">IN", 0)
 
 QUERY = defWord("QUERY",
-    [TIB_CFA, LIT, 80, EXPECT,
+    [TIB_CFA, LIT, 160, EXPECT,
     SPAN_CFA, FETCH, NUMTIB_CFA, STORE,
     LIT, 0, TOIN_CFA, STORE,
     EXIT])
@@ -767,11 +781,16 @@ WORD = defPrimWord("WORD", () -> begin
 
     # Start reading in word
     count = 0
-    while (mem[TOIN]<mem[NUMTIB] && mem[TIB+mem[TOIN]] != delim)
+    while (mem[TOIN]<mem[NUMTIB])
         mem[addr] = mem[TIB+mem[TOIN]]
+        mem[TOIN] += 1
+
+        if (mem[addr] == delim)
+            break
+        end
+
         count += 1
         addr += 1
-        mem[TOIN] += 1
     end
 
     # Record count
@@ -781,6 +800,37 @@ WORD = defPrimWord("WORD", () -> begin
     return NEXT
 end)
 
+PARSE = defPrimWord("PARSE", () -> begin
+    delim = popPS()
+
+    # Chew up initial occurrences of delim
+    addr = mem[HERE]
+
+    # Start reading input stream
+    count = 0
+    while (mem[TOIN]<mem[NUMTIB])
+        mem[addr] = mem[TIB+mem[TOIN]]
+        mem[TOIN] += 1
+
+        if (mem[addr] == delim)
+            break
+        end
+
+        count += 1
+        addr += 1
+    end
+
+    pushPS(addr)
+    pushPS(count)
+
+    return NEXT
+end)
+
+BYE = defPrimWord("BYE", () -> begin
+    println("Bye!")
+    return 0
+end)
+
 STATE, STATE_CFA = defNewVar("STATE", 0)
 
 INTERPRET = defWord("INTERPRET",
@@ -789,29 +839,30 @@ INTERPRET = defWord("INTERPRET",
     DUP, FETCH, ZE, ZBRANCH, 3,
         DROP, EXIT, # Exit if TIB is exhausted
 
-    STATE_CFA, FETCH, ZBRANCH, 27,
+    STATE_CFA, FETCH, ZBRANCH, 31,
         # Compiling
-        DUP, FIND, ZBRANCH, 17,
+        DUP, FIND, QDUP, ZBRANCH, 19,
 
             # Found word. 
+            SWAP, DROP,
             DUP, TOCFA, SWAP, INCR, FETCH, LIT, F_IMMED, AND, ZBRANCH, 4,
                 # Immediate: Execute!
-                EXECUTE, BRANCH, -30,
+                EXECUTE, BRANCH, -33,
 
                 # Not immediate: Compile!
-                COMMA, BRANCH, -33,
+                COMMA, BRANCH, -36,
 
             # No word found, parse number
-            NUMBER, BTICK, LIT, COMMA, BRANCH, -39,
+            NUMBER, BTICK, LIT, COMMA, COMMA, BRANCH, -43,
         
        # Interpreting
-        DUP, FIND, ZBRANCH, 5,
+        DUP, FIND, QDUP, ZBRANCH, 7,
 
             # Found word. Execute!
-            TOCFA, EXECUTE, BRANCH, -47,
+            SWAP, DROP, TOCFA, EXECUTE, BRANCH, -54,
 
             # No word found, parse number and leave on stack
-            NUMBER, BRANCH, -50,
+            NUMBER, BRANCH, -57,
     EXIT]
 )
 
@@ -824,19 +875,21 @@ PROMPT = defPrimWord("PROMPT", () -> begin
 end)
 
 QUIT = defWord("QUIT",
-    [RSP0_CFA, RSPSTORE,
+    [LIT, 0, STATE_CFA, STORE,
+    LIT, 0, NUMTIB_CFA, STORE,
+    RSP0_CFA, RSPSTORE,
     QUERY,
     INTERPRET, PROMPT,
     BRANCH,-4])
 
-BYE = defPrimWord("BYE", () -> begin
-    return 0
-end)
+ABORT = defWord("ABORT",
+    [PSP0_CFA, PSPSTORE, QUIT])
 
 INCLUDE = defPrimWord("INCLUDE", () -> begin
+    pushPS(32)
     callPrim(mem[WORD])
-    wordLen = popPS()
-    wordAddr = popPS()
+    wordAddr = popPS()+1
+    wordLen = mem[wordAddr-1]
     word = getString(wordAddr, wordLen)
 
     push!(sources, open(word, "r"))
@@ -850,7 +903,6 @@ end)
 # Compilation
 
 HEADER = defPrimWord("HEADER", () -> begin
-
     wordAddr = popPS()+1
     wordLen = mem[wordAddr-1]
     word = getString(wordAddr, wordLen)
@@ -877,13 +929,13 @@ HIDDEN = defPrimWord("HIDDEN", () -> begin
 end)
 
 HIDE = defWord("HIDE",
-    [WORD,
+    [LIT, 32, WORD,
     FIND,
     HIDDEN,
     EXIT])
 
 COLON = defWord(":",
-    [WORD,
+    [LIT, 32, WORD,
     HEADER,
     LIT, DOCOL, COMMA,
     LATEST_CFA, FETCH, HIDDEN,
@@ -902,9 +954,6 @@ IMMEDIATE = defPrimWord("IMMEDIATE", () -> begin
     return NEXT
 end, flags=F_IMMED)
 
-TICK = defWord("'",
-    [WORD, FIND, TOCFA, EXIT])
-
 
 #### VM loop ####
 
@@ -916,7 +965,7 @@ elseif isfile(Pkg.dir("forth/src/lib.4th"))
     initFileName = Pkg.dir("forth/src/lib.4th")
 end
 
-function run(;initialize=false)
+function run(;initialize=true)
     # Begin with STDIN as source
     push!(sources, STDIN)
 
@@ -938,25 +987,22 @@ function run(;initialize=false)
     # Everyting else is simply a consequence of this loop!
     jmp = NEXT
     while jmp != 0
-#        try
-            println("Entering prim $(getPrimName(jmp))")
+        try
+            #println("Entering prim $(getPrimName(jmp))")
             jmp = callPrim(jmp)
 
-#        catch ex
-#            showerror(STDOUT, ex)
-#            println()
-#
-#            while !isempty(sources) && currentSource() != STDIN
-#                close(pop!(sources))
-#            end
-#
-#            mem[STATE] = 0
-#            mem[NUMTIB] = 0
-#            reg.PSP = mem[PSP0]
-#            reg.RSP = mem[RSP0]
-#            reg.IP = QUIT + 1
-#            jmp = NEXT
-#        end
+        catch ex
+            showerror(STDOUT, ex)
+            println()
+
+            while !isempty(sources) && currentSource() != STDIN
+                close(pop!(sources))
+            end
+
+            # QUIT
+            reg.IP = ABORT + 1
+            jmp = NEXT
+        end
     end
 end
 
@@ -996,11 +1042,11 @@ function dump(startAddr::Int64; count::Int64 = 100, cellsPerLine::Int64 = 10)
 end
 
 function printPS()
-    count = reg.PSP - mem[PSP0]
+    count = reg.PSP - PSP0
 
     if count > 0
         print("<$count>")
-        for i in (mem[PSP0]+1):reg.PSP
+        for i in (PSP0+1):reg.PSP
             print(" $(mem[i])")
         end
         println()
@@ -1010,11 +1056,11 @@ function printPS()
 end
 
 function printRS()
-    count = reg.RSP - mem[RSP0]
+    count = reg.RSP - RSP0
 
     if count > 0
         print("<$count>")
-        for i in (mem[RSP0]+1):reg.RSP
+        for i in (RSP0+1):reg.RSP
             print(" $(mem[i])")
         end
         println()