all repos — min @ ddfb7a5b368a801666cc039aff552981e18c63e1

A small but practical concatenative programming language.

Implemented read and parse.
* Closes #14.
h3rald h3rald@h3rald.com
Fri, 10 Nov 2017 21:20:50 +0100
commit

ddfb7a5b368a801666cc039aff552981e18c63e1

parent

c11d56a229645ee23353a9cc3f19961048604cc8

M core/interpreter.nimcore/interpreter.nim

@@ -173,14 +173,18 @@ return i.stack[i.stack.len-1]

else: raiseEmptyStack() -proc interpret*(i: In): MinValue {.discardable, extern:"min_exported_symbol_$1".} = +proc interpret*(i: In, parseOnly=false): MinValue {.discardable, extern:"min_exported_symbol_$1".} = var val: MinValue + var q = newSeq[MinValue](0).newVal(i.scope) while i.parser.token != tkEof: if i.trace.len == 0: i.stackcopy = i.stack try: val = i.parser.parseMinValue(i) - i.push val + if parseOnly: + q.qVal.add val + else: + i.push val except MinRuntimeError: let msg = getCurrentExceptionMsg() i.stack = i.stackcopy

@@ -197,25 +201,34 @@ i.error(msg)

i.stackTrace i.trace = @[] raise MinTrappedException(msg: msg) + if parseOnly: + return q if i.stack.len > 0: return i.stack[i.stack.len - 1] -proc eval*(i: In, s: string, name="<eval>") {.extern:"min_exported_symbol_$1".}= +proc eval*(i: In, s: string, name="<eval>", parseOnly=false): MinValue {.discardable, extern:"min_exported_symbol_$1".}= var i2 = i.copy(name) i2.open(newStringStream(s), name) discard i2.parser.getToken() - i2.interpret() + result = i2.interpret(parseOnly) i.trace = i2.trace i.stackcopy = i2.stackcopy i.stack = i2.stack i.scope = i2.scope -proc load*(i: In, s: string) {.extern:"min_exported_symbol_$1".}= +proc load*(i: In, s: string, parseOnly=false): MinValue {.discardable, extern:"min_exported_symbol_$1".}= var i2 = i.copy(s) i2.open(newStringStream(s.readFile), s) discard i2.parser.getToken() - i2.interpret() + result = i2.interpret(parseOnly) i.trace = i2.trace i.stackcopy = i2.stackcopy i.stack = i2.stack i.scope = i2.scope + +proc parse*(i: In, s: string, name="<parse>"): MinValue {.extern:"min_exported_symbol_$1".}= + return i.eval(s, name, true) + +proc read*(i: In, s: string): MinValue {.extern:"min_exported_symbol_$1".}= + return i.load(s, true) +
M lib/min_lang.nimlib/min_lang.nim

@@ -158,6 +158,11 @@ let vals = i.expect("string")

let s = vals[0] i.eval s.strVal + def.symbol("parse") do (i: In): + let vals = i.expect("string") + let s = vals[0] + i.push i.parse s.strVal + def.symbol("load") do (i: In): let vals = i.expect("'sym") let s = vals[0]

@@ -169,6 +174,17 @@ info("[load] File: ", file)

if not file.fileExists: raiseInvalid("File '$1' does not exists." % file) i.load file + + def.symbol("read") do (i: In): + let vals = i.expect("'sym") + let s = vals[0] + var file = s.getString + if not file.endsWith(".min"): + file = file & ".min" + info("[read] File: ", file) + if not file.fileExists: + raiseInvalid("File '$1' does not exists." % file) + i.push i.read file def.symbol("with") do (i: In): let vals = i.expect("quot", "quot")
M min.vimmin.vim

@@ -11,7 +11,7 @@

setl iskeyword=@,36-39,+,-,/,*,.,:,~,!,48-57,60-65,94-95,192-255 setl iskeyword+=^ -syntax keyword minDefaultSymbol ! != $ & ' * + # - % ^ -> . .. / : < <= == => =~ > >= @ -inf ROOT acos aes all? and any? append apply args asin ask atan atime bind bool boolean? call call! capitalize case cd ceil chmod choose clear-stack cleave column-print concat confirm cons cos cosh cp cpu crypto ctime d2r datetime ddel debug decode define defined? delete dget dhas? dkeys dictionary? dip dir? dirname div dpick dprint dprint! dset dsort dup dvalues e encode env? error eval even? exists? exit expect fappend fatal find file? filename filter first flatten float float? floor foreach fperms fread from-json format-error fs fsize fstats ftype fwrite get gets get-env get-stack hardlink harvest hidden? id if import in? indent indexof inf info insert int integer? interpolate interval io join keep last length linrec ln load load-symbol log2 log10 logic loglevel loglevel? lowercase ls ls-r map map-reduce match math md5 mkdir mod module module-symbols module-sigils mtime mv nan newline nip not notice now num number? odd? opts os over partition password pi pick pop popd pow pred prepend print print! prompt publish puts puts! put-env q quotation? quote quote-bind quote-define r2d random raise reduce regex reject remove remove-symbol repeat replace rest reverse rm rmdir round run save-symbol scope scope? seal search seq set set-stack sha1 sha224 sha256 sha384 sha512 shorten sigils sin sinh sip size sleep slice sort source split spread sqrt stack startup stored-symbols str string string? strip succ sum swap swons symbols symlink symlink? sys system take tan tanh tap tap! tau tformat time timeinfo times timestamp titleize to-json to-timestamp try trunc dequote uppercase unzip version warn when which while with xor zip +syntax keyword minDefaultSymbol ! != $ & ' * + # - % ^ -> . .. / : < <= == => =~ > >= @ -inf ROOT acos aes all? and any? append apply args asin ask atan atime bind bool boolean? call call! capitalize case cd ceil chmod choose clear-stack cleave column-print concat confirm cons cos cosh cp cpu crypto ctime d2r datetime ddel debug decode define defined? delete dget dhas? dkeys dictionary? dip dir? dirname div dpick dprint dprint! dset dsort dup dvalues e encode env? error eval even? exists? exit expect fappend fatal find file? filename filter first flatten float float? floor foreach fperms fread from-json format-error fs fsize fstats ftype fwrite get gets get-env get-stack hardlink harvest hidden? id if import in? indent indexof inf info insert int integer? interpolate interval io join keep last length linrec ln load load-symbol log2 log10 logic loglevel loglevel? lowercase ls ls-r map map-reduce match math md5 mkdir mod module module-symbols module-sigils mtime mv nan newline nip not notice now num number? odd? opts os over parse partition password pi pick pop popd pow pred prepend print print! prompt publish puts puts! put-env q quotation? quote quote-bind quote-define r2d random raise read reduce regex reject remove remove-symbol repeat replace rest reverse rm rmdir round run save-symbol scope scope? seal search seq set set-stack sha1 sha224 sha256 sha384 sha512 shorten sigils sin sinh sip size sleep slice sort source split spread sqrt stack startup stored-symbols str string string? strip succ sum swap swons symbols symlink symlink? sys system take tan tanh tap tap! tau tformat time timeinfo times timestamp titleize to-json to-timestamp try trunc dequote uppercase unzip version warn when which while with xor zip syntax match minDefaultSigil ;\<[:@'~!?$%&$=<>#^*#+/]; contained syntax match minSpecialSymbols ;[:@'~!?$%&$=<>#^*#+/]; contained
M site/contents/_includes/_reference-lang.mdsite/contents/_includes/_reference-lang.md

@@ -198,6 +198,9 @@

{#op||opts||{{null}}||{{d}}|| Returns a dictionary of all options passed to the current program, with their respective values.#} +{#op||parse||{{s}}||{{q}}|| +Parses {{s}} and returns a quoted program {{q}}. #} + {#op||prompt||{{null}}||{{s}}|| > This symbol is used to configure the prompt of the min shell. By default, it is set to the following quotation: >

@@ -225,6 +228,9 @@ Quotes {{any}} and assigns the quotation to the symbol {{sl}}, creating it if not already defined. #}

{#op||raise||{{e}}||{{null}}|| Raises the error specified via the dictionary {{e}}.#} + +{#op||read||{{sl}}||{{q}}|| +Reads and parses the specified {{m}} file {{sl}} and returns a quoted program {{q}}. #} {#op||remove-symbol||{{sl}}||{{null}}|| Removes the symbol {{sl}} from the [.min\_symbols](class:file) file. #}
M tests/lang.mintests/lang.min

@@ -203,6 +203,12 @@ ) assert

(3.4 "test" 1 (int string num) expect (3.4 "test" 1) ==) assert + ("2 2 +" "testread.min" fwrite "testread.min" read (2 2 +) ==) assert + + "testread.min" rm + + ("aaa bbb ccc 2 2 + (2 3 4)" parse (aaa bbb ccc 2 2 + (2 3 4)) ==) assert + report ; Tidy up clear-stack