/
trace.clj
330 lines (290 loc) · 11.1 KB
/
trace.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
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
;;;
;; trace.clj -- simple call-tracing macros for Clojure
;; by Stuart Sierra, http://stuartsierra.com/
;; December 3, 2008
;; Copyright (c) Stuart Sierra, 2008. All rights reserved. The use
;; and distribution terms for this software are covered by the Eclipse
;; Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
;; which can be found in the file epl-v10.html at the root of this
;; distribution. By using this software in any fashion, you are
;; agreeing to be bound by the terms of this license. You must not
;; remove this notice, or any other, from this software.
;;
;; This file defines simple "tracing" macros to help you see what your
;; code is doing.
;;
;; CHANGE LOG
;;
;; March 4, 2012: Luc Préfontaine
;;
;; * added macro wrappers around fns allowing dynamic tracing.
;;
;; Feb. 20, 2012: Luc Préfontaine
;;
;; * added contribution from Michał Marczyk and Don jackson to allow dynamic tracing of fns in a namespace.
;;
;; Sept 18, 2011: Luc Préfontaine
;;
;; * moved it to new contrib modular struct
;;
;; * made it 1.2/1.3 compliant
;;
;; * supported doc strings
;;
;; * added a trace-form macro, from Jonathan Fischer
;;
;; December 3, 2008:
;;
;; * replaced *trace-out* with tracer
;;
;; * made trace a function instead of a macro
;; (suggestion from Stuart Halloway)
;;
;; * added trace-fn-call
;;
;; June 9, 2008: first version
;;;
(ns ^{:author "Stuart Sierra, Michel Salim, Luc Préfontaine, Jonathan Fischer Friberg, Michał Marczyk, Don Jackson"
:doc "This file defines simple tracing macros to help you see what your code is doing."}
clojure.tools.trace
(:use [clojure.pprint]))
(def ^{:doc "Current stack depth of traced function calls." :private true :dynamic true}
*trace-depth* 0)
(def ^{:doc "Forms to ignore when tracing forms." :private true}
ignored-form? '#{def quote var try monitor-enter monitor-exit})
(defn ^{:private true} tracer
"This function is called by trace. Prints to standard output, but
may be rebound to do anything you like. 'name' is optional."
[name value]
(println (str "TRACE" (when name (str " " name)) ": " value)))
(defn trace
"Sends name (optional) and value to the tracer function, then
returns value. May be wrapped around any expression without
affecting the result."
([value] (trace nil value))
([name value]
(tracer name (pr-str value))
value))
(defn ^{:private true} trace-indent
"Returns an indentation string based on *trace-depth*"
[]
(apply str (take *trace-depth* (repeat "| "))))
(defn ^{:skip-wiki true} trace-fn-call
"Traces a single call to a function f with args. 'name' is the
symbol name of the function."
[name f args]
(let [id (gensym "t")]
(tracer id (str (trace-indent) (pr-str (cons name args))))
(let [value (binding [*trace-depth* (inc *trace-depth*)]
(apply f args))]
(tracer id (str (trace-indent) "=> " (pr-str value)))
value)))
(defmacro deftrace
"Use in place of defn; traces each call/return of this fn, including
arguments. Nested calls to deftrace'd functions will print a
tree-like structure.
The first argument of the form definition can be a doc string"
[name & definition]
(let [doc-string (if (string? (first definition)) (first definition) "")
fn-form (if (string? (first definition)) (rest definition) definition)]
`(do
(def ~name)
(let [f# (fn ~@fn-form)]
(defn ~name ~doc-string [& args#]
(trace-fn-call '~name f# args#))))))
(defmacro dotrace
"Given a sequence of function identifiers, evaluate the body
expressions in an environment in which the identifiers are bound to
the traced functions. Does not work on inlined functions,
such as clojure.core/+"
[fnames & exprs]
`(binding [~@(interleave fnames
(for [fname fnames]
`(let [f# @(var ~fname)]
(fn [& args#]
(trace-fn-call '~fname f# args#)))))]
~@exprs))
(declare trace-form)
(defmulti trace-special-form (fn [form] (first form)))
(defn ^{:private true} trace-bindings
"Trace the forms in the given binding list."
[bindings]
(vec (apply concat
(map (fn [[sym value]]
`[~sym (trace-forms ~value)]) (partition 2 bindings)))))
;; Trace the let form, its bindings then the forms in its body.
(defmethod trace-special-form
'let* [[_ bindings & body]]
`(let* ~(trace-bindings bindings)
(trace-forms ~@body)))
;; Trace the loop form, its bindings then the forms in its body.
(defmethod trace-special-form
'loop* [[_ bindings & body]]
`(loop* ~(trace-bindings bindings)
(trace-forms ~@body)))
;; Trace the new form, mainly its arguments.
(defmethod trace-special-form
'new [[_ name & args]]
`(new ~name ~@(map trace-form args)))
(defn ^{:private true} trace-fn-body
"Trace the forms in a function body."
[body]
`(~(first body) ~@(map trace-form (rest body))))
;; Trace the fn form.
(defmethod trace-special-form 'fn* [[_ & args]]
(if (symbol? (first args))
(if (vector? (second args))
`(fn* ~(first args) ~@(trace-fn-body (rest args)))
`(fn* ~(first args) ~@(map trace-fn-body (rest args))))
(if (vector? (first args))
`(fn* ~@(trace-fn-body args))
`(fn* ~@(map trace-fn-body args)))))
(defmethod trace-special-form :default [form] :default)
(defn ^{:private true} trace-value
"Trace the given data structure by tracing individual values."
[v]
(cond
(vector? v) `(vector ~@(map trace-form v))
(map? v) `(into {} ~(vec (map trace-value v)))
(set? v) `(into #{} ~(vec (map trace-form v)))
:else v))
(defn ^{:private true} recurs?
"Test if the given form contains a recur call."
[form]
(if (and (or (list? form)
(seq? form))
(> (count form) 0))
(condp = (first form)
'recur true
'quote false
(some identity (map recurs? (rest form))))
false))
(defn ^{:private true} trace-form*
"Trace the given form body except if it is to be ignored."
[form]
(if (and (or (list? form)
(seq? form))
(> (count form) 0))
(if (ignored-form? (first form))
form
(let [sform (trace-special-form form)]
(if (= sform :default)
(let [mform (macroexpand-1 form)]
(if (= form mform)
(cons (first mform) (map trace-form (rest mform)))
(trace-form mform)))
sform)))
(trace-value form)))
(defn ^{:skip-wiki true} trace-compose-exception
"Re-create a new exception with a composed message from the given exception
and the message to be added. The exception stack trace is kept at a minimum."
[^Exception exception ^String message]
(let [klass (class exception)
previous-msg (.getMessage exception)
composed-msg(str previous-msg (if-not (.endsWith previous-msg "\n") "\n") message (if-not (.endsWith message "\n") "\n"))
ctor (.getConstructor klass (into-array [java.lang.String]))
new-exception ^Exception (cast klass (.newInstance ctor (into-array String [composed-msg])))
new-stack-trace (into-array java.lang.StackTraceElement [(aget (.getStackTrace exception) 0)])
_ (.setStackTrace new-exception new-stack-trace)]
new-exception))
(defn ^{:skip-wiki true} trace-form
"Trace the given form avoiding try catch when recur is present in the form."
[form]
(if (recurs? form)
(trace-form* form)
`(try
~(trace-form* form)
(catch Exception e#
(throw (trace-compose-exception e# (format " Form failed: %s" (with-out-str (pprint '~form)))))))))
(defmacro trace-forms
"Trace all the forms in the given body. Returns any underlying uncaught exceptions that may make the forms fail."
[& body]
`(do
~@(map trace-form body)))
(defn ^{:skip-wiki true} trace-var*
"If the specified Var holds an IFn and is not marked as a macro, its
contents is replaced with a version wrapped in a tracing call;
otherwise nothing happens. Can be undone with untrace-var.
In the unary case, v should be a Var object or a symbol to be
resolved in the current namespace.
In the binary case, ns should be a namespace object or a symbol
naming a namespace and s a symbol to be resolved in that namespace."
([ns s]
(trace-var* (ns-resolve ns s)))
([v]
(let [^clojure.lang.Var v (if (var? v) v (resolve v))
ns (.ns v)
s (.sym v)]
(if (and (ifn? @v) (-> v meta :macro not))
(let [f @v
vname (symbol (str ns "/" s))]
(doto v
(alter-var-root #(fn tracing-wrapper [& args]
(trace-fn-call vname % args)))
(alter-meta! assoc ::traced f)))))))
(defn ^{:skip-wiki true} untrace-var*
"Reverses the effect of trace-var / trace-vars / trace-ns for the
given Var, replacing the traced function with the original, untraced
version. No-op for non-traced Vars.
Argument types are the same as those for trace-var."
([ns s]
(untrace-var* (ns-resolve ns s)))
([v]
(let [^clojure.lang.Var v (if (var? v) v (resolve v))
ns (.ns v)
s (.sym v)
f ((meta v) ::traced)]
(when f
(doto v
(alter-var-root (constantly ((meta v) ::traced)))
(alter-meta! dissoc ::traced))))))
(defmacro trace-vars
"Trace each of the specified Vars.
The arguments may be Var objects or symbols to be resolved in the current
namespace."
[& vs]
`(do ~@(for [x vs] `(trace-var* (quote ~x)))))
(defmacro untrace-vars
"Untrace each of the specified Vars.
Reverses the effect of trace-var / trace-vars / trace-ns for each
of the arguments, replacing the traced functions with the original,
untraced versions."
[& vs]
`(do ~@(for [x vs] `(untrace-var* (quote ~x)))))
(defn ^{:skip-wiki true} trace-ns*
"Replaces each function from the given namespace with a version wrapped
in a tracing call. Can be undone with untrace-ns. ns should be a namespace
object or a symbol.
No-op for clojure.core and clojure.tools.trace."
[ns]
(let [ns (the-ns ns)]
(when-not ('#{clojure.core clojure.tools.trace} (.name ns))
(let [ns-fns (->> ns ns-interns vals)]
(doseq [f ns-fns]
(trace-var* f))))))
(defmacro trace-ns
"Trace all fns in the given name space."
[ns]
`(trace-ns* ~ns))
(defn ^{:skip-wiki true} untrace-ns*
"Reverses the effect of trace-var / trace-vars / trace-ns for the
Vars in the given namespace, replacing each traced function from the
given namespace with the original, untraced version."
[ns]
(let [ns-fns (->> ns the-ns ns-interns vals)]
(doseq [f ns-fns]
(untrace-var* f))))
(defmacro untrace-ns
"Untrace all fns in the given name space."
[ns]
`(untrace-ns* ~ns))
(defn traced?
"Returns true if the given var is currently traced, false otherwise"
[v]
(let [^clojure.lang.Var v (if (var? v) v (resolve v))]
(-> v meta ::traced nil? not)))
(defn traceable?
"Returns true if the given var can be traced, false otherwise"
[v]
(let [^clojure.lang.Var v (if (var? v) v (resolve v))]
(and (ifn? @v) (-> v meta :macro not))))