forked from clj-python/libpython-clj
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcodegen.clj
209 lines (181 loc) · 7.84 KB
/
codegen.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
(ns libpython-clj2.codegen
"Generate a namespace on disk for a python module or instances"
(:require [clojure.java.io :as io]
[libpython-clj2.python :as py]
[clojure.string :as s]
[clojure.tools.logging :as log])
(:import [java.nio.file Paths]
[java.io Writer]))
(defn- escape-quotes
[input-str]
(if input-str
(-> (.replace (str input-str) "\\" "\\\\")
(.replace "\"" "\\\""))
""))
(defn- get-docs
[v]
(escape-quotes (:doc v "No documentation")))
(defn- output-module-list
[^Writer writer clj-name k v]
(.write writer
(format "
(def ^{:doc \"%s\"} %s (as-jvm/generic-python-as-list (py-global-delay (py/get-attr @src-obj* \"%s\")))) "
(get-docs v)
clj-name
k)))
(defn- output-module-tuple
[^Writer writer clj-name k v]
(.write writer
(format "
(def ^{:doc \"%s\"} %s (as-jvm/generic-python-as-list (py-global-delay (py/get-attr @src-obj* \"%s\")))) "
(get-docs v)
clj-name
k)))
(defn- output-module-dict
[^Writer writer clj-name k v]
(.write writer
(format "
(def ^{:doc \"%s\"} %s (as-jvm/generic-python-as-map (py-global-delay (py/get-attr @src-obj* \"%s\")))) "
(get-docs v)
clj-name
k)))
(defn- output-module-callable
[^Writer writer clj-name k v]
(.write writer
(format "
(def ^{:doc \"%s\" :arglists '%s} %s (as-jvm/generic-callable-pyobject (py-global-delay (py/get-attr @src-obj* \"%s\"))))"
(get-docs v)
(:arglists v)
clj-name
k
clj-name)))
(defn- output-module-generic
[^Writer writer clj-name k v vv]
(let [output-value (cond
;;nils and boolean require no extra formatting
(or (nil? vv) (boolean? vv)) vv
;;string values should be output surrounded by double quotes
(string? vv) (format "\"%s\"" (escape-quotes vv))
;;NaN is a number and should use the proper reader macro
(and (number? vv) (Double/isNaN vv)) "##NaN"
;;Finite, non NAN numbers should be treated as literals
(and (number? vv) (Double/isFinite vv)) vv
;;Positive and negative infinity are numbers and should use the proper reader macros
(and (number? vv) (not (neg? vv)) (Double/isInfinite vv)) "##Inf"
(and (number? vv) (neg? vv) (Double/isInfinite vv)) "##-Inf"
;;Anything else should be derefed by name from Python
:else (format "(as-jvm/generic-pyobject (py-global-delay (py/get-attr @src-obj* \"%s\")))" k)
)]
(.write writer
(format "\n\n(def ^{:doc \"%s\"} %s %s)"
(get-docs v)
clj-name
output-value))))
(def ^:no-doc default-exclude
'[+ - * / float double int long mod byte test char short take partition require
max min identity empty mod repeat str load cast type sort conj
map range list next hash eval bytes filter compile print set format
compare reduce merge])
(def ^:private invalid-symbol-names
#{"__cached__" "__file__"})
(defn write-namespace!
"Generate a clojure namespace file from a python module or class. If python hasn't
been initialized yet this will call the default python initialization. Accessing
the generated namespace without initialization will cause an error.
Once generated this namespace is safe to be used for AOT,
Options:
* `:output-fname` - override the autogenerated file path.
* `:output-dir` - Defaults \"src\". Set the output directory. The final filename,
if `:output-fname` is not provided, is built up from `:ns-prefix and
`py-mod-or-cls`.
* `:ns-symbol` - The fully qualified namespace symbol. If not provided is built
from `:ns-prefix` and `py-mod-or-cls`.
* `:ns-prefix` - The prefix used for all python namespaces. Defaults to \"python\".
* `:symbol-name-remaps` - A list of remaps used to avoid name clashes with
clojure.core or builtin java symbols.
* `:exclude` - List of symbols used like `(:refer-clojure :exclude %s)`. You can
see the default list as `codegen/default-exclude`.
Example:
```clojure
user> (require '[libpython-clj2.codegen :as codegen])
nil
user> (codegen/write-namespace!
\"builtins\" {:symbol-name-remaps {\"AssertionError\" \"PyAssertionError\"
\"Exception\" \"PyException\"}})
:ok
user> (require '[python.builtins :as python])
nil
user> (doc python/list)
-------------------------
python.builtins/list
[[self & [args {:as kwargs}]]]
Built-in mutable sequence.
If no argument is given, the constructor creates a new empty list.
The argument must be an iterable if specified.
nil
user> (doto (python/list)
(.add 1)
(.add 2))
[1, 2]
```"
([py-mod-or-cls {:keys [output-fname output-dir ns-symbol
ns-prefix symbol-name-remaps exclude]
:or {output-dir "src"
ns-prefix "python"
exclude default-exclude}}]
(let [metadata-fn (requiring-resolve
'libpython-clj2.metadata/datafy-module-or-class)
ns-symbol (or ns-symbol (symbol (str ns-prefix "." py-mod-or-cls)))]
(py/with-gil-stack-rc-context
(let [target (py/path->py-obj py-mod-or-cls)
target-metadata (metadata-fn target)
output-fname (or output-fname
(-> (->> (-> (str ns-symbol)
(.replace "-" "_")
(s/split #"\."))
(into-array String)
(Paths/get output-dir))
(str ".clj")))]
(log/debugf "Writing python module %s to file %s" target output-fname)
(io/make-parents output-fname)
(with-open [writer (io/writer output-fname)]
(.write writer (format "(ns %s
\"%s\"
(:require [libpython-clj2.python :as py]
[libpython-clj2.python.jvm-handle :refer [py-global-delay]]
[libpython-clj2.python.bridge-as-jvm :as as-jvm])
(:refer-clojure :exclude %s))"
(name ns-symbol)
(escape-quotes
(get target "__doc__" "No documentation provided"))
(or exclude [])))
(.write writer
(format "\n\n(defonce ^:private src-obj* (py-global-delay (py/path->py-obj \"%s\")))"
py-mod-or-cls))
(doseq [[k v] target-metadata]
(when (and (string? k)
(not= "__cached__" k)
(not= 0 (count k))
(map? v)
(py/has-attr? target k))
(let [clj-name (get symbol-name-remaps k k)]
(case (:type v)
:list (output-module-list writer clj-name k v)
:tuple (output-module-tuple writer clj-name k v)
:dict (output-module-dict writer clj-name k v)
(if (:callable? (:flags v))
(output-module-callable writer clj-name k v)
(output-module-generic writer clj-name k v
(py/get-attr target k))))))))
:ok))))
([py-mod-or-cls]
(write-namespace! py-mod-or-cls nil)))
(comment
(do
(write-namespace! "builtins"
{:symbol-name-remaps
{"AssertionError" "PyAssertionError"
"Exception" "PyException"}})
(write-namespace! "numpy")
)
)