/
condition.cljc
627 lines (542 loc) · 22.9 KB
/
condition.cljc
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
(ns active.clojure.condition
"Conditions, protocol for communicating the causes of exceptions.
This provides infrastructure for building *condition* objects.
A condition object provides information about the cause of an exception.
Conditions thus form a protocol.
Clojure `ex-info` objects do not, by themselves, enough to form such
a protocol, as they do not allow classifying an exception easily.
This condition system builds on the design of
[R6RS Scheme](http://www.r6rs.org/final/html/r6rs-lib/r6rs-lib-Z-H-8.html#node_sec_7.2).
Condition objects are represented as specially marked `ex-info` objects.
One notable difference to the R6RS design is that there is no user-facing type for
'simple conditions', nor are they regular records."
(:refer-clojure :exclude (assert))
#?(:clj (:require [clojure.core :as core] ; get assert back
[clojure.stacktrace :as stack]
[clojure.main :as main]))
#?(:clj (:require [io.aviso.exception :as aviso-exception]
[io.aviso.columns :as aviso-columns]
[io.aviso.ansi :as aviso-ansi]
[clojure.string :as string]
[active.clojure.macro :refer (if-cljs)]))
#?(:cljs (:require-macros [active.clojure.condition
:refer (define-condition-type assert condition raise guard throw-condition)]
[active.clojure.macro :refer (if-cljs)]
[cljs.core :as core]))
#?(:clj (:import clojure.lang.ExceptionInfo)))
(defn condition?
[x]
(and #?(:clj (instance? ExceptionInfo x))
(contains? (ex-data x) ::condition)))
;; Printing conditions in ClojureScript:
;;
;; TODO `print-method` does not exist in ClojureScript and there is no
;; other way to define how an object should print itself. For now,
;; you have to call `print-condition` yourself.
;;
;; TODO `*ns*` does not exist in ClojureSript. Therefore, it would be
;; nice to have at least file name and line number information stored
;; in `ex-info-msg`, but this does not work:
;;
;; (let [e (new js/Error "message" "file" 23)]
;; (println (.-message e))
;; (println (.-fileName e))
;; (println (.-lineNumber e)))
;;
;; as it prints
;;
;; message
;; nil
;; nil
;;
;; TODO Also, there is no run-time-independent way to get a stack
;; trace in ClojureScript.
#?(:clj (declare print-condition))
#?(:clj
(defmethod print-method ExceptionInfo [^ExceptionInfo exc ^java.io.Writer w]
(if (condition? exc)
(print-condition exc w)
(.write w (str "clojure.lang.ExceptionInfo: " (.getMessage exc) " " (str (ex-data exc)))))))
(defn ^:private ex-info-msg
[namespace]
(str "This is a " namespace " active.clojure.condition."))
(defrecord ConditionType
[name supertype field-names total-field-count])
#?(:clj
(defmethod print-method ConditionType [^ConditionType ct ^java.io.Writer w]
(.write w (name (:name ct)))))
(def ^{:doc "Root of the condition-type hierarchy."}
&condition
(ConditionType. '&condition nil [] 0))
(defrecord ConditionComponent
[type arguments])
#?(:clj
(defmethod print-method ConditionComponent [^ConditionComponent cc ^java.io.Writer w]
(print-method (:type cc) w)
(.write w ": ")
(print-method (:arguments cc) w)))
(defn- condition-component?
"Is object a condition component?"
[x]
(instance? ConditionComponent x))
(defn- condition-subtype?
"Is `ty1` subtype of `ty2`?"
[ty1 ty2]
(or (= ty1 ty2)
(if-let [st (:supertype ty1)]
(condition-subtype? st ty2)
false)))
(defn- condition-component-of-condition-type?
"Does condition component `comp` have condition type `type`?"
[type comp]
(condition-subtype? (:type comp) type))
(defn- condition-components
"Extract components from condition."
[cond]
{:pre [(condition? cond)]}
(::components (ex-data cond)))
(declare &message)
(defn make-condition
"Make a condition from components.
For internal use only."
[condition-components]
(ex-info (or (some (fn [cmp]
(and (condition-component-of-condition-type? &message cmp)
(first (:arguments cmp))))
condition-components)
#?(:clj (ex-info-msg *ns*))
#?(:cljs (ex-info-msg "<cljs>")))
{::condition true
::components condition-components}))
#?(:clj
(defn stack-trace-who
"Get a suitable argument for [[&who]] from an exception object."
[st]
;; the top is the let, above that it's stack-trace-who itself
(if-let [^StackTraceElement e (nth st 2)]
(let [class (.getClassName e)
method (.getMethodName e)]
;; adapted from clojure.stacktrace
(let [match (re-matches #"^([A-Za-z0-9_.-]+)\$(\w+)$" (str class))]
(if (and match (= "invoke" method))
(apply format "%s/%s" (rest match))
(format "%s.%s" class method)))))))
(declare make-throwable make-error make-assertion-violation make-message-condition make-who-condition)
#?(:clj
(defn ->condition
"Coerce something into a condition object.
This yields `thing` if it's already a condition,
and an [[&exception]] condition if it's not."
[thing]
(cond
(condition? thing) thing
(instance? Throwable thing)
(let [^Throwable throwable thing]
(make-condition (mapcat condition-components
(filter identity
[(make-throwable throwable)
(make-message-condition (.getMessage throwable))
(cond
(instance? Exception throwable) (make-error)
(instance? Error throwable) (make-assertion-violation)
:else nil)
(make-who-condition (stack-trace-who (.getStackTrace throwable)))]))))
:else (clojure.core/assert (instance? Throwable thing) "not a throwable"))))
#?(:cljs
(defn ->condition
"Coerce something into a condition object.
This yields `thing` if it's already a condition,
and an [[&exception]] condition if it's not."
[thing]
(if (condition? thing)
thing
(make-throwable thing))))
(defn combine-conditions
"Make a compound condition from constituents.
`nil` and `false` arguments are ignored."
[& component-conditions]
(make-condition (mapcat (comp condition-components ->condition) (filter identity component-conditions))))
(defn condition-of-type?
"Does condition `cond` have type `type`?"
[type cond]
(some (partial condition-component-of-condition-type? type) (::components (ex-data cond))))
(defn condition-predicate
"Make predicate from condition type."
[type]
(fn [x]
(and (condition? x)
(condition-of-type? type x))))
#?(:cljs
(defn index-of [coll v]
(let [i (count (take-while #(not= v %) coll))]
(when (or (< i (count coll))
(= v (last coll)))
i))))
(defn- field-index
"Compute the field index of field named `field-name` for type `type`."
[type field-name]
(let [#?(:clj ^java.util.List fn)
#?(:cljs fn) (:field-names type)
local-index (#?(:clj .indexOf) #?(:cljs index-of) fn field-name)]
(core/assert (not= -1 local-index))
(if-let [supertype (:supertype type)]
(+ (:total-field-count supertype)
local-index)
local-index)))
#?(:cljs
(def Error js/Error))
(defn condition-accessor
"Create an an accessor for `field-name` for conditions of type `type`."
[type field-name]
(let [i (field-index type field-name)]
(fn [cond]
{:pre [(condition? cond)
(condition-of-type? type cond)]}
(if-let [comp
(some (fn [comp]
(and (condition-component-of-condition-type? type comp)
comp))
(::components (ex-data cond)))]
(nth (:arguments comp) i)
(throw (new Error (str cond " is not a condition of type " type)))))))
#?(:clj
(defmacro define-condition-type
" (define-condition-type <condition-type>
<supertype>
<constructor> <predicate>
[<field> <accessor> ...)
`<Condition-type>`, `<supertype>`, `<constructor>`, and
`<predicate>` must all be identifiers. Each `<field>` and `<accessor>`
must be identifiers.
The `define-condition-type` form defines a condition type named
`<condition-type>`. It will have <supertype> has its parent type. The
remaining identifiers will be bound as follows:
`<Constructor>` is bound to a constructor for the type: It accepts
one argument for each of the condition type's complete set of fields
(including parent types, with the fields of the parent coming before
those of the extension in the arguments) and returns a condition
object initialized to those arguments.
`<Predicate>` is bound to a predicate that identifies conditions of
type `<condition-type>` or any of its subtypes.
Each `<accessor>` is bound to a function that extracts the
corresponding field from a condition of type `<condition-type>`.
`:doc` properties attached to the metadata of `<condition-type>` and
`the <field>s will yield proper docstrings for the names defined by this form."
[?condition-type ?supertype ?constructor ?predicate & ?field-specs]
(let [?field-pairs (if (and (= 1 (count ?field-specs))
(vector? (first ?field-specs)))
(partition 2 (first ?field-specs))
;; legacy syntax
?field-specs)
document (fn [n doc]
(vary-meta n
(fn [m]
(if (contains? m :doc)
m
(assoc m :doc doc)))))
document-with-arglist (fn [n arglist doc]
(vary-meta n
(fn [m]
(let [m (if (contains? m :doc)
m
(assoc m :doc doc))]
(if (contains? m :arglists)
m
(assoc m :arglists `'(~arglist)))))))
name-doc (fn [field]
(if-let [doc (:doc (meta field))]
(str " (" doc ")")
""))
reference (fn [name]
(str "[[" (ns-name *ns*) "/" name "]]"))
?docref (str "See " (reference ?condition-type) ".")]
`(do
(let [total-field-count# (+ ~(count ?field-pairs) (:total-field-count ~?supertype))]
(def ~(vary-meta ?condition-type
(fn [m]
(assoc m :doc
(str (or (get m :doc)
"Condition type.")
"\n"
(apply str
(map (fn [[?field ?accessor]]
(str "\n`" ?field "`" (name-doc ?field) ": access via " (reference ?accessor)))
?field-pairs))))))
(->ConditionType '~(symbol (str *ns*) (name ?condition-type)) ~?supertype
'[~@(map first ?field-pairs)] total-field-count#))
(def ~(document ?constructor
(str "Construct a " (reference ?condition-type) " condition."))
(fn [& args#]
{:pre [(= (count args#) total-field-count#)]}
(make-condition [(->ConditionComponent ~?condition-type (vec args#))])))
(def ~(document-with-arglist ?predicate '[thing]
(str "Is object a " (reference ?condition-type) " condition?"))
(condition-predicate ~?condition-type))
~@(map (fn [[?field-name ?accessor]]
`(def ~(document-with-arglist ?accessor
(vector ?condition-type)
(str "Access the `" ?field-name "`" (name-doc ?field-name)
" field from a " (reference ?condition-type) " condition."))
(condition-accessor ~?condition-type '~?field-name)))
?field-pairs))))))
; These standard condition types correspond directly to R6RS Scheme
(define-condition-type ^{:doc "Human-reaable message."} &message &condition
make-message-condition message-condition?
[^{:doc "message text"} message condition-message])
(define-condition-type ^{:doc "Non-fatal warning."} &warning &condition
make-warning warning?
[])
(define-condition-type ^{:doc "Serious condition that should not be ignored."} &serious &condition
make-serious-condition serious-condition?
[])
(define-condition-type ^{:doc "Error from environment, not preventable by the program."} &error &serious
make-error error?
[])
(define-condition-type ^{:doc "Bug in the program."} &violation &serious
make-violation violation?
[])
(define-condition-type ^{:doc "Violation of a specific assertion."} &assertion &violation
make-assertion-violation assertion-violation?
[])
(define-condition-type ^{:doc "Condition with objects providing more information about an exceptional situation."} &irritants &condition
make-irritants-condition irritants-condition?
[^{:doc "objects providing more information"} irritants condition-irritants])
(define-condition-type ^{:doc "Information about in what entity an exceptional situation occurred."} &who &condition
make-who-condition who-condition?
[^{:doc "name of the entity"} who condition-who])
(define-condition-type ^{:doc "Location information about an exceptional situation"} &location &condition
make-location-condition location-condition?
;; any of these can be nil
[^{:doc "namespace of the location"} namespace location-condition-namespace
^{:doc "file name of the location"} file location-condition-file
^{:doc "line number of the loocation"} line location-condition-line])
(define-condition-type
^{:doc "Throwable value that's not a condition."} &throwable &serious
make-throwable throwable?
[^{:doc "Throwable object"} value throwable-value])
#?(:clj
(defmacro throw-condition
"Throw a condition.
For internal use."
[?base ?who ?message ?irritants]
`(let [g# (group-by (fn [thing#] (or (condition? thing#) (if-cljs (instance? js/Error thing#) (instance? Throwable thing#)))) ~?irritants)
irritants# (get g# false)
conditions# (get g# true)
who# ~?who]
(throw (apply combine-conditions
~?base
(and who# (make-who-condition who#))
(make-message-condition ~?message)
(and (not-empty irritants#) (make-irritants-condition irritants#))
conditions#)))))
(defn error
"Throw an exception that signals that an error has occurred.
This function should be called when an error has occurred,
typically caused by something that has gone wrong in the interaction
of the program with the external world or the user.
The `irritants` arguments can be conditions, in which case they're included
in the resulting condition, or non-conditions, which are included in an
[[&irritants]] condition."
[who message & irritants]
(throw-condition (make-error) who message irritants))
(defn assertion-violation
"Throw an exception that signals that an assertion was violated.
This should be called when an invalid call to a procedure was made,
either passing an invalid number of arguments, or passing an argument
that it is not specified to handle.
The `irritants` arguments can be conditions, in which case they're included
in the resulting condition, or non-conditions, which are included in an
[[&irritants]] condition.
On Java, `irritants` can also include ``Throwable`` objects."
[who message & irritants]
(throw-condition (make-assertion-violation) who message irritants))
#?(:clj
(defmacro assert
"Evaluates expr and throws an exception if it does not evaluate to
logical true."
([x]
(when *assert*
(let [?ns (str *ns*)
?file (let [f *file*] (when (not= f "NO_SOURCE_PATH") f))
;; TODO Waiting on http://dev.clojure.org/jira/browse/CLJ-865:
?line (:line (meta &form))]
`(when-not ~x
(assertion-violation (if-cljs
nil
(stack-trace-who (.getStackTrace (Thread/currentThread))))
(str "Assertion failed")
(make-location-condition '~?ns ~?file ~?line)
'~x)))))
([x message]
(when *assert*
(let [?ns (str *ns*)
?file (let [f *file*] (when (not= f "NO_SOURCE_PATH") f))
;; TODO Waiting on http://dev.clojure.org/jira/browse/CLJ-865:
?line (:line (meta &form))]
`(when-not ~x
(assertion-violation (if-cljs
nil
(stack-trace-who (.getStackTrace (Thread/currentThread))))
(str "Assert failed: " ~message)
(make-location-condition '~?ns ~?file ~?line)
'~x)))))))
#?(:clj
(defmacro condition
[?base ?message & ?irritants]
`(combine-conditions ~?base
(if-cljs
nil
(make-who-condition (stack-trace-who (.getStackTrace (Thread/currentThread)))))
(make-message-condition ~?message)
(make-irritants-condition [~@?irritants]))))
#?(:clj
(defmacro raise
[?base ?message & ?irritants]
`(throw (condition ~?base ~?message ~@?irritants))))
#?(:cljs
(def Throwable js/Object))
#?(:clj
(defmacro guard
[?handling & ?body]
(when-not (vector? ?handling)
(throw (IllegalArgumentException. (str "guard requires vector in " *ns* " " (meta &form)))))
(when-not (odd? (count ?handling))
(throw (IllegalArgumentException. (str "guard requires vector in " *ns* " " (meta &form)))))
(let [?id (first ?handling)]
`(try
~@?body
; If Throwable is not a symbol it means java.lang.Throwable which does not work in ClojureScript.
(catch ~'Throwable ~?id
(cond
~@(rest ?handling)
~@(if (= :else (last (butlast ?handling)))
`()
`(:else (throw ~?id)))))))))
(defn delete-first
[pred? l]
(letfn [(recurse [l]
(cond
(empty? l) l
(pred? (first l)) (rest l)
:else
(cons (first l) (recurse (rest l)))))]
(recurse l)))
;; Turning this into a constant def screws things up somehow.
(defn covered-condition-types
[]
#{&error &assertion &serious &violation})
(defn decode-condition
"Return a keyword describing the type,
a symbol or string describing the source of the problem, an error
message or nil, and a sequence of other objects describing the
problem.
Valid type symbols include: `:error`, `:assertion-violation`,
`:violation`, `:serious`."
[con]
;; adapted from Scheme 48
(let [type (cond
(error? con) :error
(assertion-violation? con) :assertion-violation
(violation? con) :violation
(serious-condition? con) :serious
:else 'unknown)
who (and (who-condition? con)
(condition-who con))
message (and (message-condition? con)
(condition-message con))
stuff (if (irritants-condition? con)
(condition-irritants con)
[])
more-stuff (delete-first
(fn [comp] ; make sure interesting subtypes still get printed
(contains? (covered-condition-types)
(:type comp)))
;; we don't expect interesting subtypes here
(delete-first
(partial condition-component-of-condition-type? &message)
(delete-first
(partial condition-component-of-condition-type? &who)
(delete-first
(partial condition-component-of-condition-type? &irritants)
(condition-components con)))))]
[type who message (concat stuff more-stuff)]))
#?(:clj
(defn- preformat-stack-frame
[frame]
(cond
(:omitted frame)
(assoc frame :formatted-name "..."
:file ""
:line nil)
;; When :names is empty, it's a Java (not Clojure) frame
(-> frame :names empty?)
(let [formatted-name (str (:class frame) "." (:method frame))]
(assoc frame
:formatted-name formatted-name))
:else
(let [names (:names frame)
formatted-name (str
(->> names drop-last (string/join "/"))
"/"
(last names))]
(assoc frame :formatted-name formatted-name)))))
#?(:clj
(defn print-stack-trace-of
[writer exception]
(let [elements (map preformat-stack-frame (aviso-exception/expand-stack-trace exception))]
(aviso-columns/write-rows writer [:formatted-name
" "
:file
[#(if (:line %) ": ") :left 2]
#(-> % :line str)]
elements))))
#?(:clj
(defn print-condition
[c ^java.io.Writer w]
(binding [*out* w]
(let [[type who message stuff] (decode-condition c)]
(doto w
(.write (name type))
(.write ": "))
(cond
(nil? message) (print "<no message>")
(string? message) (let [^String s message]
(.write w s))
:else (print message))
(let [^String spaces
(apply str (repeat (+ (count (name type)) 2)
\space))]
(when who
(.write w " [")
(print who)
(.write w "]"))
(binding [*print-length* 12]
(doseq [irritant stuff]
(doto w
(.write "\n")
(.write spaces))
(pr irritant))
(.write w "\n"))))
(print-stack-trace-of w c))))
#?(:cljs
(defn print-condition
[c]
(let [[type who message stuff] (decode-condition c)]
(print (name type))
(print ": ")
(cond
(nil? message) (print "<no message>")
(string? message) (print message)
:else (print message))
(let [spaces
(apply str (repeat (+ (count (name type)) 2)
\space))]
(when who
(print " [")
(print who)
(print "]"))
(doseq [irritant stuff]
(print "\n")
(print spaces)
(pr irritant))
(print "\n")))))