 ;; ANTLR Lexer Javadoc:
 ;; http://www.antlr.org/api/Java-master/org/antlr/v4/runtime/Lexer.html
 
-(def ^:dynamic *lexrules* (atom {}))
+(def ^:dynamic *tokmap* (atom nil))
+(def ^:dynamic *rulemap* (atom nil))
+
+(defn- settoks [^String grammar]
+  (let [lexname (str grammar "Lexer")
+        lxr (eval `(new ~(Class/forName lexname) nil))
+        toks (.getTokenNames lxr)
+        tokmap (.getTokenTypeMap lxr)]
+    (doall (map #(do
+                   (swap!  *tokmap* assoc (.getValue %) (.getKey %))
+                   ;;(println %)
+                   )
+                tokmap))
+    ;; (doseq [[k v] (sort @*tokmap*)]
+    ;;   (println k ": " v))
+    nil))
+
+(defn tokmap [^String grammar]
+  (if (nil? @*tokmap*)
+    (println (format "tokmap for %s not set; run lex-string to set it" grammar))
+    (doseq [[k v] (sort @*tokmap*)]
+      (println k ": " v))))
+
+(defn- setrules [^String grammar]
+  (let [lexname (str grammar "Lexer")
+        lxr (eval `(new ~(Class/forName lexname) nil))
+        rules (.getRuleNames lxr)
+        rulemap (.getRuleIndexMap lxr)]
+    ;;(doall (map (fn [[k v] %] (println k)) rulemap))
+    (doall (map #(do
+                   (swap!  *rulemap* assoc (+ 1 (.getValue %)) (.getKey %))
+                   ;(println (+ 1(.getValue %)) (.getKey %))
+                   )
+                rulemap))
+    nil))
+
+(defn rule [^long i]
+  (@*rulemap* i))
+
+(defn rulemap [^String grammar]
+  (if (nil? @*rulemap*)
+    (println (format "rulemap for %s not set; run lex-string to set it" grammar))
+    (doseq [[k v] (sort @*rulemap*)]
+      (println k ": " v))))
 
 (defn lex-file
   [^String grammar ;; e.g. "org.mobileink.antlr.sym"

        devnull (.setInputStream lxr strinput)
        tokens (CommonTokenStream. lxr)

        parsername (str grammar "Parser")

        foo (macroexpand `(new ~(Class/forName parsername)
                               (CommonTokenStream.
                                (new ~(Class/forName lexname)
                                     (ANTLRInputStream. ~the-string)))))

        parser (eval foo) ;;`(new ~(Class/forName parsername) #=tokens))

        tree (do ;;(println "getting tree")
               (.id_kw parser)) ; method name = start rule in grammar
        ]

    (do
      (.fill tokens)
      (let
          [seqtoks (iterator-seq (.iterator (.getTokens tokens)))]

                        (print (format "%s  %s %s\n"
                                       (.toString tok)
                                       (.getType tok)
                                       (get @*tokmap* (.getType tok)))))
                      seqtoks))
          ;; (println (.toStringTree tree))
          ;;(println (.getText tree))
          ))))
  nil)

