all repos — mn @ 6984649e66f0bbc60ba295a2ff6f9d7640a3ab5f

A truly minimal concatenative programming language.

mnpkg/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
import 
  streams, 
  strutils, 
  os,
  osproc,
  critbits,
  algorithm
import 
  value,
  scope,
  parser

type
  MnTrappedException* = ref object of CatchableError
  MnReturnException* = ref object of CatchableError
  MnRuntimeError* = ref object of CatchableError
    data*: MnValue

var DEBUG* {. threadvar .} : bool
DEBUG = false

proc diff*(a, b: seq[MnValue]): seq[MnValue] =
  result = newSeq[MnValue](0)
  for it in b:
    if not a.contains it:
      result.add it

proc newSym*(i: In, s: string): MnValue =
 return MnValue(kind: mnSymbol, symVal: s, filename: i.currSym.filename, line: i.currSym.line, column: i.currSym.column, outerSym: i.currSym.symVal)

proc copySym*(i: In, sym: MnValue): MnValue =
  return MnValue(kind: mnSymbol, symVal: sym.outerSym, filename: sym.filename, line: sym.line, column: sym.column, outerSym: "", docComment: sym.docComment)

proc raiseRuntime*(msg: string) =
  raise MnRuntimeError(msg: msg)

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

template withScope*(i: In, res:ref MnScope, 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

proc newMinInterpreter*(filename = "input", pwd = ""): MnInterpreter =
  var path = pwd
  if not pwd.isAbsolute:
    path = joinPath(getCurrentDir(), pwd)
  var stack:MnStack = newSeq[MnValue](0)
  var trace:MnStack = newSeq[MnValue](0)
  var stackcopy:MnStack = newSeq[MnValue](0)
  var pr:MnParser
  var scope = newScopeRef(nil)
  var i:MnInterpreter = MnInterpreter(
    filename: filename, 
    pwd: path,
    parser: pr, 
    stack: stack,
    trace: trace,
    stackcopy: stackcopy,
    scope: scope,
    currSym: MnValue(column: 1, line: 1, kind: mnSymbol, symVal: "")
  )
  return i

proc copy*(i: MnInterpreter, filename: string): MnInterpreter =
  var path = filename
  if not filename.isAbsolute:
    path = joinPath(getCurrentDir(), filename)
  result = newMinInterpreter()
  result.filename = filename
  result.pwd =  path.parentDir
  result.stack = i.stack
  result.trace = i.trace
  result.stackcopy = i.stackcopy
  result.scope = i.scope
  result.currSym = MnValue(column: 1, line: 1, kind: mnSymbol, symVal: "")

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

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

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

proc error*(i: In, message: string) =
  stderr.writeLine(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: MnValue) {.gcsafe.} 

proc apply*(i: In, op: MnOperator, sym = "") {.gcsafe.}=
  if op.kind == mnProcOp:
    op.prc(i)
  else:
    if op.val.kind == mnQuotation:
      var newscope = newScopeRef(i.scope)
      i.withScope(newscope):
        for e in op.val.qVal:
          if e.isSymbol and e.symVal == sym:
            raiseInvalid("Symbol '$#' evaluates to itself" % sym)
          i.push e
    else:
      i.push(op.val)

proc dequote*(i: In, q: var MnValue) =
  if q.kind == mnQuotation:
    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 MnValue) {.gcsafe.}=
  var i2 = newMinInterpreter("<apply>")
  i2.trace = i.trace
  i2.scope = i.scope
  try:
    i2.withScope(): 
      for v in q.qVal:
        if (v.kind == mnQuotation):
          var v2 = v
          i2.dequote(v2)
        else:
          i2.push v
  except CatchableError:
    i.currSym = i2.currSym
    i.trace = i2.trace
    raise
  i.push i2.stack.newVal

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

# Inherit file/line/column from current symbol
proc pushSym*(i: In, s: string) =
  i.push MnValue(
    kind: mnSymbol, 
    symVal: s, 
    filename: i.currSym.filename, 
    line: i.currSym.line, 
    column: i.currSym.column, 
    outerSym: i.currSym.symVal, 
    docComment: i.currSym.docComment)

proc push*(i: In, val: MnValue) {.gcsafe.}= 
  if val.kind == mnSymbol:
    if not i.evaluating:
      if val.outerSym != "":
        i.currSym = i.copySym(val)
      else:
        i.currSym = val
    i.trace.add val
    if DEBUG:
      echo "-- push  symbol: $#" % val.symVal
    let symbol = val.symVal
    if i.scope.hasSymbol(symbol):
      i.apply i.scope.getSymbol(symbol), symbol
    else: 
      raiseUndefined("Undefined symbol '$1'" % [val.symVal])
    discard i.trace.pop
  elif val.kind == mnCommand:
    if DEBUG:
      echo "-- push command: $#" % val.cmdVal
    let res = execCmdEx(val.cmdVal)
    i.push res.output.strip.newVal
  else:
    if DEBUG:
      echo "-- push literal: $#" % $val
    i.stack.add(val)

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

template handleErrors*(i: In, body: untyped) =
  try:
    body
  except MnRuntimeError:
    let msg = getCurrentExceptionMsg()
    i.stack = i.stackcopy
    stderr.writeLine("$1:$2,$3 $4" % [i.currSym.filename, $i.currSym.line, $i.currSym.column, msg])
    i.stackTrace()
    i.trace = @[]
    raise MnTrappedException(msg: msg)
  except MnTrappedException:
    raise
  except CatchableError:
    let msg = getCurrentExceptionMsg()
    i.stack = i.stackcopy
    i.stackTrace()
    i.trace = @[]
    raise MnTrappedException(msg: msg)

proc interpret*(i: In, parseOnly=false): MnValue {.discardable.} =
  var val: MnValue
  var q: MnValue
  if parseOnly:
    q = newSeq[MnValue](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 eval*(i: In, s: string, name="<eval>", parseOnly=false): MnValue {.discardable.}=
  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