{{ message }}
-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathrpcq-python.lisp
More file actions
310 lines (281 loc) · 14.1 KB
/
Copy pathrpcq-python.lisp
File metadata and controls
310 lines (281 loc) · 14.1 KB
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; Copyright 2018 Rigetti Computing
;;;;
;;;; Licensed under the Apache License, Version 2.0 (the "License");
;;;; you may not use this file except in compliance with the License.
;;;; You may obtain a copy of the License at
;;;;
;;;; http://www.apache.org/licenses/LICENSE-2.0
;;;;
;;;; Unless required by applicable law or agreed to in writing, software
;;;; distributed under the License is distributed on an "AS IS" BASIS,
;;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;;;; See the License for the specific language governing permissions and
;;;; limitations under the License.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;
;;;; rpcq-python.lisp
;;;;
;;;; Authors: Nikolas Tezak, Eric Peterson
;;;;
(in-package #:rpcq)
(defparameter *python-types*
'(:string "str"
:bytes "bytes"
:float "float"
:integer "int"
:bool "bool"
:map "Dict"
:list "List"
:any "Any"))
(defparameter *python-instance-check-types*
'(:string "basestring"
:bytes "bytes"
:float "float"
:integer "int"
:bool "bool"
:map "dict"
:list "list"
:any "object"))
(defun python-instance-check-type (field-type)
(let ((*python-types* *python-instance-check-types*))
(python-type field-type)))
(defun python-argspec-default (field-type default &optional defaultp)
"Translate DEFAULT values for immutable objects of a given FIELD-TYPE to python.
DEFAULTP indicates whether DEFAULT has a value of NIL because NIL was provided in the DEFMESSAGE (T), or because it was missing in the DEFMESSAGE (NIL)."
(typecase field-type
((eql :string)
(if default
(format nil "~S" default)
"None"))
((eql :bytes)
(if default
(format nil "b~S" (to-string default))
"None"))
((eql :bool)
(cond
((not defaultp) "None")
(default "True")
(t "False")))
((eql :integer)
(if default
(format nil "~d" default)
"None"))
((eql :float)
(if default
(format nil "~e" default)
"None"))
((cons (eql :list))
(if default
(format nil "[~{~S~^, ~}]" default)
"field(default_factory=list)"))
((cons (eql :map))
(when default
(warn "I don't know how to encode default dictionaries into generated python3 output."))
"field(default_factory=dict)")
(otherwise
"None")))
(defun python-type (field-type)
"Always return a basic python type not List[...] or Dict[...] for
instance checks."
(python-typing-type
(if (listp field-type)
(car field-type)
field-type)))
(defun python-typing-type (field-type)
"Return the python typing-module compliant field type"
(etypecase field-type
(keyword
(assert (member field-type *python-types*)
(field-type)
"Unknown field-type ~S" field-type)
(getf *python-types* field-type))
(symbol
;; field-type is assumed to be message object
(format nil "~a" field-type))
((cons (eql :list))
(format nil "List[~a]" (python-typing-type (cadr field-type))))
((cons (eql :map))
(assert (string= (symbol-name (caddr field-type)) "->")
(field-type)
"Bad mapping spec.")
(format nil
"Dict[~a, ~a]"
(python-typing-type (cadr field-type))
(python-typing-type (cadddr field-type))))))
(defun python-maybe-optional-typing-type (field-type required)
"Rerturn the python type string for FIELD-TYPE while
accounting for whether the field is REQUIRED.
"
(let ((b (python-typing-type field-type)))
(if (or required (listp field-type))
b
(format nil "Optional[~a]" b))))
(defun python-collections-initform (field-type default)
"Translate a DEFAULT value of type FIELD-TYPE to a python initform."
(check-type field-type list)
(etypecase field-type
;; handle lists
((cons (eql :list))
(if (null default)
"[]"
(with-output-to-string (s)
(yason:encode default s))))
;; handle mappings
((cons (eql :map))
(if (null default)
"{}"
(with-output-to-string (s)
(yason:encode (%plist-to-string-hash-table default) s))))))
(defun python-message-spec (stream messages &optional parent-modules)
"Print an importable python file with the message definitions."
(flet ((python-out (line-list)
(dolist (line line-list)
(apply 'format stream line)
(terpri stream))
(terpri stream)))
(format stream "~
#!/usr/bin/env python
\"\"\"
WARNING: This file is auto-generated, do not edit by hand. See README.md.
\"\"\"
import sys
from warnings import warn
from rpcq._base import Message
from typing import Any, List, Dict, Optional
if sys.version_info < (3, 7):
from rpcq.external.dataclasses import dataclass, field, InitVar
else:
from dataclasses import dataclass, field, InitVar~%~%")
(format stream "~{from ~a import *~%~}~%" parent-modules)
(dolist (message-spec messages)
(destructuring-bind (msg-name parent-name field-specs documentation) message-spec
;; print the class header
(python-out `(("@dataclass(eq=False, repr=False)")
("class ~a(~a):" ,(symbol-name msg-name)
,(if parent-name
(symbol-name parent-name)
"Message"))
(" \"\"\"")
(" ~a" ,documentation)
(" \"\"\"")))
(let ((deprecated-fields nil))
;; python dataclasses require their fields to be written in the order
;; * required slots
;; * optional slots
;; * deprecated slots
(labels ((requiredp (r)
(and (not (member ':default (rest r)))
(getf (rest r) ':required)))
(optionalp (r)
(not (requiredp r)))
(deprecatedp (r)
(or (getf (cdr r) ':deprecated)
(getf (cdr r) ':deprecated-by))))
(setf field-specs (sort (copy-seq field-specs)
(lambda (r s)
(or (and (requiredp r) (optionalp s))
(and (requiredp r) (deprecatedp s))
(and (optionalp r) (deprecatedp s)))))))
(dolist (field-spec field-specs)
(let* ((slot-name (car field-spec))
(field-settings (cdr field-spec))
(type (getf field-settings ':type))
(required (getf field-settings ':required))
(documentation (getf field-settings ':documentation))
(defaultp (member ':default field-settings))
(default (getf field-settings ':default))
(deprecated (getf field-settings ':deprecated))
(deprecates (getf field-settings ':deprecates))
(deprecated-by (getf field-settings ':deprecated-by)))
;; optional fields automatically acquire a NIL default
(unless (or required defaultp)
(setf default nil)
(setf defaultp t))
;; print the slot descriptor
(cond
;; recipe for a deprecated slot
((or deprecated-by deprecated)
(python-out `((" ~a: InitVar[~a] = None" ,(symbol-name slot-name)
,(python-maybe-optional-typing-type type required))
(" \"\"\"~a\"\"\"" ,documentation)))
(when deprecated
(push (list slot-name nil required "None") deprecated-fields)))
;; recipe for a deprecating slot
(deprecates
(let ((definite-default (python-argspec-default type default (member ':default field-settings))))
(python-out `((" ~a: ~a = ~a" ,(symbol-name slot-name)
,(python-maybe-optional-typing-type type t)
,definite-default)
(" \"\"\"~a\"\"\"" ,documentation)))
(push (list deprecates slot-name required definite-default) deprecated-fields)))
;; recipe for a slot with a default value
(defaultp
(python-out `((" ~a: ~a = ~a" ,(symbol-name slot-name)
,(python-maybe-optional-typing-type type required)
,(python-argspec-default type default
(member ':default field-settings)))
(" \"\"\"~a\"\"\"" ,documentation))))
;; recipe for a slot otherwise
(t
(python-out `((" ~a: ~a" ,(symbol-name slot-name)
,(python-maybe-optional-typing-type type required))
(" \"\"\"~a\"\"\"" ,documentation)))))))
;; deprecated fields need special care.
(when deprecated-fields
;; (1) add fake getters / setters
(dolist (field-spec deprecated-fields)
(destructuring-bind (old new new-required default-value) field-spec
(declare (ignore new-required default-value))
(when new
(python-out `((" @property")
(" def ~a(self):" ,(symbol-name old))
(" warn('~a is deprecated, use ~a instead')" ,(symbol-name old)
,(symbol-name new))
(" return self.~a" ,(symbol-name new))
("")
(" @~a.setter" ,(symbol-name old))
(" def ~a(self, value):" ,(symbol-name old))
(" warn('~a is deprecated, use ~a instead')" ,(symbol-name old)
,(symbol-name new))
(" self.~a = value" ,(symbol-name new)))))))
;; (2) add extra fields to output
(python-out `((" def _extend_by_deprecated_fields(self, d):")
(" super()._extend_by_deprecated_fields(d)")))
(dolist (field-spec deprecated-fields)
(destructuring-bind (old new new-required default-value) field-spec
(declare (ignore new-required default-value))
(when new
(python-out `((" d.~a = d.~a" ,(symbol-name old)
,(symbol-name new)))))))
;; (3) tolerate extra fields on input
(format stream
" def __post_init__(self, ~{~a~^, ~}):~%"
(mapcar (alexandria:compose #'symbol-name #'first) deprecated-fields))
(dolist (field-spec deprecated-fields)
(destructuring-bind (old new new-required default-value) field-spec
(let* ((appearance-index (search "field" default-value))
(default-property-p (and appearance-index (zerop appearance-index))))
(cond
(new
(python-out `(,(if default-property-p
`(" if not isinstance(~a, property):" ,(symbol-name old))
`(" if ~a is not ~a:" ,(symbol-name old)
,default-value))
(" if \"~a\" not in self.__dict__ or self.~a is None:" ,(symbol-name new)
,(symbol-name new))
(" warn('~a is deprecated, use ~a instead')" ,(symbol-name old)
,(symbol-name new))
(" self.__dict__[\"~a\"] = ~a~%" ,(symbol-name new)
,(symbol-name old))))
(when new-required
(python-out `((" if \"~a\" not in self.__dict__ or self.~a is None:" ,(symbol-name new)
,(symbol-name new))
(" raise(TypeError(\"~a is a required key.\"))~%" ,(symbol-name new))))))
(t
(python-out `(,(if default-property-p
`(" if not isinstance(~a, property):" ,(symbol-name old))
`(" if ~a is not ~a:" ,(symbol-name old)
,default-value))
(" warn('~a is deprecated; please don\\'t set it anymore')" ,(symbol-name old)))))))))))
(python-out '())))))
You can’t perform that action at this time.
