all repos — min @ 190fe7d067beab63a5504b08c9086711d717922e

A small but practical concatenative programming language.

core/interpreter.nim

 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
import 
  streams, 
  strutils, 
  sequtils,
  os,
  critbits,
  algorithm
when defined(mini):
  import
    minilogger
else:
  import 
    base64,
    logging
import 
  baseutils,
  value,
  scope,
  parser

type
  MinTrappedException* = ref object of CatchableError
  MinReturnException* = ref object of CatchableError
  MinRuntimeError* = ref object of CatchableError
    data*: MinValue

var ASSETPATH* {.threadvar.}: string
ASSETPATH = ""
var COMPILEDMINFILES* {.threadvar.}: CritBitTree[MinOperatorProc]
var COMPILEDASSETS* {.threadvar.}: CritBitTree[string]

const USER_SYMBOL_REGEX* = "^[a-zA-Z_][a-zA-Z0-9/!?+*._-]*$"

proc raiseRuntime*(msg: string, data: MinValue) =
  data.objType = "error"
  raise MinRuntimeError(msg: msg, data: data)

proc dump*(i: MinInterpreter): string =
  var s = ""
  for item in i.stack:
    s = s & $item & " "
  return s

proc debug*(i: In, value: MinValue) =
  debug("(" & i.dump & $value & ")")

proc debug*(i: In, value: string) =
  debug(value)

template withScope*(i: In, res:ref MinScope, body: untyped): untyped =
  let origScope = i.scope
  try:
    i.scope = newScopeRef(origScope)
    body
    res = i.scope
  finally:
    i.scope = origScope

template withScope*(i: In, body: untyped): untyped =
  let origScope = i.scope
  try:
    i.scope = newScopeRef(origScope)
    body
  finally:
    i.scope = origScope

template withDictScope*(i: In, s: ref MinScope, body: untyped): untyped =
  let origScope = i.scope
  try:
    i.scope = s
    body
  finally:
    i.scope = origScope

proc newMinInterpreter*(filename = "input", pwd = ""): MinInterpreter =
  var path = pwd
  when not defined(mini): 
    if not pwd.isAbsolute:
      path = joinPath(getCurrentDir(), pwd)
  var stack:MinStack = newSeq[MinValue](0)
  var trace:MinStack = newSeq[MinValue](0)
  var stackcopy:MinStack = newSeq[MinValue](0)
  var pr:MinParser
  var scope = newScopeRef(nil)
  var i:MinInterpreter = MinInterpreter(
    filename: filename, 
    pwd: path,
    parser: pr, 
    stack: stack,
    trace: trace,
    stackcopy: stackcopy,
    scope: scope,
    currSym: MinValue(column: 1, line: 1, kind: minSymbol, symVal: "")
  )
  return i

proc copy*(i: MinInterpreter, filename: string): MinInterpreter =
  var path = filename
  when not defined(mini): 
    if not filename.isAbsolute:
      path = joinPath(getCurrentDir(), filename)
  result = newMinInterpreter()
  result.filename = filename
  result.pwd =  path.parentDirEx
  result.stack = i.stack
  result.trace = i.trace
  result.stackcopy = i.stackcopy
  result.scope = i.scope
  result.currSym = MinValue(column: 1, line: 1, kind: minSymbol, symVal: "")

proc formatError(sym: MinValue, message: string): string =
  if sym.filename == "":
    return "[$1]: $2" % [sym.symVal, message]
  else:
    return "$1($2,$3) [$4]: $5" % [sym.filename, $sym.line, $sym.column, sym.symVal, message]

proc formatTrace(sym: MinValue): string =
  if sym.filename == "":
    return "<native> in symbol: $1" % [sym.symVal]
  else:
    return "$1($2,$3) in symbol: $4" % [sym.filename, $sym.line, $sym.column, sym.symVal]

proc stackTrace*(i: In) =
  var trace = i.trace
  trace.reverse()
  for sym in trace:
    notice sym.formatTrace

proc error(i: In, message: string) =
  error(i.currSym.formatError(message))

proc open*(i: In, stream:Stream, filename: string) =
  i.filename = filename
  i.parser.open(stream, filename)

proc close*(i: In) = 
  i.parser.close();

proc push*(i: In, val: MinValue) {.gcsafe, extern:"min_exported_symbol_$1".} 

proc call*(i: In, q: var MinValue): MinValue {.gcsafe, extern:"min_exported_symbol_$1".}=
  var i2 = newMinInterpreter("<call>")
  i2.trace = i.trace
  i2.scope = i.scope
  try:
    i2.withScope(): 
      for v in q.qVal:
        i2.push v
  except:
    i.currSym = i2.currSym
    i.trace = i2.trace
    raise
  return i2.stack.newVal

proc callValue*(i: In, v: var MinValue): MinValue {.gcsafe, extern:"min_exported_symbol_$1".}=
  var i2 = newMinInterpreter("<call-value>")
  i2.trace = i.trace
  i2.scope = i.scope
  try:
    i2.withScope(): 
      i2.push v
  except:
    i.currSym = i2.currSym
    i.trace = i2.trace
    raise
  return i2.stack[0]

proc copyDict*(i: In, val: MinValue): MinValue {.gcsafe, extern:"min_exported_symbol_$1".}=
   # Assuming val is a dictionary
   var v = newDict(i.scope)
   for item in val.scope.symbols.pairs:
     v.scope.symbols[item.key] = item.val
   for item in val.scope.sigils.pairs:
     v.scope.sigils[item.key] = item.val
   if val.objType != "":
     v.objType = val.objType
   if not val.obj.isNil:
     v.obj = val.obj
   return v

proc applyDict*(i: In, val: MinValue): MinValue {.gcsafe, extern:"min_exported_symbol_$1".}=
   # Assuming val is a dictionary
   var v = i.copyDict(val)
   for item in v.dVal.pairs:
     var value = item.val.val
     v.scope.symbols[item.key] = MinOperator(kind: minValOp, val: i.callValue(value), sealed: false)
   return v

proc apply*(i: In, op: MinOperator) {.gcsafe, extern:"min_exported_symbol_$1".}=
  if op.kind == minProcOp:
    op.prc(i)
  else:
    if op.val.kind == minQuotation:
      var newscope = newScopeRef(i.scope)
      i.withScope(newscope):
        for e in op.val.qVal:
          i.push e
    else:
      i.push(op.val)

proc dequote*(i: In, q: var MinValue) =
  if q.kind == minQuotation:
    i.withScope(): 
      let qqval = deepCopy(q.qVal)
      for v in q.qVal:
        i.push v
      q.qVal = qqval
  else:
    i.push(q)

proc apply*(i: In, q: var MinValue) {.gcsafe, extern:"min_exported_symbol_$1_2".}=
  var i2 = newMinInterpreter("<apply>")
  i2.trace = i.trace
  i2.scope = i.scope
  try:
    i2.withScope(): 
      for v in q.qVal:
        if (v.kind == minQuotation):
          var v2 = v
          i2.dequote(v2)
        else:
          i2.push v
  except:
    i.currSym = i2.currSym
    i.trace = i2.trace
    raise
  i.push i2.stack.newVal

proc push*(i: In, val: MinValue) {.gcsafe, extern:"min_exported_symbol_$1".}= 
  if val.kind == minSymbol:
    i.debug(val)
    if not i.evaluating:
      #echo val, ":", val.filename, ":", val.line, ":", val.column
      if val.line == 0 and val.column == 0 and val.filename == "":
        # Simbol was added via min code, get data from previous min symbol
        var nval = deepCopy(val)
        let pval = i.trace[i.trace.len-1]
        nval.symVal = pval.symVal & " > " & nval.symVal
        nval.filename = pval.filename
        nval.column = pval.column
        nval.line = pval.line
        i.currSym = nval
      else:
        i.currSym = val
    i.trace.add val
    let symbol = val.symVal
    if symbol == "return":
      raise MinReturnException(msg: "return symbol found")
    if i.scope.hasSymbol(symbol):
      i.apply i.scope.getSymbol(symbol) 
    else: 
      var qIndex = symbol.find('"')
      if qIndex > 0:
        let sigil = symbol[0..qIndex-1]
        if not i.scope.hasSigil(sigil):
          raiseUndefined("Undefined sigil '$1'"%sigil)
        i.stack.add(MinValue(kind: minString, strVal: symbol[qIndex+1..symbol.len-2]))
        i.apply(i.scope.getSigil(sigil))
      else:
        let sigil = "" & symbol[0]
        if symbol.len > 1 and i.scope.hasSigil(sigil):
          i.stack.add(MinValue(kind: minString, strVal: symbol[1..symbol.len-1]))
          i.apply(i.scope.getSigil(sigil))
        else:
          raiseUndefined("Undefined symbol '$1'" % [val.symVal])
    discard i.trace.pop
  elif val.kind == minDictionary and val.objType != "module":
    # Dictionary must be copied every time they are interpreted, otherwise when they are used in cycles they reference each other.
    var v = i.copyDict(val)
    i.stack.add(v)
  else:
    i.stack.add(val)

proc pop*(i: In): MinValue =
  if i.stack.len > 0:
    return i.stack.pop
  else:
    raiseEmptyStack()

proc peek*(i: MinInterpreter): MinValue = 
  if i.stack.len > 0:
    return i.stack[i.stack.len-1]
  else:
    raiseEmptyStack()

template handleErrors*(i: In, body: untyped) =
  try:
    body
  except MinRuntimeError:
    echo "runtime"
    let msg = getCurrentExceptionMsg()
    i.stack = i.stackcopy
    error("$1:$2,$3 $4" % [i.currSym.filename, $i.currSym.line, $i.currSym.column, msg])
    i.stackTrace()
    i.trace = @[]
    raise MinTrappedException(msg: msg)
  except MinTrappedException:
    echo "trapped"
    raise
  except:
    let msg = getCurrentExceptionMsg()
    i.stack = i.stackcopy
    echo "generic "
    #echo("$1:$2,$3 $4" % [i.currSym.filename, $i.currSym.line, $i.currSym.column, msg])
    #i.error(msg)
    error("$1:$2,$3 $4" % [i.currSym.filename, $i.currSym.line, $i.currSym.column, msg])
    i.stackTrace()
    i.trace = @[]
    raise MinTrappedException(msg: msg)


proc interpret*(i: In, parseOnly=false): MinValue {.discardable, extern:"min_exported_symbol_$1".} =
  var val: MinValue
  var q: MinValue
  if parseOnly:
    q = newSeq[MinValue](0).newVal
  while i.parser.token != tkEof: 
    if i.trace.len == 0:
      i.stackcopy = i.stack
    handleErrors(i) do:
      val = i.parser.parseMinValue(i)
      if parseOnly:
        q.qVal.add val
      else:
        i.push val
  if parseOnly:
    return q
  if i.stack.len > 0:
    return i.stack[i.stack.len - 1]

proc rawCompile*(i: In, indent = ""): seq[string] {.discardable, extern:"min_exported_symbol_$1".} =
  while i.parser.token != tkEof: 
    if i.trace.len == 0:
      i.stackcopy = i.stack
    try:
      result.add i.parser.compileMinValue(i, push = true, indent)
    except MinRuntimeError:
      let msg = getCurrentExceptionMsg()
      i.stack = i.stackcopy
      error("$1:$2,$3 $4" % [i.currSym.filename, $i.currSym.line, $i.currSym.column, msg])
      i.stackTrace
      i.trace = @[]
      raise MinTrappedException(msg: msg)
    except MinTrappedException:
      raise
    except:
      let msg = getCurrentExceptionMsg()
      i.stack = i.stackcopy
      i.error(msg)
      i.stackTrace
      i.trace = @[]
      raise MinTrappedException(msg: msg)
    
proc compileFile*(i: In, main: bool): seq[string] {.discardable, extern:"min_exported_symbol_$1".} =
  result = newSeq[string](0)
  if not main:
    result.add "COMPILEDMINFILES[\"$#\"] = proc(i: In) {.gcsafe.}=" % i.filename
    result = result.concat(i.rawCompile("  "))
  else:
    result = i.rawCompile("")

proc initCompiledFile*(i: In, files: seq[string]): seq[string] {.discardable, extern:"min_exported_symbol_$1".} =
  result = newSeq[string](0)
  result.add "import min"
  if files.len > 0 or (ASSETPATH != "" and not defined(mini)):
    result.add "import critbits"
  when not defined(mini):
    if ASSETPATH != "":
      result.add "import base64"
  result.add "MINCOMPILED = true"
  result.add "var i = newMinInterpreter(\"$#\")" % i.filename
  result.add "i.stdLib()"
  when not defined(mini): 
    if ASSETPATH != "":
      for f in walkDirRec(ASSETPATH):
        var file = f.replace("\\", "/")
        logging.notice("- Including: $#" % file)
        let ef = file.readFile.encode
        let asset = "COMPILEDASSETS[\"$#\"] = \"$#\".decode" % [file, ef]
        result.add asset

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() 
  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, parseOnly=false): MinValue {.discardable, extern:"min_exported_symbol_$1".}=
  var fileLines = newSeq[string](0)
  var contents = ""
  try:
    fileLines = s.readFile().splitLines()
  except:
    fatal("Cannot read from file: " & s)
  if fileLines[0].len >= 2 and fileLines[0][0..1] == "#!":
    contents = ";;\n" & fileLines[1..fileLines.len-1].join("\n")
  else:
    contents = fileLines.join("\n")
  var i2 = i.copy(s)
  i2.open(newStringStream(contents), s)
  discard i2.parser.getToken() 
  result = i2.interpret(parseOnly)
  i.trace = i2.trace
  i.stackcopy = i2.stackcopy
  i.stack = i2.stack
  i.scope = i2.scope

proc require*(i: In, s: string, parseOnly=false): MinValue {.discardable, extern:"min_exported_symbol_$1".}=
  var fileLines = newSeq[string](0)
  var contents = ""
  try:
    fileLines = s.readFile().splitLines()
  except:
    fatal("Cannot read from file: " & s)
  if fileLines[0].len >= 2 and fileLines[0][0..1] == "#!":
    contents = ";;\n" & fileLines[1..fileLines.len-1].join("\n")
  else:
    contents = fileLines.join("\n")
  var i2 = i.copy(s)
  i2.withScope:
    i2.open(newStringStream(contents), s)
    discard i2.parser.getToken() 
    discard i2.interpret(parseOnly)
    result = newDict(i2.scope)
    result.objType = "module"
    for key, value in i2.scope.symbols.pairs:
      result.scope.symbols[key] = value

proc parse*(i: In, s: string, name="<parse>"): MinValue =
  return i.eval(s, name, true)

proc read*(i: In, s: string): MinValue =
  return i.load(s, true)