Skip to content

Instantly share code, notes, and snippets.

@mrb
Last active December 14, 2015 17:29
Show Gist options
  • Save mrb/5122568 to your computer and use it in GitHub Desktop.
Save mrb/5122568 to your computer and use it in GitHub Desktop.
Using JRuby's Ruby Parser from Clojure
(ns graaaph.core
(:import (org.jrubyparser Parser
CompatVersion)
(org.jrubyparser.parser ParserConfiguration)
(org.jrubyparser.ast Node)
(java.io.StringReader))
(:require [clojure.zip :as z]))
(defn parse-ruby [ruby-string]
(let [config (ParserConfiguration. 0 (CompatVersion/RUBY1_9))
reader (java.io.StringReader. ruby-string)
parser (Parser.)]
(.parse parser "" reader config)))
(defn has-children? [nodes]
(not (nil? (-> nodes
.childNodes
first))))
(defn get-children [nodes]
(.childNodes nodes))
(def c (parse-ruby "module Cool;class Dude;def sick;'siiiick';end;def bro;'whoooah';end;end;end"))
(defn code-zipper [nodes]
(z/zipper has-children? get-children (fn [_ c] c) nodes))
(def zipped-code (code-zipper c))
(-> zipped-code
z/down
z/down
z/down
z/node)
;; graaaph.core=> c
;; #<RootNode (RootNode, (NewlineNode, (ModuleNode, (Colon2ImplicitNode:Cool), (NewlineNode, (ClassNode, (Colon2ImplicitNode:Dude), (BlockNode, (NewlineNode, (DefnNode:sick, (ArgumentNode:sick), (ArgsNode), (NewlineNode, (StrNode)))), (NewlineNode, (DefnNode:bro, (ArgumentNode:bro), (ArgsNode), (NewlineNode, (StrNode))))))))))>
;; graaaph.core=> (-> zipped-code
;; z/down
;; z/down
;; z/down
;; z/node)
;; #<Colon2ImplicitNode (Colon2ImplicitNode:Cool)>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment