Created
July 19, 2020 18:11
-
-
Save allison-casey/33da1d7777bc7727a3140b7d328d7ebb to your computer and use it in GitHub Desktop.
Hy Jedi Completions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; %% | |
(import os | |
jedi | |
astor | |
re | |
[hy.compiler [hy-compile]] | |
[hy.lex [hy-parse mangle unmangle]] | |
[hy.cmdline [filtered-hy-exceptions]]) | |
;; %% | |
(defn compile | |
[source &optional [with-source False] [with-ast False] [without-python False]] | |
(setv filename "<stdin>" | |
out (dict :source None :python None)) | |
(with [_ (filtered_hy_exceptions)] | |
(setv hst (hy-parse source :filename filename))) | |
(when with-source | |
(setv (get out "filename") hst)) | |
(with [_ (filtered-hy-exceptions)] | |
(setv -ast (hy-compile hst "__main__" :filename filename :source source))) | |
(unless without-python | |
(setv (get out "python") (astor.code-gen.to-source -ast))) | |
out) | |
(setv -placeholder-sentinel "___COMPLETION_PLACERHOLDER___") | |
(defn get-placeholder-location [source] | |
(for [(, linno line) (enumerate (source.splitlines) 1)] | |
(when (in -placeholder-sentinel line) | |
(setv start (line.find -placeholder-sentinel) | |
end (+ start (len -placeholder-sentinel))) | |
(return (, linno start))))) | |
(defn find-attribute-location [source obj attribute] | |
(setv s f"{obj}.{attribute}") | |
(for [(, linno line) (enumerate (source.splitlines) 1)] | |
(when (in s line) | |
(setv start (line.find s)) | |
(return (, linno (+ start (len s))))))) | |
(defn complete [src lineno column] | |
(setv | |
completion-line (cut (get (src.splitlines) (dec cursor-line)) 0 cursor-column) | |
match (re.search r"(.*)?\.(.+?)[\(\s\[]" (cut completion-line None None -1)) | |
(, attribute obj) (map (fn [x] (cut x None None -1)) (match.groups))) | |
(if (not attribute) | |
(setv | |
generated (get (compile src) "python") | |
(, lineno column) (get-placeholder-location generated) | |
generated (.replace generated -placeholder-sentinel "")) | |
(setv generated (get (compile src) "python") | |
(, lineno column) (find-attribute-location generated (mangle obj) (mangle attribute)))) | |
(setv script (jedi.Script generated)) | |
(script.complete lineno column)) | |
;; %% | |
(setv source " | |
(setv something [1 2 3 4]) | |
(print (something.)) | |
" | |
cursor-line 3 | |
cursor-column 18) | |
;; %% | |
(setv source " | |
(import json) | |
(json.lo) | |
" | |
cursor-line 3 | |
cursor-column 8) | |
;; %% | |
(lfor completion (complete source cursor-line cursor-column) | |
completion.name) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment