all repos — min @ f6d70d57fdabbe5f68ea66738ce0598a46c6cdbc

A small but practical concatenative programming language.

Refactoring.
h3rald h3rald@h3rald.com
Sat, 22 Oct 2016 14:00:46 +0200
commit

f6d70d57fdabbe5f68ea66738ce0598a46c6cdbc

parent

14d4c4a3e87bcea1940456a4306191125f896698

6 files changed, 36 insertions(+), 82 deletions(-)

jump to
M core/interpreter.nimcore/interpreter.nim

@@ -139,7 +139,6 @@ trace: trace,

stackcopy: stackcopy, scope: scope, debugging: debugging, - unsafe: false, currSym: MinValue(column: 1, line: 1, kind: minSymbol, symVal: "") ) return i

@@ -174,8 +173,6 @@ stderr.writeLine sym.formatTrace

proc error(i: In, message: string) = stderr.writeLine i.currSym.formatError(message) - -#template execute(i: In, body: untyped) = proc open*(i: In, stream:Stream, filename: string) = i.filename = filename

@@ -211,35 +208,13 @@ let sigil = "" & symbol[0]

let found = i.scope.hasSymbol(symbol) if found: let sym = i.scope.getSymbol(symbol) - if i.unsafe: - i.apply(sym) - #if i.unsafe: - #let stack = i.stack - #try: - # i.apply(sym) - #except: - # echo "yeah!" - # i.stack = stack - # raise - else: - #i.execute: - i.apply(sym) + i.apply(sym) else: let found = i.scope.hasSigil(sigil) if symbol.len > 1 and found: let sig = i.scope.getSigil(sigil) let sym = symbol[1..symbol.len-1] i.stack.add(MinValue(kind: minString, strVal: sym)) - #if i.unsafe: - #let stack = i.stack - #try: - # i.apply(sig) - #except: - # echo "yup!" - # i.stack = stack - # raise - #else: - #i.execute: i.apply(sig) else: raiseUndefined("Undefined symbol '$1' in scope '$2'" % [val.symVal, i.scope.fullname])

@@ -263,7 +238,7 @@ return i.stack[i.stack.len-1]

else: raiseEmptyStack() -proc interpret*(i: In) {.gcsafe.}= +proc interpret*(i: In): MinValue {.gcsafe, discardable.} = var val: MinValue while i.parser.token != tkEof: if i.trace.len == 0:

@@ -285,6 +260,8 @@ i.stack = i.stackcopy

i.error(msg) i.stackTrace raise MinTrappedException(msg: msg) + if i.stack.len > 0: + return i.stack[i.stack.len - 1] proc unquote*(i: In, name: string, q: var MinValue) = i.createScope(name, q):

@@ -292,35 +269,21 @@ for v in q.qVal:

i.push v proc eval*(i: In, s: string, name="<eval>") = - #let fn = i.filename - #try: - var i2 = i.copy(name) - i2.open(newStringStream(s), name) - discard i2.parser.getToken() - i2.interpret() - i.trace = i2.trace - i.stackcopy = i2.stackcopy - i.stack = i2.stack - i.scope = i2.scope - #except: - # stderr.writeLine getCurrentExceptionMsg() - # raise - #finally: - # i.filename = fn + var i2 = i.copy(name) + i2.open(newStringStream(s), name) + discard i2.parser.getToken() + i2.interpret() + i.trace = i2.trace + i.stackcopy = i2.stackcopy + i.stack = i2.stack + i.scope = i2.scope proc load*(i: In, s: string) = - #let fn = i.filename - #try: - var i2 = i.copy(s) - i2.open(newStringStream(s.readFile), s) - discard i2.parser.getToken() - i2.interpret() - i.trace = i2.trace - i.stackcopy = i2.stackcopy - i.stack = i2.stack - i.scope = i2.scope - #except: - # stderr.writeLine getCurrentExceptionMsg() - # raise - #finally: - # i.filename = fn + var i2 = i.copy(s) + i2.open(newStringStream(s.readFile), s) + discard i2.parser.getToken() + i2.interpret() + i.trace = i2.trace + i.stackcopy = i2.stackcopy + i.stack = i2.stack + i.scope = i2.scope
M core/parser.nimcore/parser.nim

@@ -99,7 +99,6 @@ currSym*: MinValue

filename*: string debugging*: bool evaluating*: bool - unsafe*: bool MinParsingError* = ref object of ValueError MinUndefinedError* = ref object of ValueError MinEmptyStackError* = ref object of ValueError
M lib/min_lang.nimlib/min_lang.nim

@@ -280,7 +280,6 @@ .symbol("publish") do (i: In):

var qscope, str: MinValue i.reqQuotationAndStringLike qscope, str let sym = str.getString - #TODO Check for sealed if qscope.scope.symbols.hasKey(sym) and qscope.scope.symbols[sym].sealed: raiseUndefined("Attempting to redefine sealed symbol '$1' on scope '$2'" % [sym, qscope.scope.name]) qscope.scope.symbols[sym] = i.scope.getSymbol(sym)

@@ -317,12 +316,10 @@ for s in scope.scope.symbols.keys:

symbols.add s.newVal i.push symbols.newVal - # ("SomeError" "message") .symbol("raise") do (i: In): var err: MinValue i.reqDictionary err if err.dhas("error".newSym) and err.dhas("message".newSym): - # TODO rewrite as dictionary! raiseRuntime("($1) $2" % [err.dget("error".newVal).getString, err.dget("message".newVal).getString], err.qVal) else: raiseInvalid("Invalid error dictionary")

@@ -367,20 +364,17 @@ final = prog.qVal[2]

hasFinally = true if (not code.isQuotation) or (hasCatch and not catch.isQuotation) or (hasFinally and not final.isQuotation): raiseInvalid("Quotation must contain at one quotation") - i.unsafe = true try: i.unquote("<try-code>", code) except MinRuntimeError: if not hasCatch: return - i.unsafe = false let e = (MinRuntimeError)getCurrentException() i.push e.qVal.newVal i.unquote("<try-catch>", catch) except: if not hasCatch: return - i.unsafe = false let e = getCurrentException() var res = newSeq[MinValue](0) let err = regex.replace($e.name, ":.+$", "")
M minim.nimminim.nim

@@ -153,6 +153,19 @@ stderr.writeLine("Error - Cannot read from "& filename)

stderr.flushFile() minimStream(stream, filename, debugging) +proc printResult(i: In, res: MinValue) = + if res.isNil: + return + if i.stack.len > 0: + let n = $i.stack.len + if res.isQuotation and res.qVal.len > 1: + echo "{$1} -> (" % n + for item in res.qVal: + echo " " & $item + echo " ".repeat(n.len) & " )" + else: + echo "{$1} -> $2" % [$i.stack.len, $i.stack[i.stack.len - 1]] + proc minimRepl*(i: var MinInterpreter) = i.stdLib() var s = newStringStream("")

@@ -174,23 +187,9 @@ i.parser.buf = $i.parser.buf & $line

i.parser.bufLen = i.parser.buf.len discard i.parser.getToken() try: - i.interpret() + i.printResult i.interpret() except: discard - #stderr.writeLine getCurrentExceptionMsg() - finally: - if i.stack.len > 0: - let last = i.stack[i.stack.len - 1] - let n = $i.stack.len - if last.isQuotation and last.qVal.len > 1: - echo "{$1} -> (" % n - for item in last.qVal: - echo " " & $item - echo " ".repeat(n.len) & " )" - else: - echo "{$1} -> $2" % [$i.stack.len, $i.stack[i.stack.len - 1]] - else: - echo "{0} --" proc minimRepl*(debugging = false) = var i = newMinInterpreter(debugging)
M minim.vimminim.vim

@@ -12,7 +12,7 @@ setl iskeyword+=?,$,+,*,/,%,=,>,<,&,-,',.,:,~,!

setl iskeyword+=^ setl iskeyword+=@ -syntax keyword minimDefaultSymbol ! != $ & ' * + - % ^ -> . .. / : < <= == => =~ > >= @ ROOT aes and append apply ask at atime b bind bool bool? bury1 bury2 bury3 c call call! capitalize case cd chmod choose clear-stack column-print concat confirm cons cp cpu crypto ctime datetime ddel debug debug? decode decrypt define define* delete dget dictionary? dig1 dig2 dig3 dip dir? dirname div dprint dprint! dset dump-stack dup dupd echo encode encrypt env? eq eval even? exit fappend file? filename filter first float float? foreach fperms fread from-json format-error fs fsize fstats ftype fwrite gets get-stack getenv gt gte hardlink hidden? i id ifte import include indent inspect int int? interpolate interval io join k keys length linrec load load-symbol logic lowercase ls ls-r lt lte map match md5 mkdir mod module mtime mv newline not noteq now num number? odd? or os password pop popd pred prepend print print! prompt publish puts puts! putenv q quit quotation? quote raise regex remove-symbol repeat replace rest rm rmdir run save-symbol scope scope? seal search select set-stack sha1 sha224 sha256 sha384 sha512 sigils sip size sleep sort source split startup stored-symbols str string string? strip succ swap swapd swons symbols symlink symlink? sys system take tformat time timeinfo times timestamp titleize to-json try unit unquote uppercase unzip values version which while with xor zap zip contains +syntax keyword minimDefaultSymbol ! != $ & ' * + - % ^ -> . .. / : < <= == => =~ > >= @ ROOT aes and append apply ask at atime b bind bool bool? bury1 bury2 bury3 c call call! capitalize case cd chmod choose clear-stack column-print concat confirm cons cp cpu crypto ctime datetime ddel debug debug? decode decrypt define define* delete dget dictionary? dig1 dig2 dig3 dip dir? dirname div dprint dprint! dset dump-stack dup dupd echo encode encrypt env? eq eval even? exit fappend file? filename filter first float float? foreach fperms fread from-json format-error fs fsize fstats ftype fwrite gets get-stack getenv gt gte hardlink hidden? i id ifte import indent inspect int int? interpolate interval io join k keys length linrec load load-symbol logic lowercase ls ls-r lt lte map match md5 mkdir mod module mtime mv newline not noteq now num number? odd? or os password pop popd pred prepend print print! prompt publish puts puts! putenv q quit quotation? quote raise regex remove-symbol repeat replace rest rm rmdir run save-symbol scope scope? seal search select set-stack sha1 sha224 sha256 sha384 sha512 sigils sip size sleep sort source split startup stored-symbols str string string? strip succ swap swapd swons symbols symlink symlink? sys system take tformat time timeinfo times timestamp titleize to-json try unit unquote uppercase unzip values version which while with xor zap zip contains syntax match minimDefaultSigil ;\<[:@'~!$%&$=<>^*]; contained
M prelude.minprelude.min

@@ -62,9 +62,8 @@ (call pop) :call!

(:ms :q :check (check) (ms sleep q) while) :interval (password aes encode) :encrypt (decode password aes) :decrypt -(dup load import) :include -('print! 'dprint! 'puts! 'call! 'interval 'encrypt 'decrypt 'include) 'seal foreach +('print! 'dprint! 'puts! 'call! 'interval 'encrypt 'decrypt) 'seal foreach ; Unsealed symbols