Skip to content

Instantly share code, notes, and snippets.

@sogaiu

sogaiu/janet.clj

Last active Apr 8, 2021
Embed
What would you like to do?
using tree-sitter in clojure via janet bindings...to parse clojure code
(ns libjanet-clj.janet
(:require
[tech.v3.datatype.ffi :as dt-ffi]))
(set! *warn-on-reflection* true)
;; XXX: may need export LD_LIBRARY_PATH=... depending on setup
(def janet-def
{:janet_init {:rettype :int16
:argtypes []}
:janet_core_env {:rettype :pointer
:argtypes [['replacements :pointer?]]}
:janet_dostring {:rettype :int16
:argtypes [['env :pointer?]
['code :string]
['src_path :string]
['out :pointer?]]}
:janet_deinit {:rettype :void
:argtypes []}})
(defonce janet
(dt-ffi/library-singleton #'janet-def))
(dt-ffi/library-singleton-reset! janet)
(defn set-library-instance!
[lib-instance]
(dt-ffi/library-singleton-set-instance! janet lib-instance))
(defn initialize!
[]
(dt-ffi/library-singleton-set! janet "janet"))
(defn find-fn
[fn-name]
(dt-ffi/library-singleton-find-fn janet fn-name))
(dt-ffi/define-library-functions
libjanet-clj.janet/janet-def find-fn nil)
(comment
(initialize!)
;; => #object[tech.v3.datatype.ffi.jna.G__7690 0x510bbee6 {:status :ready, :val {:janet_deinit #object[tech.v3.datatype.ffi.jna.G__7690$invoker_janet_deinit 0x1e543351 "tech.v3.datatype.ffi.jna.G__7690$invoker_janet_deinit@1e543351"], :janet_dostring #object[tech.v3.datatype.ffi.jna.G__7690$invoker_janet_dostring 0xb8e1c39 "tech.v3.datatype.ffi.jna.G__7690$invoker_janet_dostring@b8e1c39"], :janet_init #object[tech.v3.datatype.ffi.jna.G__7690$invoker_janet_init 0x466eb02f "tech.v3.datatype.ffi.jna.G__7690$invoker_janet_init@466eb02f"], :janet_core_env #object[tech.v3.datatype.ffi.jna.G__7690$invoker_janet_core_env 0x490500ed "tech.v3.datatype.ffi.jna.G__7690$invoker_janet_core_env@490500ed"]}}]
(janet_init)
;; => 0
(def my-env
(janet_core_env nil))
;; => #'libjanet-clj.janet/my-env
(janet_dostring my-env
"(spit `/tmp/smile.txt` `yes!`)"
"here"
nil)
;; => 0
(slurp "/tmp/smile.txt")
;; => "yes!"
;; XXX: need to create and populate appropriately in project dir:
;;
;; rm -rf jpm-modules && mkdir jpm-modules
;; export JANET_PATH=$(pwd)/jpm-modules
;; jpm deps
(def jpm-dir
(str (System/getProperty "user.dir")
"/jpm-modules"))
(janet_dostring my-env
(str "(setdyn :syspath `" jpm-dir "`)"
"\n"
"(import janet-tree-sitter/tree-sitter)\n"
"\n"
"(def p (tree-sitter/init `clojure`))\n"
"\n"
"(def t (:parse p nil @[`(defn my-fn [] (+ 1 1))`]))\n"
"\n"
"(def rn (:root-node t))\n"
"\n"
"(spit `/tmp/ljc-jts-test.txt` (:expr rn))\n")
"from-comment-block"
nil)
;; (source (list_lit value: (sym_lit) value: (sym_lit) value: (vec_lit) value: (list_lit value: (sym_lit) value: (num_lit) value: (num_lit))))
(print (slurp "/tmp/ljc-jts-test.txt"))
;; => nil
(janet_deinit)
;; => nil
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment