all repos — min @ e8683f56b3be94e952dcb394f6812b5681d0edff

A small but practical concatenative programming language.

min.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
{.passL: "-rdynamic".}
import 
  streams, 
  critbits, 
  parseopt2, 
  strutils, 
  os, 
  json, 
  sequtils,
  algorithm,
  logging,
  dynlib

import 
  packages/nimline/nimline,
  packages/niftylogger,
  core/consts,
  core/parser, 
  core/value, 
  core/scope,
  core/interpreter, 
  core/utils
import 
  lib/min_lang, 
  lib/min_stack, 
  lib/min_seq, 
  lib/min_num,
  lib/min_str,
  lib/min_logic,
  lib/min_time, 
  lib/min_io,
  lib/min_sys,
  lib/min_fs

when not defined(lite):
  import lib/min_crypto

export 
  parser,
  interpreter,
  utils,
  niftylogger,
  value,
  scope,
  min_lang

const PRELUDE* = "prelude.min".slurp.strip

newNiftyLogger().addHandler()

proc getExecs(): seq[string] =
  var res = newSeq[string](0)
  let getFiles = proc(dir: string) =
    for c, s in walkDir(dir, true):
      if (c == pcFile or c == pcLinkToFile) and not res.contains(s):
        res.add s
  getFiles(getCurrentDir())
  for dir in "PATH".getEnv.split(PathSep):
    getFiles(dir)
  res.sort(system.cmp)
  return res

proc getCompletions(ed: LineEditor, symbols: seq[string]): seq[string] =
  var words = ed.lineText.split(" ")
  var word: string
  if words.len == 0:
    word = ed.lineText
  else:
    word = words[words.len-1]
  if word.startsWith("'"):
    return symbols.mapIt("'" & $it)
  elif word.startsWith("~"):
    return symbols.mapIt("~" & $it)
  if word.startsWith("@"):
    return symbols.mapIt("@" & $it)
  if word.startsWith("#"):
    return symbols.mapIt("#" & $it)
  if word.startsWith(">"):
    return symbols.mapIt(">" & $it)
  if word.startsWith("*"):
    return symbols.mapIt("*" & $it)
  if word.startsWith("("):
    return symbols.mapIt("(" & $it)
  if word.startsWith("<"):
    return toSeq(MINSYMBOLS.readFile.parseJson.pairs).mapIt("<" & $it[0])
  if word.startsWith("$"):
    return toSeq(envPairs()).mapIt("$" & $it[0])
  if word.startsWith("!"):
    return getExecs().mapIt("!" & $it)
  if word.startsWith("&"):
    return getExecs().mapIt("&" & $it)
  if word.startsWith("\""):
    var f = word[1..^1]
    if f == "":
      f = getCurrentDir().replace("\\", "/")  
      return toSeq(walkDir(f, true)).mapIt("\"$1" % it.path.replace("\\", "/"))
    elif f.dirExists:
      f = f.replace("\\", "/")
      if f[f.len-1] != '/':
        f = f & "/"
      return toSeq(walkDir(f, true)).mapIt("\"$1$2" % [f, it.path.replace("\\", "/")])
    else:
      var dir: string
      if f.contains("/") or dir.contains("\\"):
        dir = f.parentDir
        let file = f.extractFileName
        return toSeq(walkDir(dir, true)).filterIt(it.path.toLowerAscii.startsWith(file.toLowerAscii)).mapIt("\"$1/$2" % [dir, it.path.replace("\\", "/")])
      else:
        dir = getCurrentDir()
        return toSeq(walkDir(dir, true)).filterIt(it.path.toLowerAscii.startsWith(f.toLowerAscii)).mapIt("\"$1" % [it.path.replace("\\", "/")])
  return symbols

proc stdLib*(i: In) =
  if not MINSYMBOLS.fileExists:
    MINSYMBOLS.writeFile("{}")
  if not MINHISTORY.fileExists:
    MINHISTORY.writeFile("")
  if not MINRC.fileExists:
    MINRC.writeFile("")
  i.lang_module
  i.stack_module
  i.seq_module
  i.io_module
  i.logic_module
  i.num_module
  i.str_module
  i.sys_module
  i.time_module
  i.fs_module
  when not defined(lite):
    i.crypto_module
  i.eval PRELUDE, "<prelude>"
  i.eval MINRC.readFile()
  i.eval "\"prompt\" unseal"

type
  DynInfo = object
    moduleName: string # The name of the symbol to load and run
    dynlibVersion: int # The version of the interface the dynlib is built for. This should increase if the interface changes
  setupProc = proc(): DynInfo {.nimcall.}
  libProc = proc(
      i: In
    ) {.nimcall.}
proc dynLib*(i: In) =
  var
    dll: LibHandle
    setup: setupProc
  echo "Trying to load libraries from " & $(getAppDir() / "dynlibs")
  for library in walkFiles(getAppDir() / "dynlibs/*"):
    dll = loadLib(library)
    if dll != nil:
      let setupAddr = dll.symAddr("setup")
      if setupAddr != nil:
        setup = cast[setupProc](setupAddr)
      if setup != nil:
        let
          expectedVersion = 1
          libInfo = setup()
          libAddr = dll.symAddr(libInfo.moduleName)
        if libInfo.dynlibVersion == expectedVersion: 
          if libAddr != nil:
            var lib = cast[libProc](libAddr)
            i.lib
            echo "Loaded dynlib " & libInfo.moduleName & "[" & library & "]"
          else:
            echo "Wasn't able to load " & libInfo.moduleName & "(i: In) from " & library
        else:
          echo "Dynlib in " & library & " has wrong version, got " & $libInfo.dynlibVersion & " but expected " & $expectedVersion
      else:
        echo "Wasn't able to load setup() from " & library
    else:
      echo "Unable to load lib from " & library

proc interpret*(i: In, s: Stream) =
  i.stdLib()
  i.dynLib()
  i.open(s, i.filename)
  discard i.parser.getToken() 
  try:
    i.interpret()
  except:
    discard
  i.close()

proc minStream(s: Stream, filename: string) = 
  var i = newMinInterpreter(filename = filename)
  i.pwd = filename.parentDir
  i.interpret(s)

proc minString*(buffer: string) =
  minStream(newStringStream(buffer), "input")

proc minFile*(filename: string) =
  var stream = newFileStream(filename, fmRead)
  if stream == nil:
    fatal("Cannot read from file: "& filename)
    quit(3)
  minStream(stream, filename)

proc minFile*(file: File, filename="stdin") =
  var stream = newFileStream(stdin)
  if stream == nil:
    fatal("Cannot read from file: "& filename)
    quit(3)
  minStream(stream, filename)

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 minRepl*(i: var MinInterpreter) =
  i.stdLib()
  i.dynLib()
  var s = newStringStream("")
  i.open(s, "<repl>")
  var line: string
  #echo "$1 v$2" % [appname, version]
  var ed = initEditor(historyFile = MINHISTORY)
  while true:
    let symbols = toSeq(i.scope.symbols.keys)
    ed.completionCallback = proc(ed: LineEditor): seq[string] =
      return ed.getCompletions(symbols)
    # evaluate prompt
    i.push("prompt".newSym)
    let vals = i.expect("string")
    let v = vals[0] 
    let prompt = v.getString()
    line = ed.readLine(prompt)
    i.parser.bufpos = 0
    i.parser.buf = $line
    i.parser.bufLen = i.parser.buf.len
    discard i.parser.getToken() 
    try:
      i.printResult i.interpret()
    except:
      discard

proc minRepl*() = 
  var i = newMinInterpreter(filename = "<repl>")
  i.minRepl
    
when isMainModule:

  var REPL = false

  let usage* = """  $1 v$2 - a tiny concatenative shell and programming language
  (c) 2014-2017 Fabio Cevasco
  
  Usage:
    min [options] [filename]

  Arguments:
    filename  A $1 file to interpret (default: STDIN).
  Options:
    -e, --evaluate    Evaluate a $1 program inline
    -h, --help        Print this help
    -v, --version     Print the program version
    -i, --interactive Start $1 shell""" % [appname, version]

  var file, s: string = ""
  setLogFilter(lvlNotice)
  
  for kind, key, val in getopt():
    case kind:
      of cmdArgument:
        file = key
      of cmdLongOption, cmdShortOption:
        case key:
          of "log", "l":
            var val = val
            setLogLevel(val)
          of "evaluate", "e":
            s = val
          of "help", "h":
            echo usage
            quit(0)
          of "version", "v":
            echo version
            quit(0)
          of "interactive", "i":
            REPL = true
          else:
            discard
      else:
        discard
  
  if s != "":
    minString(s)
  elif file != "":
    minFile file
  elif REPL:
    minRepl()
    quit(0)
  else:
    minFile stdin, "stdin"