simplification
Download
197 lines 7.7 KiBMoonScriptModified 2026-11-09executable raw
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
#!/usr/bin/env moon
-- This file contains the command-line Nomsu runner.
-- When it's loaded with `require "nomsu"` instead of run as a script, it returns the
-- Nomsu library (see nomsu_library.moon), so Lua programs can use Nomsu idiomatically.
if pcall(debug.getlocal, 4, 1)
    return require "nomsu_library"

clibtype = package.cpath\match("?%.(so)") or package.cpath\match("?%.(dll)")

-- An installed runner has NOMSU_PREFIX, NOMSU_PACKAGEPATH, and NOMSU_VERSION set at the top
-- of the file by `make install`, so it can find the installed Nomsu files
if NOMSU_PREFIX
    package.path = "#{NOMSU_PREFIX}/share/nomsu/#{NOMSU_VERSION}/?.lua;"..package.path
    package.cpath = "#{NOMSU_PREFIX}/lib/nomsu/#{NOMSU_VERSION}/?.#{clibtype};"..package.cpath

COLOR_ENABLED = true
if clibtype == "dll"
    -- Enable colors:
    ok, enable_colors = pcall(require, 'wincolors')
    COLOR_ENABLED = ok and pcall(enable_colors)
    -- Special hack to enable utf8 for windows console applications:
    pcall(os.execute,"chcp 65001>nul")

Text = require 'text'
EXIT_FAILURE = 1
EXIT_SUCCESS = 0

usage = [=[
Nomsu Usage: nomsu [-V version] [--help | -h] [--version] [-O optimization level] [-v] [-c] [-s] [-d debugger] [--no-core] [(file | -t tool | -e "nomsu code..." | files... -- ) [nomsu args...]]

OPTIONS
    -t <tool> Run a tool.
    -e Execute the specified string.
    -O <level> Run the compiler with the given optimization level (>0: use precompiled .lua versions of Nomsu files, when available).
    -v Verbose: print compiled lua code.
    -c Compile the input files into a .lua files.
    -s Check the input files for syntax errors.
    -d <debugger> Attempt to use the specified debugger to wrap the main body of execution.
    -h/--help Print this message.
    --version Print the version number and exit.
    --no-core Skip loading the Nomsu core by default.
    -V specify which Nomsu version is desired.
    <file> The Nomsu file to run (can be "-" to use stdin).
]=]

ok, lpeg = pcall(require, 'lpeg')
re = ok and require('re')
if not ok
    print("Error: unable to find the 'lpeg' Lua module. Please install LPEG either from http://www.inf.puc-rio.br/~roberto/lpeg/re.html or, if you use luarocks: `luarocks install lpeg`")
    os.exit(EXIT_FAILURE)
Files = require "files"
{:NomsuCode, :LuaCode, :Source} = require "code_obj"

sep = "\3"
parser = re.compile([[
    args <- {| (flag %sep)*
         {:files: {|
          ( ("-m" %sep)? (file %sep)+ "--" %sep
           / file %sep
           / {~ '' %sep? -> 'nomsu://tools/repl.nom' ~}) |} :}
      {:nomsu_args: {| (nomsu_flag %sep)* {:extras: {| ({[^%sep]+} %sep)* |} :} |} :}
      |} ({.+}?)

    file <-
        (  "-e" %sep ({[^%sep]+} -> spoof)
         / "-t" %sep {~ {[^%sep]+} -> "nomsu://tools/%1.nom" ~}
         / !"--" {[^%sep]+})

    flag <- longflag / shortflag / "-" shortboolflag+
    longflag <-
        {:help: "--help" %true :}
      / {:version: "--version" %true :}
      / {:no_core: "--no-core" %true :}
    shortflag <-
        {:optimization: "-O" %sep? %number :}
      / {:debugger: ("-d" %sep? {[^%sep]+}) :}
      / {:requested_version: "-V" %sep? {([0-9.])+} :}
    shortboolflag <-
        {:check_syntax: "s" %true:}
      / {:compile: "c" %true:}
      / {:verbose: "v" %true :}
      / {:help: "h" %true :}

    nomsu_flag <- nomsu_longflag / "-" nomsu_shortboolflag+
    nomsu_shortboolflag <- {| {:key: [a-zA-Z] :} {:value: %true :} |}
    nomsu_longflag <- '--' {| {:key: [^%sep=]+ :} {:value: ('=' {[^%sep]+}) / %true :} |}
]], {
    true:lpeg.Cc(true), number:lpeg.R("09")^1/tonumber, sep:lpeg.P(sep),
    spoof: Files.spoof
})
arg_string = table.concat(arg, sep)..sep
args, err = parser\match(arg_string)
if not args or err
    if err
        print("Didn't understand: #{err}")
    print usage
    os.exit(EXIT_FAILURE)
if args.help
    print "Nomsu - A dynamically typed programming language with natural syntax and strong metaprogramming abilities."
    print "https://nomsu.bruce-hill.com\n"
    print usage
    os.exit(EXIT_SUCCESS)
if args.version
    print(table.concat(require("nomsu_version"), "."))
    os.exit(EXIT_SUCCESS)
nomsu_args = {}
for argpair in *args.nomsu_args
    nomsu_args[argpair.key] = argpair.value
nomsu_args.extras = args.nomsu_args.extras or {}
optimization = tonumber(args.optimization or 1)

{:new_instance, NOMSU_VERSION: LIBRARY_VERSION} = require 'nomsu_environment'
{:search_path, :file_loader} = require 'nomsu_loaders'
if NOMSU_VERSION
    assert table.concat(LIBRARY_VERSION, ".") == NOMSU_VERSION,
        "The Nomsu runner's version doesn't match the version of the Nomsu library it found"
require('colors').enabled = COLOR_ENABLED
NOMSU_PACKAGEPATH or= "/opt/nomsu"
lib_dir = if NOMSU_PREFIX
    "#{NOMSU_PREFIX}/share/nomsu/#{NOMSU_VERSION}/lib"
else "./lib"
nomsupath = search_path({lib_dir, NOMSU_PACKAGEPATH, "."}, optimization)

run = ->
    nomsu_environment = new_instance{
        loader: file_loader({lib_dir, NOMSU_PACKAGEPATH, "."}, optimization), :optimization
    }
    nomsu_environment.COMMAND_LINE_ARGS = nomsu_args
    nomsu_environment.NOMSU_PACKAGEPATH = NOMSU_PACKAGEPATH
    nomsu_environment.NOMSU_PREFIX = NOMSU_PREFIX
    nomsu_environment.COLOR_ENABLED = COLOR_ENABLED
    nomsu_environment\export("core") unless args.no_core

    input_files = {}
    if args.files and #args.files > 0
        for f in *args.files
            if nomsu_name = f\match("^nomsu://(.*)%.nom")
                path, err = package.searchpath(nomsu_name, nomsupath, "/")
                if not path then error(err)
                table.insert input_files, path
            else
                table.insert input_files, f

    for filename in *input_files
        code = Files.read(filename)
        unless code
            if filename\match "^-"
                print "Not a valid flag: "..filename.."\n"
                print usage
            else
                print "File not found: "..filename
            os.exit EXIT_FAILURE
        source = Source(filename, 1, #code)
        if args.check_syntax
            nomsu_environment._1_parsed(NomsuCode\from(source, code))
            print("Parse succeeded: #{filename}")
            continue

        env = nomsu_environment.new_environment!
        env.MODULE_NAME = filename
        env.WAS_RUN_DIRECTLY = true unless args.compile
        unless args.compile or args.verbose
            -- Just run the file
            env\run((filename\match("%.lua$") and LuaCode or NomsuCode)\from(source, code))
            continue

        local tree, lua
        if filename\match("%.lua$")
            if args.compile
                error("Cannot compile a lua file (expected a nomsu file as input)")
            lua = LuaCode\from(source, code)
        else
            tree = env._1_parsed(NomsuCode\from(source, code))
            lua = env\compile_file(tree)
            lua\declare_locals!
            lua\prepend "-- File #{filename}\n"

        if args.compile
            -- Lets nomsu tell whether this .lua file is out of date with the .nom file
            lua\prepend "\n-- Source hash: #{Files.hash(code)}\n"
            if args.verbose then print(lua\text!)
            lua_filename = filename\gsub("%.nom$", ".lua")
            output = if filename == 'stdin' then io.output()
            else io.open(lua_filename, "w")
            output\write(tree.shebang) if tree.shebang
            output\write(lua\text!, "\n")
            print ("Compiled %-25s -> %s")\format(filename, lua_filename)
            output\close!
        else
            print(lua\text!)
            env\run(lua)

debugger = if args.debugger == "nil" then {}
else require(args.debugger or 'error_handling')
guard = if type(debugger) == 'function' then debugger
else debugger.guard or debugger.call or debugger.wrap or debugger.run or ((fn)->fn())
guard(run)