Macro expansion working properly.
[scheme.forth.jl.git] / src / scheme.4th
index 52fcbcc..ec97f09 100644 (file)
@@ -10,6 +10,7 @@ include float.4th
 include debugging.4th
 
 defer read
+defer expand
 defer eval
 defer print
 
@@ -36,7 +37,7 @@ make-type pair-type
 make-type symbol-type
 make-type primitive-proc-type
 make-type compound-proc-type
-make-type fileport-type
+make-type port-type
 : istype? ( obj type -- obj bool )
     over = ;
 
@@ -51,33 +52,21 @@ variable nextexception
     1 nextexception +!
     does> @ ;
 
-make-exception recoverable-exception
-make-exception unrecoverable-exception
-
-: display-exception-msg ( addr count -- )
+: except-message:
     bold fg red
     ." Exception: "
-    type
-    reset-term ;
-
-: throw" immediate 
-    [compile] s"
+;
 
-    ['] rot , ['] dup ,
+make-exception recoverable-exception
+make-exception unrecoverable-exception
 
-    [compile] if
-        ['] -rot ,
-        ['] display-exception-msg ,
-    [compile] then
-
-    ['] throw ,
-;
+: throw reset-term throw ;
 
 \ }}}
 
 \ ---- List-structured memory ---- {{{
 
-10000 constant scheme-memsize
+20000 constant scheme-memsize
 
 create car-cells scheme-memsize allot
 create car-type-cells scheme-memsize allot
@@ -103,7 +92,7 @@ variable nextfree
     then
 
     nextfree @ scheme-memsize >= if
-        unrecoverable-exception throw s" Out of memory!"
+        except-message: ." Out of memory!" unrecoverable-exception throw
     then
 ;
 
@@ -175,37 +164,6 @@ variable nextfree
 
 \ }}}
 
-\ ---- Port I/O ----  {{{
-
-: fileport>fid ( fileport -- fid )
-    drop ;
-
-: fid>fileport ( fid -- fileport )
-    fileport-type ;
-
-: open-input-file ( addr n -- fileport )
-    r/o open-file drop fid>fileport
-;
-
-: close-port ( fileport -- )
-    fileport>fid close-file drop
-;
-
-objvar console-i/o-port
-0 fileport-type console-i/o-port obj!
-
-objvar current-input-port
-console-i/o-port obj@ current-input-port obj!
-
-: read-port ( fileport -- obj )
-    current-input-port obj!
-    read ;
-
-: read-console ( -- obj )
-    console-i/o-port obj@ read-port ;
-
-\ }}}
-
 \ ---- Pre-defined symbols ---- {{{
 
 objvar symbol-table
@@ -304,13 +262,129 @@ create-symbol ok                ok-symbol
 create-symbol if                if-symbol
 create-symbol lambda            lambda-symbol
 create-symbol λ                 λ-symbol
-create-symbol begin             begin-symbol
+create-symbol eof               eof-symbol
+create-symbol no-match          no-match-symbol
 
 \ Symbol to be bound to welcome message procedure by library
 create-symbol welcome           welcome-symbol
 
 \ }}}
 
+\ ---- Port I/O ----  {{{
+
+( Ports are pairs with the fid in the car and the peek buffer in the cdr. )
+
+: fileport>fid ( fileport -- fid )
+    drop pair-type car drop ;
+
+: get-last-peek ( fileport -- char/nil )
+    drop pair-type cdr ;
+
+: set-last-peek ( char/nil fileport -- )
+    drop pair-type set-cdr!
+;
+
+: fid>fileport ( fid -- fileport )
+    fixnum-type nil cons drop port-type ;
+
+: open-input-file ( addr n -- fileport )
+    r/o open-file drop fid>fileport
+;
+
+: close-port ( fileport -- )
+    fileport>fid close-file drop
+;
+
+objvar console-i/o-port
+0 fixnum-type nil cons drop port-type console-i/o-port obj!
+
+objvar current-input-port
+console-i/o-port obj@ current-input-port obj!
+
+: read-char ( port -- char ) 
+    2dup get-last-peek nil? if
+        2drop
+        2dup console-i/o-port obj@ objeq? if
+            2drop
+            key character-type
+        else
+            fileport>fid pad 1 rot read-file 0= if
+                eof-symbol
+            else
+                pad @ character-type
+            then
+        then
+    else
+        nil 2rot set-cdr!
+    then
+;
+
+: peek-char ( port -- char )
+    2dup get-last-peek nil? if
+        2drop 2dup read-char
+        2dup 2rot set-last-peek
+    else
+        2swap 2drop
+    then
+;
+
+variable read-line-buffer-span
+variable read-line-buffer-offset
+
+( Hack to save original read-line while we transition to new one. )
+: orig-read-line immediate
+    ['] read-line , ;
+
+: read-line ( port -- string )
+
+    2dup get-last-peek
+    nil? if
+        2drop
+        0 read-line-buffer-offset !
+    else
+        2over nil 2swap set-last-peek
+        2dup drop '\n' = if
+            2drop nil nil cons exit
+        else
+            drop pad !
+            1 read-line-buffer-offset !
+        then
+    then
+
+    2dup console-i/o-port obj@ objeq? if
+        2drop
+        pad read-line-buffer-offset @ + 200 expect cr
+        span @ read-line-buffer-offset @ + read-line-buffer-span !
+    else
+        pad read-line-buffer-offset @ + 200 2over fileport>fid orig-read-line
+        drop swap read-line-buffer-offset @ + read-line-buffer-span !
+    then
+
+    nil
+    
+    begin
+        read-line-buffer-span @ 0>
+    while
+        pad read-line-buffer-span @ 1- + @ character-type 2swap cons
+        -1 read-line-buffer-span +!
+    repeat
+
+    nil? if
+        nil cons drop string-type
+    else
+        drop string-type
+    then
+;
+
+: read-port ( fileport -- obj )
+    current-input-port obj!
+    read ;
+
+: read-console ( -- obj )
+    console-i/o-port obj@ read-port ;
+
+\ }}}
+
 \ ---- Environments ---- {{{
 
 : enclosing-env ( env -- env )
@@ -386,24 +460,30 @@ objvar vals
 hide vars
 hide vals
 
+objvar var
+
 : lookup-var ( var env -- val )
+    2over var obj!
     get-vars-vals if
         2swap 2drop car
     else
-        recoverable-exception throw" Tried to read unbound variable."
+        except-message: ." tried to read unbound variable '" var obj@ print ." '." recoverable-exception  throw
     then
 ;
 
 : set-var ( var val env -- )
     >R >R 2swap R> R> ( val var env )
+    2over var obj!
     get-vars-vals if
         2swap 2drop ( val vals )
         set-car!
     else
-        recoverable-exception throw" Tried to set unbound variable."
+        except-message: ." tried to set unbound variable '" var obj@ print ." '." recoverable-exception throw
     then
 ;
 
+hide var
+
 objvar env
 
 : define-var ( var val env -- )
@@ -451,11 +531,11 @@ global-env obj!
 : ensure-arg-count ( args n -- )
     dup 0= if
         drop nil objeq? false = if
-            recoverable-exception throw" Too many arguments for primitive procedure."
+            except-message: ." Too many arguments for primitive procedure." recoverable-exception throw
         then
     else
         -rot nil? if
-            recoverable-exception throw" Too few arguments for primitive procedure."
+            except-message: ." Too few arguments for primitive procedure." recoverable-exception  throw
         then
         
         cdr rot 1- recurse
@@ -465,17 +545,17 @@ global-env obj!
 : ensure-arg-type-and-count ( tn tn-1 ... t2 t1 args n -- )
     dup 0= if
         drop nil objeq? false = if
-            recoverable-exception throw" Too many arguments for primitive procedure."
+            except-message: ." Too many arguments for primitive procedure." recoverable-exception throw
         then
     else
         -rot nil? if
-            recoverable-exception throw" Too few arguments for primitive procedure."
+            except-message: ." Too few arguments for primitive procedure." recoverable-exception throw
         then
 
         2dup cdr 2swap car ( ... t1 n args' arg1 )
         2rot 1- swap 2swap rot ( ... args' n-1 arg1 t1 )
         istype? false = if
-            recoverable-exception throw" Incorrect type for primitive procedure."
+            except-message: ." Incorrect type for primitive procedure." recoverable-exception throw
         then
 
         2drop recurse
@@ -545,7 +625,7 @@ global-env obj!
 
 : ensure-arg-type ( arg type -- arg )
     istype? false = if
-        recoverable-exception throw" Incorrect argument type for primitive procedure."
+        except-message: ." Incorrect argument type for primitive procedure." recoverable-exception throw
     then
 ;
 
@@ -559,6 +639,12 @@ objvar macro-table
 ( Look up macro in macro table. Returns nil if
   no macro is found. )
 : lookup-macro ( name_symbol -- proc )
+
+    symbol-type istype? invert if
+        \ Early exit if argument is not a symbol
+        2drop nil exit
+    then
+    
     macro-table obj@
 
     begin
@@ -648,7 +734,7 @@ parse-idx-stack parse-idx-sp !
         parse-str 160 expect cr
         span @ parse-str-span !
     else
-        parse-str 160 current-input-port obj@ fileport>fid read-line
+        parse-str 160 current-input-port obj@ fileport>fid orig-read-line
         drop swap parse-str-span !
 
         parse-str-span @ 0= and if append-eof then
@@ -1236,12 +1322,12 @@ parse-idx-stack parse-idx-sp !
     cdr ( env args )
 
     nil? if
-        recoverable-exception throw" no arguments to unquote."
+        except-message: ." no arguments to unquote." recoverable-exception throw
     then
 
     2dup cdr
     nil? false = if
-        recoverable-exception throw" too many arguments to unquote."
+        except-message: ." too many arguments to unquote." recoverable-exception throw
     then
 
     2drop car 2swap eval
@@ -1299,12 +1385,12 @@ defer eval-quasiquote-item
     2swap cdr ( env args )
 
     nil? if
-        recoverable-exception throw" no arguments to quasiquote."
+        except-message: ." no arguments to quasiquote." recoverable-exception throw
     then
 
     2dup cdr ( env args args-cdr )
     nil? false = if
-        recoverable-exception throw" too many arguments to quasiquote."
+        except-message: ." too many arguments to quasiquote." recoverable-exception throw
     then
 
     2drop car ( env arg )
@@ -1318,34 +1404,21 @@ defer eval-quasiquote-item
 : definition? ( obj -- obj bool )
     define-symbol tagged-list? ;
 
-: make-lambda ( params body -- lambda-exp )
-    lambda-symbol -2rot cons cons ;
-
-( Handles iterative expansion of defines in
-  terms of nested lambdas. Most Schemes only
-  handle one iteration of expansion! )
-: definition-var-val ( obj -- var val )
-
-    cdr 2dup cdr 2swap car ( val var )
-
-    begin
-        symbol-type istype? false =
-    while
-        2dup cdr 2swap car ( val formals var' )
-        -2rot 2swap ( var' formals val )
-        make-lambda nil cons ( var' val' )
-        2swap ( val' var' )
-    repeat
+: definition-var ( obj -- var )
+    cdr car ;
 
-    2swap car
-;
+: definition-val ( obj -- val )
+    cdr cdr car ;
 
 : eval-definition ( obj env -- res )
-    2dup 2rot ( env env obj )
-    definition-var-val ( env env var val )
-    2rot eval  ( env var val )
+    2swap
+    2over 2over
+    definition-val 2swap
+    eval
 
-    2rot ( var val env )
+    2swap definition-var 2swap
+
+    2rot
     define-var
 
     ok-symbol
@@ -1439,12 +1512,6 @@ hide env
 : lambda-body ( obj -- body )
     cdr cdr ;
 
-: begin? ( obj -- obj bool )
-    begin-symbol tagged-list? ;
-
-: begin-actions ( obj -- actions )
-    cdr ;
-
 : eval-sequence ( explist env -- finalexp env )
     ( Evaluates all bar the final expressions in
       an an expression list. The final expression
@@ -1515,7 +1582,7 @@ hide env
 : flatten-proc-args ( argvals argnames -- argvals' argnames' )
     nil? if
         2over nil? false = if
-            recoverable-exception throw" Too many arguments for compound procedure."
+            except-message: ." Too many arguments for compound procedure." recoverable-exception throw
         else
             2drop
         then
@@ -1532,7 +1599,7 @@ hide env
 
     2over
     nil? if
-        recoverable-exception throw" Too few arguments for compound procedure."
+        except-message: ." Too few arguments for compound procedure." recoverable-exception throw
     else
         cdr
     then
@@ -1567,27 +1634,20 @@ hide env
                 R> drop ['] eval goto-deferred  \ Tail call optimization
             endof
 
-            recoverable-exception throw" Object not applicable."
+            except-message: ." object '" drop print ." ' not applicable." recoverable-exception throw
         endcase
 ;
 
-( Simply evaluates the given procedure with expbody as its argument. )
-: macro-expand ( proc expbody -- result )
-    2swap
-    2dup procedure-body ( expbody proc procbody )
-    -2rot 2dup procedure-params ( procbody expbody proc argnames )
-    -2rot procedure-env ( procbody argnames expbody procenv )
-    
-    -2rot 2swap
-    flatten-proc-args
-    2swap 2rot
-
-    extend-env eval-sequence eval
-;
-
 :noname ( obj env -- result )
     2swap
 
+    \ --- DEBUG ---
+    ( 
+      fg yellow ." Evaluating: " bold 2dup print reset-term
+      space fg green ." PS: " bold depth . reset-term
+      space fg blue  ." RS: " bold RSP@ RSP0 - . reset-term cr
+    )
+
     self-evaluating? if
         2swap 2drop
         exit
@@ -1646,45 +1706,171 @@ hide env
         exit
     then
 
-    begin? if
-        begin-actions 2swap
-        eval-sequence
-        ['] eval goto-deferred
-    then
-
     application? if
 
         2over 2over ( env exp env exp )
         operator ( env exp env opname )
 
-        2dup lookup-macro nil? false = if
-             \ Macro function evaluation
+        2swap eval ( env exp proc )
 
-            ( env exp env opname mproc )
-            2swap 2drop -2rot 2drop cdr ( env mproc body )
+        -2rot ( proc env exp )
+        operands 2swap ( proc operands env )
+        list-of-vals ( proc argvals )
 
-            macro-expand
+        apply
+        exit
+    then
 
-            2swap
-            ['] eval goto-deferred
-        else
-           \ Regular function application
+    except-message: ." tried to evaluate object with unknown type." recoverable-exception throw
+; is eval
 
-            2drop ( env exp env opname )
+\ }}}
 
-            2swap eval ( env exp proc )
+\ ---- Macro Expansion ---- {{{
 
-            -2rot ( proc env exp )
-            operands 2swap ( proc operands env )
-            list-of-vals ( proc argvals )
+( Simply evaluates the given procedure with expbody as its argument. )
+: macro-eval ( proc expbody -- result )
+    2swap
+    2dup procedure-body ( expbody proc procbody )
+    -2rot 2dup procedure-params ( procbody expbody proc argnames )
+    -2rot procedure-env ( procbody argnames expbody procenv )
+    
+    -2rot 2swap
+    flatten-proc-args
+    2swap 2rot
 
-            apply
-            exit
-        then
+    extend-env eval-sequence eval
+;
+
+: expand-macro ( exp -- result )
+    pair-type istype? invert if exit then
+    2dup car symbol-type istype? invert if 2drop exit then
+    
+    lookup-macro nil? if
+        2drop exit then
+
+    2over cdr macro-eval
+
+    2dup no-match-symbol objeq? if
+        2drop exit
+    else
+        2swap 2drop
     then
 
-    recoverable-exception throw" Tried to evaluate object with unknown type."
-; is eval
+    R> drop ['] expand goto-deferred
+;
+
+: expand-quasiquote-item ( exp -- result )
+    nil? if exit then
+
+    unquote? if
+        unquote-symbol 2swap cdr car expand nil cons cons
+        exit
+    then
+
+    unquote-splicing? if
+        unquote-splicing-symbol 2swap cdr car expand nil cons cons
+        exit
+    then
+    
+    pair-type istype? if
+        2dup car recurse
+        2swap cdr recurse
+        cons
+    then
+;
+
+: expand-quasiquote ( exp -- result )
+    quasiquote-symbol 2swap cdr
+
+    expand-quasiquote-item
+
+    cons ;
+
+: expand-definition ( exp -- result )
+    define-symbol 2swap
+
+    2dup definition-var
+    2swap definition-val expand
+    nil ( define var val' nil )
+
+    cons cons cons ;
+
+: expand-assignment ( exp -- result )
+    set!-symbol 2swap
+
+    2dup assignment-var
+    2swap assignment-val expand
+    nil ( define var val' nil )
+
+    cons cons cons ;
+
+: expand-list ( exp -- res )
+    nil? if exit then
+
+    2dup car expand
+    2swap cdr recurse
+
+    cons ;
+
+: macro-definition-nameparams
+    cdr car ;
+
+: expand-define-macro ( exp -- res )
+    define-macro-symbol 2swap
+    2dup macro-definition-nameparams
+    2swap macro-definition-body expand-list
+
+    cons cons ;
+
+: expand-lambda ( exp -- res )
+    lambda-symbol 2swap
+    2dup lambda-parameters
+    2swap lambda-body expand-list
+
+    cons cons ;
+
+: expand-if ( exp -- res )
+    if-symbol 2swap
+    
+    2dup if-predicate expand
+    2swap 2dup if-consequent expand
+    2swap if-alternative none? if
+        2drop nil
+    else
+        expand nil cons
+    then
+
+    cons cons cons ;
+
+: expand-application ( exp -- res )
+    2dup operator expand
+    2swap operands expand-list
+
+    cons ;
+
+:noname ( exp -- result )
+    expand-macro
+
+    self-evaluating? if exit then
+
+    quote? if exit then
+
+    quasiquote? if expand-quasiquote exit then
+
+    definition? if expand-definition exit then
+
+    assignment? if expand-assignment exit then
+
+    macro-definition? if expand-define-macro exit then
+
+    lambda? if expand-lambda exit then
+
+    if? if expand-if exit then
+
+    application? if expand-application exit then
+
+; is expand
 
 \ }}}
 
@@ -1780,8 +1966,9 @@ hide env
     primitive-proc-type istype? if printprim exit then
     compound-proc-type istype? if printcomp exit then
     none-type istype? if printnone exit then
+    port-type istype? if printport exit then
 
-    recoverable-exception throw" Tried to print object with unknown type."
+    except-message: ." tried to print object with unknown type." recoverable-exception throw
 ; is print
 
 \ }}}
@@ -1808,6 +1995,7 @@ variable gc-stack-depth
     string-type istype? if true exit then
     symbol-type istype? if true exit then
     compound-proc-type istype? if true exit then
+    port-type istype? if true exit then
 
     false
 ;
@@ -1874,6 +2062,7 @@ variable gc-stack-depth
 
     symbol-table obj@ gc-mark-obj
     macro-table obj@ gc-mark-obj
+    console-i/o-port obj@ gc-mark-obj
     global-env obj@ gc-mark-obj
 
     depth gc-stack-depth @ do
@@ -1892,24 +2081,6 @@ variable gc-stack-depth
 
 \ ---- Loading files ---- {{{
 
-: charlist>cstr ( charlist addr -- n )
-
-    dup 2swap ( origaddr addr charlist )
-
-    begin 
-        nil? false =
-    while
-        2dup cdr 2swap car 
-        drop ( origaddr addr charlist char )
-        -rot 2swap ( origaddr charlist addr char )
-        over !
-        1+ -rot ( origaddr nextaddr charlist )
-    repeat
-
-    2drop ( origaddr finaladdr ) 
-    swap -
-;
-
 : load ( addr n -- finalResult )
     open-input-file
 
@@ -1927,6 +2098,8 @@ variable gc-stack-depth
 
         2swap 2drop ( port obj )
 
+        expand
+
         global-env obj@ eval ( port res )
     again
 ;
@@ -1955,6 +2128,8 @@ variable gc-stack-depth
         true exit
     then
 
+    expand
+
     global-env obj@ eval
 
     fg cyan ." ; " print reset-term
@@ -1963,7 +2138,6 @@ variable gc-stack-depth
 ;
 
 : repl
-
     empty-parse-str
 
     enable-gc