summary refs log tree commit diff stats
path: root/printtokens.lua
diff options
context:
space:
mode:
authorSoniEx2 <endermoneymod@gmail.com>2019-04-10 19:41:50 -0300
committerSoniEx2 <endermoneymod@gmail.com>2019-04-10 19:41:50 -0300
commit4cff82dd045c8acf5820768d7195327082d55950 (patch)
tree147bc8c98499e8e226689e9607d53c8d0a4f7605 /printtokens.lua
parentc77a2df387edc3f975143cf1aaab48e4c761bf5b (diff)
Allow parser.lua to be used as an argument parser
Diffstat (limited to 'printtokens.lua')
-rw-r--r--printtokens.lua55
1 files changed, 42 insertions, 13 deletions
diff --git a/printtokens.lua b/printtokens.lua
index 8f2d0f5..bf52803 100644
--- a/printtokens.lua
+++ b/printtokens.lua
@@ -18,18 +18,47 @@
 
 local parser = require "parser"
 
-do
-    local filename = arg[1]
-    local luatokens = require "luatokens"
-    local file = io.open(filename, "r")
-    local tokens = luatokens.defs
-    local state, err, etoken, estate = parser.parse(tokens, function() return file:read(8192) end)
-    if state then
-        for i,v in ipairs(state) do
-            v = luatokens.reverse_keywords[v] or luatokens.reverse_tokens[v] or v
-            print(i, v) -- TODO formatting
-        end
-    else
-        print("Parse error")
+-- CLI argument rules
+local defs = parser.selfify({})
+defs['-'] = function(state, token)
+    if state.filename then
+        error("Must specify only one filename")
     end
+    state.filename = true
+    state.file = io.stdin
+    return "self"
+end
+defs[""] = function(state, token)
+    if state.filename then
+        error("Must specify only one filename")
+    end
+    state.filename = token
+    state.file, state.err = io.open(state.filename, "r")
+    return "self"
+end
+defs[parser.EOZ] = function(state, token)
+    if not state.file then
+        error((state.filename and (state.err or "") or "No file specified") )
+    end
+    return {}
+end
+defs[-1] = function(state, token, rule)
+    if token ~= parser.EOZ and token:sub(1,1) == "-" and not rule then
+        error("Unknown option: " .. token)
+    end
+end
+defs['--'] = parser.selfify({[""] = defs[""]})
+
+local state = parser.parse(defs, arg)
+local luatokens = require "luatokens"
+local file = state.file
+local tokens = luatokens.defs
+local state, err, etoken, estate = parser.parse(tokens, function() return file:read(8192) end)
+if state then
+    for i,v in ipairs(state) do
+        v = luatokens.reverse_keywords[v] or luatokens.reverse_tokens[v] or v
+        print(i, v) -- TODO formatting
+    end
+else
+    print("Parse error")
 end