PageRenderTime 71ms CodeModel.GetById 28ms RepoModel.GetById 1ms app.codeStats 0ms

/clojure/untranslated.clj

https://github.com/egasimus/clojure-py
Clojure | 1655 lines | 1463 code | 175 blank | 17 comment | 153 complexity | c6bf193ba56f66b798d0320d85ed24a0 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. (defn load-reader
  2. "Sequentially read and evaluate the set of forms contained in the
  3. stream/file"
  4. {:added "1.0"
  5. :static true}
  6. [rdr] (. clojure.lang.Compiler (load rdr)))
  7. (defn load-string
  8. "Sequentially read and evaluate the set of forms contained in the
  9. string"
  10. {:added "1.0"
  11. :static true}
  12. [s]
  13. (let [rdr (-> (java.io.StringReader. s)
  14. (clojure.lang.LineNumberingPushbackReader.))]
  15. (load-reader rdr)))
  16. (defn var-get
  17. "Gets the value in the var object"
  18. {:added "1.0"
  19. :static true}
  20. [^clojure.lang.Var x] (. x (get)))
  21. (defn var-set
  22. "Sets the value in the var object to val. The var must be
  23. thread-locally bound."
  24. {:added "1.0"
  25. :static true}
  26. [^clojure.lang.Var x val] (. x (set val)))
  27. (defmacro with-local-vars
  28. "varbinding=> symbol init-expr
  29. Executes the exprs in a context in which the symbols are bound to
  30. vars with per-thread bindings to the init-exprs. The symbols refer
  31. to the var objects themselves, and must be accessed with var-get and
  32. var-set"
  33. {:added "1.0"}
  34. [name-vals-vec & body]
  35. (assert-args
  36. (vector? name-vals-vec) "a vector for its binding"
  37. (even? (count name-vals-vec)) "an even number of forms in binding vector")
  38. `(let [~@(interleave (take-nth 2 name-vals-vec)
  39. (repeat '(.. clojure.lang.Var create setDynamic)))]
  40. (. clojure.lang.Var (pushThreadBindings (hash-map ~@name-vals-vec)))
  41. (try
  42. ~@body
  43. (finally (. clojure.lang.Var (popThreadBindings))))))
  44. (defmacro lazy-cat
  45. "Expands to code which yields a lazy sequence of the concatenation
  46. of the supplied colls. Each coll expr is not evaluated until it is
  47. needed.
  48. (lazy-cat xs ys zs) === (concat (lazy-seq xs) (lazy-seq ys) (lazy-seq zs))"
  49. {:added "1.0"}
  50. [& colls]
  51. `(concat ~@(map #(list `lazy-seq %) colls)))
  52. (defmacro with-out-str
  53. "Evaluates exprs in a context in which *out* is bound to a fresh
  54. StringWriter. Returns the string created by any nested printing
  55. calls."
  56. {:added "1.0"}
  57. [& body]
  58. `(let [s# (new java.io.StringWriter)]
  59. (binding [*out* s#]
  60. ~@body
  61. (str s#))))
  62. (defmacro with-in-str
  63. "Evaluates body in a context in which *in* is bound to a fresh
  64. StringReader initialized with the string s."
  65. {:added "1.0"}
  66. [s & body]
  67. `(with-open [s# (-> (java.io.StringReader. ~s) clojure.lang.LineNumberingPushbackReader.)]
  68. (binding [*in* s#]
  69. ~@body)))
  70. (defn pr-str
  71. "pr to a string, returning it"
  72. {:tag String
  73. :added "1.0"
  74. :static true}
  75. [& xs]
  76. (with-out-str
  77. (apply pr xs)))
  78. (defn prn-str
  79. "prn to a string, returning it"
  80. {:tag String
  81. :added "1.0"
  82. :static true}
  83. [& xs]
  84. (with-out-str
  85. (apply prn xs)))
  86. (defn print-str
  87. "print to a string, returning it"
  88. {:tag String
  89. :added "1.0"
  90. :static true}
  91. [& xs]
  92. (with-out-str
  93. (apply print xs)))
  94. (defn println-str
  95. "println to a string, returning it"
  96. {:tag String
  97. :added "1.0"
  98. :static true}
  99. [& xs]
  100. (with-out-str
  101. (apply println xs)))
  102. (import clojure.lang.ExceptionInfo)
  103. (defn ex-info
  104. "Alpha - subject to change.
  105. Create an instance of ExceptionInfo, a RuntimeException subclass
  106. that carries a map of additional data."
  107. {:added "1.4"}
  108. ([msg map]
  109. (ExceptionInfo. msg map))
  110. ([msg map cause]
  111. (ExceptionInfo. msg map cause)))
  112. (defn ex-data
  113. "Alpha - subject to change.
  114. Returns exception data (a map) if ex is an ExceptionInfo.
  115. Otherwise returns nil."
  116. {:added "1.4"}
  117. [ex]
  118. (when (instance? ExceptionInfo ex)
  119. (.getData ^ExceptionInfo ex)))
  120. (defmacro assert
  121. "Evaluates expr and throws an exception if it does not evaluate to
  122. logical true."
  123. {:added "1.0"}
  124. ([x]
  125. (when *assert*
  126. `(when-not ~x
  127. (throw (new AssertionError (str "Assert failed: " (pr-str '~x)))))))
  128. ([x message]
  129. (when *assert*
  130. `(when-not ~x
  131. (throw (new AssertionError (str "Assert failed: " ~message "\n" (pr-str '~x))))))))
  132. (defn test
  133. "test [v] finds fn at key :test in var metadata and calls it,
  134. presuming failure will throw exception"
  135. {:added "1.0"}
  136. [v]
  137. (let [f (:test (meta v))]
  138. (if f
  139. (do (f) :ok)
  140. :no-test)))
  141. (defmacro defn-
  142. "same as defn, yielding non-public def"
  143. {:added "1.0"}
  144. [name & decls]
  145. (list* `defn (with-meta name (assoc (meta name) :private true)) decls))
  146. (defn xml-seq
  147. "A tree seq on the xml elements as per xml/parse"
  148. {:added "1.0"
  149. :static true}
  150. [root]
  151. (tree-seq
  152. (complement string?)
  153. (comp seq :content)
  154. root))
  155. (defn special-symbol?
  156. "Returns true if s names a special form"
  157. {:added "1.0"
  158. :static true}
  159. [s]
  160. (contains? (. clojure.lang.Compiler specials) s))
  161. (defn distinct
  162. "Returns a lazy sequence of the elements of coll with duplicates removed"
  163. {:added "1.0"
  164. :static true}
  165. [coll]
  166. (let [step (fn step [xs seen]
  167. (lazy-seq
  168. ((fn [[f :as xs] seen]
  169. (when-let [s (seq xs)]
  170. (if (contains? seen f)
  171. (recur (rest s) seen)
  172. (cons f (step (rest s) (conj seen f))))))
  173. xs seen)))]
  174. (step coll #{})))
  175. (defmacro with-precision
  176. "Sets the precision and rounding mode to be used for BigDecimal operations.
  177. Usage: (with-precision 10 (/ 1M 3))
  178. or: (with-precision 10 :rounding HALF_DOWN (/ 1M 3))
  179. The rounding mode is one of CEILING, FLOOR, HALF_UP, HALF_DOWN,
  180. HALF_EVEN, UP, DOWN and UNNECESSARY; it defaults to HALF_UP."
  181. {:added "1.0"}
  182. [precision & exprs]
  183. (let [[body rm] (if (= (first exprs) :rounding)
  184. [(next (next exprs))
  185. `((. java.math.RoundingMode ~(second exprs)))]
  186. [exprs nil])]
  187. `(binding [*math-context* (java.math.MathContext. ~precision ~@rm)]
  188. ~@body)))
  189. (defn mk-bound-fn
  190. {:private true}
  191. [^clojure.lang.Sorted sc test key]
  192. (fn [e]
  193. (test (.. sc comparator (compare (. sc entryKey e) key)) 0)))
  194. (defn subseq
  195. "sc must be a sorted collection, test(s) one of <, <=, > or
  196. >=. Returns a seq of those entries with keys ek for
  197. which (test (.. sc comparator (compare ek key)) 0) is true"
  198. {:added "1.0"
  199. :static true}
  200. ([^clojure.lang.Sorted sc test key]
  201. (let [include (mk-bound-fn sc test key)]
  202. (if (#{> >=} test)
  203. (when-let [[e :as s] (. sc seqFrom key true)]
  204. (if (include e) s (next s)))
  205. (take-while include (. sc seq true)))))
  206. ([^clojure.lang.Sorted sc start-test start-key end-test end-key]
  207. (when-let [[e :as s] (. sc seqFrom start-key true)]
  208. (take-while (mk-bound-fn sc end-test end-key)
  209. (if ((mk-bound-fn sc start-test start-key) e) s (next s))))))
  210. (defn rsubseq
  211. "sc must be a sorted collection, test(s) one of <, <=, > or
  212. >=. Returns a reverse seq of those entries with keys ek for
  213. which (test (.. sc comparator (compare ek key)) 0) is true"
  214. {:added "1.0"
  215. :static true}
  216. ([^clojure.lang.Sorted sc test key]
  217. (let [include (mk-bound-fn sc test key)]
  218. (if (#{< <=} test)
  219. (when-let [[e :as s] (. sc seqFrom key false)]
  220. (if (include e) s (next s)))
  221. (take-while include (. sc seq false)))))
  222. ([^clojure.lang.Sorted sc start-test start-key end-test end-key]
  223. (when-let [[e :as s] (. sc seqFrom end-key false)]
  224. (take-while (mk-bound-fn sc start-test start-key)
  225. (if ((mk-bound-fn sc end-test end-key) e) s (next s))))))
  226. (defn repeatedly
  227. "Takes a function of no args, presumably with side effects, and
  228. returns an infinite (or length n if supplied) lazy sequence of calls
  229. to it"
  230. {:added "1.0"
  231. :static true}
  232. ([f] (lazy-seq (cons (f) (repeatedly f))))
  233. ([n f] (take n (repeatedly f))))
  234. (defn add-classpath
  235. "DEPRECATED
  236. Adds the url (String or URL object) to the classpath per
  237. URLClassLoader.addURL"
  238. {:added "1.0"
  239. :deprecated "1.1"}
  240. [url]
  241. (println "WARNING: add-classpath is deprecated")
  242. (clojure.lang.rt/addURL url))
  243. (defn hash
  244. "Returns the hash code of its argument. Note this is the hash code
  245. consistent with =, and thus is different than .hashCode for Integer,
  246. Short, Byte and Clojure collections."
  247. {:added "1.0"
  248. :static true}
  249. [x] (. clojure.lang.Util (hasheq x)))
  250. (defmacro definline
  251. "Experimental - like defmacro, except defines a named function whose
  252. body is the expansion, calls to which may be expanded inline as if
  253. it were a macro. Cannot be used with variadic (&) args."
  254. {:added "1.0"}
  255. [name & decl]
  256. (let [[pre-args [args expr]] (split-with (comp not vector?) decl)]
  257. `(do
  258. (defn ~name ~@pre-args ~args ~(apply (eval (list `fn args expr)) args))
  259. (alter-meta! (var ~name) assoc :inline (fn ~name ~args ~expr))
  260. (var ~name))))
  261. (defn empty
  262. "Returns an empty collection of the same category as coll, or nil"
  263. {:added "1.0"
  264. :static true}
  265. [coll]
  266. (when (instance? clojure.lang.IPersistentCollection coll)
  267. (.empty ^clojure.lang.IPersistentCollection coll)))
  268. (defmacro amap
  269. "Maps an expression across an array a, using an index named idx, and
  270. return value named ret, initialized to a clone of a, then setting
  271. each element of ret to the evaluation of expr, returning the new
  272. array ret."
  273. {:added "1.0"}
  274. [a idx ret expr]
  275. `(let [a# ~a
  276. ~ret (aclone a#)]
  277. (loop [~idx 0]
  278. (if (< ~idx (alength a#))
  279. (do
  280. (aset ~ret ~idx ~expr)
  281. (recur (unchecked-inc ~idx)))
  282. ~ret))))
  283. (defmacro areduce
  284. "Reduces an expression across an array a, using an index named idx,
  285. and return value named ret, initialized to init, setting ret to the
  286. evaluation of expr at each step, returning ret."
  287. {:added "1.0"}
  288. [a idx ret init expr]
  289. `(let [a# ~a]
  290. (loop [~idx 0 ~ret ~init]
  291. (if (< ~idx (alength a#))
  292. (recur (unchecked-inc ~idx) ~expr)
  293. ~ret))))
  294. (defn boolean-array
  295. "Creates an array of booleans"
  296. {:inline (fn [& args] `(. clojure.lang.Numbers boolean_array ~@args))
  297. :inline-arities #{1 2}
  298. :added "1.1"}
  299. ([size-or-seq] (. clojure.lang.Numbers boolean_array size-or-seq))
  300. ([size init-val-or-seq] (. clojure.lang.Numbers boolean_array size init-val-or-seq)))
  301. (defn object-array
  302. "Creates an array of objects"
  303. {:inline (fn [arg] `(. clojure.lang.rt object_array ~arg))
  304. :inline-arities #{1}
  305. :added "1.2"}
  306. ([size-or-seq] (. clojure.lang.rt object_array size-or-seq)))
  307. (definline booleans
  308. "Casts to boolean[]"
  309. {:added "1.1"}
  310. [xs] `(. clojure.lang.Numbers booleans ~xs))
  311. (definline bytes
  312. "Casts to bytes[]"
  313. {:added "1.1"}
  314. [xs] `(. clojure.lang.Numbers bytes ~xs))
  315. (definline chars
  316. "Casts to chars[]"
  317. {:added "1.1"}
  318. [xs] `(. clojure.lang.Numbers chars ~xs))
  319. (definline shorts
  320. "Casts to shorts[]"
  321. {:added "1.1"}
  322. [xs] `(. clojure.lang.Numbers shorts ~xs))
  323. (definline floats
  324. "Casts to float[]"
  325. {:added "1.0"}
  326. [xs] `(. clojure.lang.Numbers floats ~xs))
  327. (definline ints
  328. "Casts to int[]"
  329. {:added "1.0"}
  330. [xs] `(. clojure.lang.Numbers ints ~xs))
  331. (definline doubles
  332. "Casts to double[]"
  333. {:added "1.0"}
  334. [xs] `(. clojure.lang.Numbers doubles ~xs))
  335. (definline longs
  336. "Casts to long[]"
  337. {:added "1.0"}
  338. [xs] `(. clojure.lang.Numbers longs ~xs))
  339. (import '(java.util.concurrent BlockingQueue LinkedBlockingQueue))
  340. (defn seque
  341. "Creates a queued seq on another (presumably lazy) seq s. The queued
  342. seq will produce a concrete seq in the background, and can get up to
  343. n items ahead of the consumer. n-or-q can be an integer n buffer
  344. size, or an instance of java.util.concurrent BlockingQueue. Note
  345. that reading from a seque can block if the reader gets ahead of the
  346. producer."
  347. {:added "1.0"
  348. :static true}
  349. ([s] (seque 100 s))
  350. ([n-or-q s]
  351. (let [^BlockingQueue q (if (instance? BlockingQueue n-or-q)
  352. n-or-q
  353. (LinkedBlockingQueue. (int n-or-q)))
  354. NIL (Object.) ;nil sentinel since LBQ doesn't support nils
  355. agt (agent (seq s))
  356. fill (fn [s]
  357. (try
  358. (loop [[x & xs :as s] s]
  359. (if s
  360. (if (.offer q (if (nil? x) NIL x))
  361. (recur xs)
  362. s)
  363. (.put q q))) ; q itself is eos sentinel
  364. (catch Exception e
  365. (.put q q)
  366. (throw e))))
  367. drain (fn drain []
  368. (lazy-seq
  369. (let [x (.take q)]
  370. (if (identical? x q) ;q itself is eos sentinel
  371. (do @agt nil) ;touch agent just to propagate errors
  372. (do
  373. (send-off agt fill)
  374. (cons (if (identical? x NIL) nil x) (drain)))))))]
  375. (send-off agt fill)
  376. (drain))))
  377. (defn- is-annotation? [c]
  378. (and (class? c)
  379. (.isAssignableFrom java.lang.annotation.Annotation c)))
  380. (defn- is-runtime-annotation? [^Class c]
  381. (boolean
  382. (and (is-annotation? c)
  383. (when-let [^java.lang.annotation.Retention r
  384. (.getAnnotation c java.lang.annotation.Retention)]
  385. (= (.value r) java.lang.annotation.RetentionPolicy/RUNTIME)))))
  386. (defn- descriptor [^Class c] (clojure.asm.Type/getDescriptor c))
  387. (declare process-annotation)
  388. (defn- add-annotation [^clojure.asm.AnnotationVisitor av name v]
  389. (cond
  390. (vector? v) (let [avec (.visitArray av name)]
  391. (doseq [vval v]
  392. (add-annotation avec "value" vval))
  393. (.visitEnd avec))
  394. (symbol? v) (let [ev (eval v)]
  395. (cond
  396. (instance? java.lang.Enum ev)
  397. (.visitEnum av name (descriptor (class ev)) (str ev))
  398. (class? ev) (.visit av name (clojure.asm.Type/getType ev))
  399. :else (throw (IllegalArgumentException.
  400. (str "Unsupported annotation value: " v " of class " (class ev))))))
  401. (seq? v) (let [[nested nv] v
  402. c (resolve nested)
  403. nav (.visitAnnotation av name (descriptor c))]
  404. (process-annotation nav nv)
  405. (.visitEnd nav))
  406. :else (.visit av name v)))
  407. (defn- process-annotation [av v]
  408. (if (map? v)
  409. (doseq [[k v] v]
  410. (add-annotation av (name k) v))
  411. (add-annotation av "value" v)))
  412. (defn- add-annotations
  413. ([visitor m] (add-annotations visitor m nil))
  414. ([visitor m i]
  415. (doseq [[k v] m]
  416. (when (symbol? k)
  417. (when-let [c (resolve k)]
  418. (when (is-annotation? c)
  419. ;this is known duck/reflective as no common base of ASM Visitors
  420. (let [av (if i
  421. (.visitParameterAnnotation visitor i (descriptor c)
  422. (is-runtime-annotation? c))
  423. (.visitAnnotation visitor (descriptor c)
  424. (is-runtime-annotation? c)))]
  425. (process-annotation av v)
  426. (.visitEnd av))))))))
  427. (defn underive
  428. "Removes a parent/child relationship between parent and
  429. tag. h must be a hierarchy obtained from make-hierarchy, if not
  430. supplied defaults to, and modifies, the global hierarchy."
  431. {:added "1.0"}
  432. ([tag parent] (alter-var-root #'global-hierarchy underive tag parent) nil)
  433. ([h tag parent]
  434. (let [parentMap (:parents h)
  435. childsParents (if (parentMap tag)
  436. (disj (parentMap tag) parent) #{})
  437. newParents (if (not-empty childsParents)
  438. (assoc parentMap tag childsParents)
  439. (dissoc parentMap tag))
  440. deriv-seq (flatten (map #(cons (key %) (interpose (key %) (val %)))
  441. (seq newParents)))]
  442. (if (contains? (parentMap tag) parent)
  443. (reduce1 #(apply derive %1 %2) (make-hierarchy)
  444. (partition 2 deriv-seq))
  445. h))))
  446. (defn distinct?
  447. "Returns true if no two of the arguments are ="
  448. {:tag Boolean
  449. :added "1.0"
  450. :static true}
  451. ([x] true)
  452. ([x y] (not (= x y)))
  453. ([x y & more]
  454. (if (not= x y)
  455. (loop [s #{x y} [x & etc :as xs] more]
  456. (if xs
  457. (if (contains? s x)
  458. false
  459. (recur (conj s x) etc))
  460. true))
  461. false)))
  462. (defn resultset-seq
  463. "Creates and returns a lazy sequence of structmaps corresponding to
  464. the rows in the java.sql.ResultSet rs"
  465. {:added "1.0"}
  466. [^java.sql.ResultSet rs]
  467. (let [rsmeta (. rs (getMetaData))
  468. idxs (range 1 (inc (. rsmeta (getColumnCount))))
  469. keys (map (comp keyword #(.toLowerCase ^String %))
  470. (map (fn [i] (. rsmeta (getColumnLabel i))) idxs))
  471. check-keys
  472. (or (apply distinct? keys)
  473. (throw (Exception. "ResultSet must have unique column labels")))
  474. row-struct (apply create-struct keys)
  475. row-values (fn [] (map (fn [^Integer i] (. rs (getObject i))) idxs))
  476. rows (fn thisfn []
  477. (when (. rs (next))
  478. (cons (apply struct row-struct (row-values)) (lazy-seq (thisfn)))))]
  479. (rows)))
  480. (defn iterator-seq
  481. "Returns a seq on a java.util.Iterator. Note that most collections
  482. providing iterators implement Iterable and thus support seq directly."
  483. {:added "1.0"
  484. :static true}
  485. [iter]
  486. (clojure.lang.IteratorSeq/create iter))
  487. (defn enumeration-seq
  488. "Returns a seq on a java.util.Enumeration"
  489. {:added "1.0"
  490. :static true}
  491. [e]
  492. (clojure.lang.EnumerationSeq/create e))
  493. (defn printf
  494. "Prints formatted output, as per format"
  495. {:added "1.0"
  496. :static true}
  497. [fmt & args]
  498. (print (apply format fmt args)))
  499. (defmacro with-loading-context [& body]
  500. `((fn loading# []
  501. (. clojure.lang.Var (pushThreadBindings {clojure.lang.Compiler/LOADER
  502. (.getClassLoader (.getClass ^Object loading#))}))
  503. (try
  504. ~@body
  505. (finally
  506. (. clojure.lang.Var (popThreadBindings)))))))
  507. (defmacro defonce
  508. "defs name to have the root value of the expr iff the named var has no root value,
  509. else expr is unevaluated"
  510. {:added "1.0"}
  511. [name expr]
  512. `(let [v# (def ~name)]
  513. (when-not (.hasRoot v#)
  514. (def ~name ~expr))))
  515. ;;;;;;;;;;; require/use/load, contributed by Stephen C. Gilardi ;;;;;;;;;;;;;;;;;;
  516. (defonce ^:dynamic
  517. ^{:private true
  518. :doc "A ref to a sorted set of symbols representing loaded libs"}
  519. *loaded-libs* (ref (sorted-set)))
  520. (defonce ^:dynamic
  521. ^{:private true
  522. :doc "A stack of paths currently being loaded by this thread"}
  523. *pending-paths* ())
  524. (defn- throw-if
  525. "Throws an exception with a message if pred is true"
  526. [pred fmt & args]
  527. (when pred
  528. (let [^String message (apply format fmt args)
  529. exception (Exception. message)
  530. raw-trace (.getStackTrace exception)
  531. boring? #(not= (.getMethodName ^StackTraceElement %) "doInvoke")
  532. trace (into-array (drop 2 (drop-while boring? raw-trace)))]
  533. (.setStackTrace exception trace)
  534. (throw exception))))
  535. (defn- root-resource
  536. "Returns the root directory path for a lib"
  537. {:tag String}
  538. [lib]
  539. (str \/
  540. (.. (name lib)
  541. (replace \- \_)
  542. (replace \. \/))))
  543. (defn- root-directory
  544. "Returns the root resource path for a lib"
  545. [lib]
  546. (let [d (root-resource lib)]
  547. (subs d 0 (.lastIndexOf d "/"))))
  548. (defn- check-cyclic-dependency
  549. "Detects and rejects non-trivial cyclic load dependencies. The
  550. exception message shows the dependency chain with the cycle
  551. highlighted. Ignores the trivial case of a file attempting to load
  552. itself because that can occur when a gen-class'd class loads its
  553. implementation."
  554. [path]
  555. (when (some #{path} (rest *pending-paths*))
  556. (let [pending (map #(if (= % path) (str "[ " % " ]") %)
  557. (cons path *pending-paths*))
  558. chain (apply str (interpose "->" pending))]
  559. (throw (Exception. (str "Cyclic load dependency: " chain))))))
  560. ;; Public
  561. (defn loaded-libs
  562. "Returns a sorted set of symbols naming the currently loaded libs"
  563. {:added "1.0"}
  564. [] @*loaded-libs*)
  565. (defn load
  566. "Loads Clojure code from resources in classpath. A path is interpreted as
  567. classpath-relative if it begins with a slash or relative to the root
  568. directory for the current namespace otherwise."
  569. {:added "1.0"}
  570. [& paths]
  571. (doseq [^String path paths]
  572. (let [^String path (if (.startsWith path "/")
  573. path
  574. (str (root-directory (ns-name *ns*)) \/ path))]
  575. (when *loading-verbosely*
  576. (printf "(clojure.core/load \"%s\")\n" path)
  577. (flush))
  578. (check-cyclic-dependency path)
  579. (when-not (= path (first *pending-paths*))
  580. (binding [*pending-paths* (conj *pending-paths* path)]
  581. (clojure.lang.rt/load (.substring path 1)))))))
  582. (defn compile
  583. "Compiles the namespace named by the symbol lib into a set of
  584. classfiles. The source for the lib must be in a proper
  585. classpath-relative directory. The output files will go into the
  586. directory specified by *compile-path*, and that directory too must
  587. be in the classpath."
  588. {:added "1.0"}
  589. [lib]
  590. (binding [*compile-files* true]
  591. (load-one lib true true))
  592. lib)
  593. ;;;;;;;;;;;;; nested associative ops ;;;;;;;;;;;
  594. (defn get-in
  595. "Returns the value in a nested associative structure,
  596. where ks is a sequence of keys. Returns nil if the key
  597. is not present, or the not-found value if supplied."
  598. {:added "1.2"
  599. :static true}
  600. ([m ks]
  601. (reduce1 get m ks))
  602. ([m ks not-found]
  603. (loop [sentinel (Object.)
  604. m m
  605. ks (seq ks)]
  606. (if ks
  607. (let [m (get m (first ks) sentinel)]
  608. (if (identical? sentinel m)
  609. not-found
  610. (recur sentinel m (next ks))))
  611. m))))
  612. (defn assoc-in
  613. "Associates a value in a nested associative structure, where ks is a
  614. sequence of keys and v is the new value and returns a new nested structure.
  615. If any levels do not exist, hash-maps will be created."
  616. {:added "1.0"
  617. :static true}
  618. [m [k & ks] v]
  619. (if ks
  620. (assoc m k (assoc-in (get m k) ks v))
  621. (assoc m k v)))
  622. (defn update-in
  623. "'Updates' a value in a nested associative structure, where ks is a
  624. sequence of keys and f is a function that will take the old value
  625. and any supplied args and return the new value, and returns a new
  626. nested structure. If any levels do not exist, hash-maps will be
  627. created."
  628. {:added "1.0"
  629. :static true}
  630. ([m [k & ks] f & args]
  631. (if ks
  632. (assoc m k (apply update-in (get m k) ks f args))
  633. (assoc m k (apply f (get m k) args)))))
  634. (defn ifn?
  635. "Returns true if x implements IFn. Note that many data structures
  636. (e.g. sets and maps) implement IFn"
  637. {:added "1.0"
  638. :static true}
  639. [x] (instance? clojure.lang.IFn x))
  640. (defn associative?
  641. "Returns true if coll implements Associative"
  642. {:added "1.0"
  643. :static true}
  644. [coll] (instance? clojure.lang.Associative coll))
  645. (defn sequential?
  646. "Returns true if coll implements Sequential"
  647. {:added "1.0"
  648. :static true}
  649. [coll] (instance? clojure.lang.Sequential coll))
  650. (defn sorted?
  651. "Returns true if coll implements Sorted"
  652. {:added "1.0"
  653. :static true}
  654. [coll] (instance? clojure.lang.Sorted coll))
  655. (defn counted?
  656. "Returns true if coll implements count in constant time"
  657. {:added "1.0"
  658. :static true}
  659. [coll] (instance? clojure.lang.Counted coll))
  660. (defn reversible?
  661. "Returns true if coll implements Reversible"
  662. {:added "1.0"
  663. :static true}
  664. [coll] (instance? clojure.lang.Reversible coll))
  665. (def ^:dynamic
  666. ^{:doc "bound in a repl thread to the most recent exception caught by the repl"
  667. :added "1.0"}
  668. *e)
  669. (defn trampoline
  670. "trampoline can be used to convert algorithms requiring mutual
  671. recursion without stack consumption. Calls f with supplied args, if
  672. any. If f returns a fn, calls that fn with no arguments, and
  673. continues to repeat, until the return value is not a fn, then
  674. returns that non-fn value. Note that if you want to return a fn as a
  675. final value, you must wrap it in some data structure and unpack it
  676. after trampoline returns."
  677. {:added "1.0"
  678. :static true}
  679. ([f]
  680. (let [ret (f)]
  681. (if (fn? ret)
  682. (recur ret)
  683. ret)))
  684. ([f & args]
  685. (trampoline #(apply f args))))
  686. (defn memoize
  687. "Returns a memoized version of a referentially transparent function. The
  688. memoized version of the function keeps a cache of the mapping from arguments
  689. to results and, when calls with the same arguments are repeated often, has
  690. higher performance at the expense of higher memory use."
  691. {:added "1.0"
  692. :static true}
  693. [f]
  694. (let [mem (atom {})]
  695. (fn [& args]
  696. (if-let [e (find @mem args)]
  697. (val e)
  698. (let [ret (apply f args)]
  699. (swap! mem assoc args ret)
  700. ret)))))
  701. (defmacro condp
  702. "Takes a binary predicate, an expression, and a set of clauses.
  703. Each clause can take the form of either:
  704. test-expr result-expr
  705. test-expr :>> result-fn
  706. Note :>> is an ordinary keyword.
  707. For each clause, (pred test-expr expr) is evaluated. If it returns
  708. logical true, the clause is a match. If a binary clause matches, the
  709. result-expr is returned, if a ternary clause matches, its result-fn,
  710. which must be a unary function, is called with the result of the
  711. predicate as its argument, the result of that call being the return
  712. value of condp. A single default expression can follow the clauses,
  713. and its value will be returned if no clause matches. If no default
  714. expression is provided and no clause matches, an
  715. IllegalArgumentException is thrown."
  716. {:added "1.0"}
  717. [pred expr & clauses]
  718. (let [gpred (gensym "pred__")
  719. gexpr (gensym "expr__")
  720. emit (fn emit [pred expr args]
  721. (let [[[a b c :as clause] more]
  722. (split-at (if (= :>> (second args)) 3 2) args)
  723. n (count clause)]
  724. (cond
  725. (= 0 n) `(throw (IllegalArgumentException. (str "No matching clause: " ~expr)))
  726. (= 1 n) a
  727. (= 2 n) `(if (~pred ~a ~expr)
  728. ~b
  729. ~(emit pred expr more))
  730. :else `(if-let [p# (~pred ~a ~expr)]
  731. (~c p#)
  732. ~(emit pred expr more)))))
  733. gres (gensym "res__")]
  734. `(let [~gpred ~pred
  735. ~gexpr ~expr]
  736. ~(emit gpred gexpr clauses))))
  737. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; var documentation ;;;;;;;;;;;;;;;;;;;;;;;;;;
  738. (alter-meta! #'*agent* assoc :added "1.0")
  739. (alter-meta! #'in-ns assoc :added "1.0")
  740. (alter-meta! #'load-file assoc :added "1.0")
  741. (defmacro add-doc-and-meta {:private true} [name docstring meta]
  742. `(alter-meta! (var ~name) merge (assoc ~meta :doc ~docstring)))
  743. (add-doc-and-meta *file*
  744. "The path of the file being evaluated, as a String.
  745. Evaluates to nil when there is no file, eg. in the REPL."
  746. {:added "1.0"})
  747. (add-doc-and-meta *command-line-args*
  748. "A sequence of the supplied command line arguments, or nil if
  749. none were supplied"
  750. {:added "1.0"})
  751. (add-doc-and-meta *warn-on-reflection*
  752. "When set to true, the compiler will emit warnings when reflection is
  753. needed to resolve Java method calls or field accesses.
  754. Defaults to false."
  755. {:added "1.0"})
  756. (add-doc-and-meta *compile-path*
  757. "Specifies the directory where 'compile' will write out .class
  758. files. This directory must be in the classpath for 'compile' to
  759. work.
  760. Defaults to \"classes\""
  761. {:added "1.0"})
  762. (add-doc-and-meta *compile-files*
  763. "Set to true when compiling files, false otherwise."
  764. {:added "1.0"})
  765. (add-doc-and-meta *unchecked-math*
  766. "While bound to true, compilations of +, -, *, inc, dec and the
  767. coercions will be done without overflow checks. Default: false."
  768. {:added "1.3"})
  769. (add-doc-and-meta *in*
  770. "A java.io.Reader object representing standard input for read operations.
  771. Defaults to System/in, wrapped in a LineNumberingPushbackReader"
  772. {:added "1.0"})
  773. (add-doc-and-meta *out*
  774. "A java.io.Writer object representing standard output for print operations.
  775. Defaults to System/out, wrapped in an OutputStreamWriter"
  776. {:added "1.0"})
  777. (add-doc-and-meta *err*
  778. "A java.io.Writer object representing standard error for print operations.
  779. Defaults to System/err, wrapped in a PrintWriter"
  780. {:added "1.0"})
  781. (add-doc-and-meta *flush-on-newline*
  782. "When set to true, output will be flushed whenever a newline is printed.
  783. Defaults to true."
  784. {:added "1.0"})
  785. (add-doc-and-meta *print-meta*
  786. "If set to logical true, when printing an object, its metadata will also
  787. be printed in a form that can be read back by the reader.
  788. Defaults to false."
  789. {:added "1.0"})
  790. (add-doc-and-meta *print-dup*
  791. "When set to logical true, objects will be printed in a way that preserves
  792. their type when read in later.
  793. Defaults to false."
  794. {:added "1.0"})
  795. (add-doc-and-meta *print-readably*
  796. "When set to logical false, strings and characters will be printed with
  797. non-alphanumeric characters converted to the appropriate escape sequences.
  798. Defaults to true"
  799. {:added "1.0"})
  800. (add-doc-and-meta *read-eval*
  801. "When set to logical false, the EvalReader (#=(...)) is disabled in the
  802. read/load in the thread-local binding.
  803. Example: (binding [*read-eval* false] (read-string \"#=(eval (def x 3))\"))
  804. Defaults to true"
  805. {:added "1.0"})
  806. (defn future?
  807. "Returns true if x is a future"
  808. {:added "1.1"
  809. :static true}
  810. [x] (instance? java.util.concurrent.Future x))
  811. (defn future-done?
  812. "Returns true if future f is done"
  813. {:added "1.1"
  814. :static true}
  815. [^java.util.concurrent.Future f] (.isDone f))
  816. (defmacro letfn
  817. "fnspec ==> (fname [params*] exprs) or (fname ([params*] exprs)+)
  818. Takes a vector of function specs and a body, and generates a set of
  819. bindings of functions to their names. All of the names are available
  820. in all of the definitions of the functions, as well as the body."
  821. {:added "1.0", :forms '[(letfn [fnspecs*] exprs*)],
  822. :special-form true, :url nil}
  823. [fnspecs & body]
  824. `(letfn* ~(vec (interleave (map first fnspecs)
  825. (map #(cons `fn %) fnspecs)))
  826. ~@body))
  827. (defn fnil
  828. "Takes a function f, and returns a function that calls f, replacing
  829. a nil first argument to f with the supplied value x. Higher arity
  830. versions can replace arguments in the second and third
  831. positions (y, z). Note that the function f can take any number of
  832. arguments, not just the one(s) being nil-patched."
  833. {:added "1.2"
  834. :static true}
  835. ([f x]
  836. (fn
  837. ([a] (f (if (nil? a) x a)))
  838. ([a b] (f (if (nil? a) x a) b))
  839. ([a b c] (f (if (nil? a) x a) b c))
  840. ([a b c & ds] (apply f (if (nil? a) x a) b c ds))))
  841. ([f x y]
  842. (fn
  843. ([a b] (f (if (nil? a) x a) (if (nil? b) y b)))
  844. ([a b c] (f (if (nil? a) x a) (if (nil? b) y b) c))
  845. ([a b c & ds] (apply f (if (nil? a) x a) (if (nil? b) y b) c ds))))
  846. ([f x y z]
  847. (fn
  848. ([a b] (f (if (nil? a) x a) (if (nil? b) y b)))
  849. ([a b c] (f (if (nil? a) x a) (if (nil? b) y b) (if (nil? c) z c)))
  850. ([a b c & ds] (apply f (if (nil? a) x a) (if (nil? b) y b) (if (nil? c) z c) ds)))))
  851. ;;;;;;; case ;;;;;;;;;;;;;
  852. (defn- shift-mask [shift mask x]
  853. (-> x (bit-shift-right shift) (bit-and mask)))
  854. (def ^:private max-mask-bits 13)
  855. (def ^:private max-switch-table-size (bit-shift-left 1 max-mask-bits))
  856. (defn- maybe-min-hash
  857. "takes a collection of hashes and returns [shift mask] or nil if none found"
  858. [hashes]
  859. (first
  860. (filter (fn [[s m]]
  861. (apply distinct? (map #(shift-mask s m %) hashes)))
  862. (for [mask (map #(dec (bit-shift-left 1 %)) (range 1 (inc max-mask-bits)))
  863. shift (range 0 31)]
  864. [shift mask]))))
  865. (defn- case-map
  866. "Transforms a sequence of test constants and a corresponding sequence of then
  867. expressions into a sorted map to be consumed by case*. The form of the map
  868. entries are {(case-f test) [(test-f test) then]}."
  869. [case-f test-f tests thens]
  870. (into1 (sorted-map)
  871. (zipmap (map case-f tests)
  872. (map vector
  873. (map test-f tests)
  874. thens))))
  875. (defn- fits-table?
  876. "Returns true if the collection of ints can fit within the
  877. max-table-switch-size, false otherwise."
  878. [ints]
  879. (< (- (apply max (seq ints)) (apply min (seq ints))) max-switch-table-size))
  880. (defn- prep-ints
  881. "Takes a sequence of int-sized test constants and a corresponding sequence of
  882. then expressions. Returns a tuple of [shift mask case-map switch-type] where
  883. case-map is a map of int case values to [test then] tuples, and switch-type
  884. is either :sparse or :compact."
  885. [tests thens]
  886. (if (fits-table? tests)
  887. ; compact case ints, no shift-mask
  888. [0 0 (case-map int int tests thens) :compact]
  889. (let [[shift mask] (or (maybe-min-hash (map int tests)) [0 0])]
  890. (if (zero? mask)
  891. ; sparse case ints, no shift-mask
  892. [0 0 (case-map int int tests thens) :sparse]
  893. ; compact case ints, with shift-mask
  894. [shift mask (case-map #(shift-mask shift mask (int %)) int tests thens) :compact]))))
  895. (defn- merge-hash-collisions
  896. "Takes a case expression, default expression, and a sequence of test constants
  897. and a corresponding sequence of then expressions. Returns a tuple of
  898. [tests thens skip-check-set] where no tests have the same hash. Each set of
  899. input test constants with the same hash is replaced with a single test
  900. constant (the case int), and their respective thens are combined into:
  901. (condp = expr
  902. test-1 then-1
  903. ...
  904. test-n then-n
  905. default).
  906. The skip-check is a set of case ints for which post-switch equivalence
  907. checking must not be done (the cases holding the above condp thens)."
  908. [expr-sym default tests thens]
  909. (let [buckets (loop [m {} ks tests vs thens]
  910. (if (and ks vs)
  911. (recur
  912. (update-in m [(hash (first ks))] (fnil conj []) [(first ks) (first vs)])
  913. (next ks) (next vs))
  914. m))
  915. assoc-multi (fn [m h bucket]
  916. (let [testexprs (apply concat bucket)
  917. expr `(condp = ~expr-sym ~@testexprs ~default)]
  918. (assoc m h expr)))
  919. hmap (reduce1
  920. (fn [m [h bucket]]
  921. (if (== 1 (count bucket))
  922. (assoc m (ffirst bucket) (second (first bucket)))
  923. (assoc-multi m h bucket)))
  924. {} buckets)
  925. skip-check (->> buckets
  926. (filter #(< 1 (count (second %))))
  927. (map first)
  928. (into1 #{}))]
  929. [(keys hmap) (vals hmap) skip-check]))
  930. (defn- prep-hashes
  931. "Takes a sequence of test constants and a corresponding sequence of then
  932. expressions. Returns a tuple of [shift mask case-map switch-type skip-check]
  933. where case-map is a map of int case values to [test then] tuples, switch-type
  934. is either :sparse or :compact, and skip-check is a set of case ints for which
  935. post-switch equivalence checking must not be done (occurs with hash
  936. collisions)."
  937. [expr-sym default tests thens]
  938. (let [hashes (into1 #{} (map hash tests))]
  939. (if (== (count tests) (count hashes))
  940. (if (fits-table? hashes)
  941. ; compact case ints, no shift-mask
  942. [0 0 (case-map hash identity tests thens) :compact]
  943. (let [[shift mask] (or (maybe-min-hash hashes) [0 0])]
  944. (if (zero? mask)
  945. ; sparse case ints, no shift-mask
  946. [0 0 (case-map hash identity tests thens) :sparse]
  947. ; compact case ints, with shift-mask
  948. [shift mask (case-map #(shift-mask shift mask (hash %)) identity tests thens) :compact])))
  949. ; resolve hash collisions and try again
  950. (let [[tests thens skip-check] (merge-hash-collisions expr-sym default tests thens)
  951. [shift mask case-map switch-type] (prep-hashes expr-sym default tests thens)
  952. skip-check (if (zero? mask)
  953. skip-check
  954. (into1 #{} (map #(shift-mask shift mask %) skip-check)))]
  955. [shift mask case-map switch-type skip-check]))))
  956. (defmacro case
  957. "Takes an expression, and a set of clauses.
  958. Each clause can take the form of either:
  959. test-constant result-expr
  960. (test-constant1 ... test-constantN) result-expr
  961. The test-constants are not evaluated. They must be compile-time
  962. literals, and need not be quoted. If the expression is equal to a
  963. test-constant, the corresponding result-expr is returned. A single
  964. default expression can follow the clauses, and its value will be
  965. returned if no clause matches. If no default expression is provided
  966. and no clause matches, an IllegalArgumentException is thrown.
  967. Unlike cond and condp, case does a constant-time dispatch, the
  968. clauses are not considered sequentially. All manner of constant
  969. expressions are acceptable in case, including numbers, strings,
  970. symbols, keywords, and (Clojure) composites thereof. Note that since
  971. lists are used to group multiple constants that map to the same
  972. expression, a vector can be used to match a list if needed. The
  973. test-constants need not be all of the same type."
  974. {:added "1.2"}
  975. [e & clauses]
  976. (let [ge (with-meta (gensym) {:tag Object})
  977. default (if (odd? (count clauses))
  978. (last clauses)
  979. `(throw (IllegalArgumentException. (str "No matching clause: " ~ge))))]
  980. (if (> 2 (count clauses))
  981. `(let [~ge ~e] ~default)
  982. (let [pairs (partition 2 clauses)
  983. assoc-test (fn assoc-test [m test expr]
  984. (if (contains? m test)
  985. (throw (IllegalArgumentException. (str "Duplicate case test constant: " test)))
  986. (assoc m test expr)))
  987. pairs (reduce1
  988. (fn [m [test expr]]
  989. (if (seq? test)
  990. (reduce1 #(assoc-test %1 %2 expr) m test)
  991. (assoc-test m test expr)))
  992. {} pairs)
  993. tests (keys pairs)
  994. thens (vals pairs)
  995. mode (cond
  996. (every? #(and (integer? %) (<= Integer/MIN_VALUE % Integer/MAX_VALUE)) tests)
  997. :ints
  998. (every? keyword? tests)
  999. :identity
  1000. :else :hashes)]
  1001. (condp = mode
  1002. :ints
  1003. (let [[shift mask imap switch-type] (prep-ints tests thens)]
  1004. `(let [~ge ~e] (case* ~ge ~shift ~mask ~default ~imap ~switch-type :int)))
  1005. :hashes
  1006. (let [[shift mask imap switch-type skip-check] (prep-hashes ge default tests thens)]
  1007. `(let [~ge ~e] (case* ~ge ~shift ~mask ~default ~imap ~switch-type :hash-equiv ~skip-check)))
  1008. :identity
  1009. (let [[shift mask imap switch-type skip-check] (prep-hashes ge default tests thens)]
  1010. `(let [~ge ~e] (case* ~ge ~shift ~mask ~default ~imap ~switch-type :hash-identity ~skip-check))))))))
  1011. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; helper files ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  1012. (alter-meta! (find-ns 'clojure.core) assoc :doc "Fundamental library of the Clojure language")
  1013. (load "core_proxy")
  1014. (load "core_print")
  1015. (load "genclass")
  1016. (load "core_deftype")
  1017. (load "core/protocols")
  1018. (load "gvec")
  1019. ;; redefine reduce with internal-reduce
  1020. (defn reduce
  1021. "f should be a function of 2 arguments. If val is not supplied,
  1022. returns the result of applying f to the first 2 items in coll, then
  1023. applying f to that result and the 3rd item, etc. If coll contains no
  1024. items, f must accept no arguments as well, and reduce returns the
  1025. result of calling f with no arguments. If coll has only 1 item, it
  1026. is returned and f is not called. If val is supplied, returns the
  1027. result of applying f to val and the first item in coll, then
  1028. applying f to that result and the 2nd item, etc. If coll contains no
  1029. items, returns val and f is not called."
  1030. {:added "1.0"}
  1031. ([f coll]
  1032. (if-let [s (seq coll)]
  1033. (reduce f (first s) (next s))
  1034. (f)))
  1035. ([f val coll]
  1036. (let [s (seq coll)]
  1037. (clojure.core.protocols/internal-reduce s f val))))
  1038. (defn into
  1039. "Returns a new coll consisting of to-coll with all of the items of
  1040. from-coll conjoined."
  1041. {:added "1.0"
  1042. :static true}
  1043. [to from]
  1044. (if (instance? clojure.lang.IEditableCollection to)
  1045. (persistent! (reduce conj! (transient to) from))
  1046. (reduce conj to from)))
  1047. (defn mapv
  1048. "Returns a vector consisting of the result of applying f to the
  1049. set of first items of each coll, followed by applying f to the set
  1050. of second items in each coll, until any one of the colls is
  1051. exhausted. Any remaining items in other colls are ignored. Function
  1052. f should accept number-of-colls arguments."
  1053. {:added "1.4"
  1054. :static true}
  1055. ([f coll]
  1056. (-> (reduce (fn [v o] (conj! v (f o))) (transient []) coll)
  1057. persistent!))
  1058. ([f c1 c2]
  1059. (into [] (map f c1 c2)))
  1060. ([f c1 c2 c3]
  1061. (into [] (map f c1 c2 c3)))
  1062. ([f c1 c2 c3 & colls]
  1063. (into [] (apply map f c1 c2 c3 colls))))
  1064. (defn filterv
  1065. "Returns a vector of the items in coll for which
  1066. (pred item) returns true. pred must be free of side-effects."
  1067. {:added "1.4"
  1068. :static true}
  1069. [pred coll]
  1070. (-> (reduce (fn [v o] (if (pred o) (conj! v o) v))
  1071. (transient [])
  1072. coll)
  1073. persistent!))
  1074. (require '[clojure.java.io :as jio])
  1075. (defn- normalize-slurp-opts
  1076. [opts]
  1077. (if (string? (first opts))
  1078. (do
  1079. (println "WARNING: (slurp f enc) is deprecated, use (slurp f :encoding enc).")
  1080. [:encoding (first opts)])
  1081. opts))
  1082. (defn slurp
  1083. "Opens a reader on f and reads all its contents, returning a string.
  1084. See clojure.java.io/reader for a complete list of supported arguments."
  1085. {:added "1.0"}
  1086. ([f & opts]
  1087. (let [opts (normalize-slurp-opts opts)
  1088. sb (StringBuilder.)]
  1089. (with-open [#^java.io.Reader r (apply jio/reader f opts)]
  1090. (loop [c (.read r)]
  1091. (if (neg? c)
  1092. (str sb)
  1093. (do
  1094. (.append sb (char c))
  1095. (recur (.read r)))))))))
  1096. (defn spit
  1097. "Opposite of slurp. Opens f with writer, writes content, then
  1098. closes f. Options passed to clojure.java.io/writer."
  1099. {:added "1.2"}
  1100. [f content & options]
  1101. (with-open [#^java.io.Writer w (apply jio/writer f options)]
  1102. (.write w (str content))))
  1103. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; futures (needs proxy);;;;;;;;;;;;;;;;;;
  1104. (defn future-call
  1105. "Takes a function of no args and yields a future object that will
  1106. invoke the function in another thread, and will cache the result and
  1107. return it on all subsequent calls to deref/@. If the computation has
  1108. not yet finished, calls to deref/@ will block, unless the variant
  1109. of deref with timeout is used. See also - realized?."
  1110. {:added "1.1"
  1111. :static true}
  1112. [f]
  1113. (let [f (binding-conveyor-fn f)
  1114. fut (.submit clojure.lang.Agent/soloExecutor ^Callable f)]
  1115. (reify
  1116. clojure.lang.IDeref
  1117. (deref [_] (.get fut))
  1118. clojure.lang.IBlockingDeref
  1119. (deref
  1120. [_ timeout-ms timeout-val]
  1121. (try (.get fut timeout-ms java.util.concurrent.TimeUnit/MILLISECONDS)
  1122. (catch java.util.concurrent.TimeoutException e
  1123. timeout-val)))
  1124. clojure.lang.IPending
  1125. (isRealized [_] (.isDone fut))
  1126. java.util.concurrent.Future
  1127. (get [_] (.get fut))
  1128. (get [_ timeout unit] (.get fut timeout unit))
  1129. (isCancelled [_] (.isCancelled fut))
  1130. (isDone [_] (.isDone fut))
  1131. (cancel [_ interrupt?] (.cancel fut interrupt?)))))
  1132. (defmacro future
  1133. "Takes a body of expressions and yields a future object that will
  1134. invoke the body in another thread, and will cache the result and
  1135. return it on all subsequent calls to deref/@. If the computation has
  1136. not yet finished, calls to deref/@ will block, unless the variant of
  1137. deref with timeout is used. See also - realized?."
  1138. {:added "1.1"}
  1139. [& body] `(future-call (^{:once true} fn* [] ~@body)))
  1140. (defn future-cancel
  1141. "Cancels the future, if possible."
  1142. {:added "1.1"
  1143. :static true}
  1144. [^java.util.concurrent.Future f] (.cancel f true))
  1145. (defn future-cancelled?
  1146. "Returns true if future f is cancelled"
  1147. {:added "1.1"
  1148. :static true}
  1149. [^java.util.concurrent.Future f] (.isCancelled f))
  1150. (defn pmap
  1151. "Like map, except f is applied in parallel. Semi-lazy in that the
  1152. parallel computation stays ahead of the consumption, but doesn't
  1153. realize the entire result unless required. Only useful for
  1154. computationally intensive functions where the time of f dominates
  1155. the coordination overhead."
  1156. {:added "1.0"
  1157. :static true}
  1158. ([f coll]
  1159. (let [n (+ 2 (.. Runtime getRuntime availableProcessors))
  1160. rets (map #(future (f %)) coll)
  1161. step (fn step [[x & xs :as vs] fs]
  1162. (lazy-seq
  1163. (if-let [s (seq fs)]
  1164. (cons (deref x) (step xs (rest s)))
  1165. (map deref vs))))]
  1166. (step rets (drop n rets))))
  1167. ([f coll & colls]
  1168. (let [step (fn step [cs]
  1169. (lazy-seq
  1170. (let [ss (map seq cs)]
  1171. (when (every? identity ss)
  1172. (cons (map first ss) (step (map rest ss)))))))]
  1173. (pmap #(apply f %) (step (cons coll colls))))))
  1174. (defn pcalls
  1175. "Executes the no-arg fns in parallel, returning a lazy sequence of
  1176. their values"
  1177. {:added "1.0"
  1178. :static true}
  1179. [& fns] (pmap #(%) fns))
  1180. (defmacro pvalues
  1181. "Returns a lazy sequence of the values of the exprs, which are
  1182. evaluated in parallel"
  1183. {:added "1.0"
  1184. :static true}
  1185. [& exprs]
  1186. `(pcalls ~@(map #(list `fn [] %) exprs)))
  1187. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; clojure version number ;;;;;;;;;;;;;;;;;;;;;;
  1188. (let [properties (with-open [version-stream (.getResourceAsStream
  1189. (clojure.lang.rt/baseLoader)
  1190. "clojure/version.properties")]
  1191. (doto (new java.util.Properties)
  1192. (.load version-stream)))
  1193. version-string (.getProperty properties "version")
  1194. [_ major minor incremental qualifier snapshot]
  1195. (re-matches
  1196. #"(\d+)\.(\d+)\.(\d+)(?:-([a-zA-Z0-9_]+))?(?:-(SNAPSHOT))?"
  1197. version-string)
  1198. clojure-version {:major (Integer/valueOf ^String major)
  1199. :minor (Integer/valueOf ^String minor)
  1200. :incremental (Integer/valueOf ^String incremental)
  1201. :qualifier (if (= qualifier "SNAPSHOT") nil qualifier)}]
  1202. (def ^:dynamic *clojure-version*
  1203. (if (.contains version-string "SNAPSHOT")
  1204. (clojure.lang.rt/assoc clojure-version :interim true)
  1205. clojure-version)))
  1206. (add-doc-and-meta *clojure-version*
  1207. "The version info for Clojure core, as a map containing :major :minor
  1208. :incremental and :qualifier keys. Feature releases may increment
  1209. :minor and/or :major, bugfix releases will increment :incremental.
  1210. Possible values of :qualifier include \"GA\", \"SNAPSHOT\", \"RC-x\" \"BETA-x\""
  1211. {:added "1.0"})
  1212. (defn
  1213. clojure-version
  1214. "Returns clojure version as a printable string."
  1215. {:added "1.0"}
  1216. []
  1217. (str (:major *clojure-version*)
  1218. "."
  1219. (:minor *clojure-version*)
  1220. (when-let [i (:incremental *clojure-version*)]
  1221. (str "." i))
  1222. (when-let [q (:qualifier *clojure-version*)]
  1223. (when (pos? (count q)) (str "-" q)))
  1224. (when (:interim *clojure-version*)
  1225. "-SNAPSHOT")))
  1226. (defn promise
  1227. "Alpha - subject to change.
  1228. Returns a promise object that can be read with deref/@, and set,
  1229. once only, with deliver. Calls to deref/@ prior to delivery will
  1230. block, unless the variant of deref with timeout is used. All
  1231. subsequent derefs will return the same delivered value without
  1232. blocking. See also - realized?."
  1233. {:added "1.1"
  1234. :static true}
  1235. []
  1236. (let [d (java.util.concurrent.CountDownLatch. 1)
  1237. v (atom d)]
  1238. (reify
  1239. clojure.lang.IDeref
  1240. (deref [_] (.await d) @v)
  1241. clojure.lang.IBlockingDeref
  1242. (deref
  1243. [_ timeout-ms timeout-val]
  1244. (if (.await d timeout-ms java.util.concurrent.TimeUnit/MILLISECONDS)
  1245. @v
  1246. timeout-val))
  1247. clojure.lang.IPending
  1248. (isRealized [this]
  1249. (zero? (.getCount d)))
  1250. clojure.lang.IFn
  1251. (invoke
  1252. [this x]
  1253. (when (and (pos? (.getCount d))
  1254. (compare-and-set! v d x))
  1255. (.countDown d)
  1256. this)))))
  1257. (defn deliver
  1258. "Alpha - subject to change.
  1259. Delivers the supplied value to the promise, releasing any pending
  1260. derefs. A subsequent call to deliver on a promise will throw an exception."
  1261. {:added "1.1"
  1262. :static true}
  1263. [promise val] (promise val))
  1264. (defn flatten
  1265. "Takes any nested combination of sequential things (lists, vectors,
  1266. etc.) and returns their contents as a single, flat sequence.
  1267. (flatten nil) returns an empty sequence."
  1268. {:added "1.2"
  1269. :static true}
  1270. [x]
  1271. (filter (complement sequential?)
  1272. (rest (tree-seq sequential? seq x))))
  1273. (defn group-by
  1274. "Returns a map of the elements of coll keyed by the result of
  1275. f on each element. The value at each key will be a vector of the
  1276. corresponding elements, in the order they appeared in coll."
  1277. {:added "1.2"
  1278. :static true}
  1279. [f coll]
  1280. (persistent!
  1281. (reduce
  1282. (fn [ret x]
  1283. (let [k (f x)]
  1284. (assoc! ret k (conj (get ret k []) x))))
  1285. (transient {}) coll)))
  1286. (defn partition-by
  1287. "Applies f to each value in coll, splitting it each time f returns
  1288. a new value. Returns a lazy seq of partitions."
  1289. {:added "1.2"
  1290. :static true}
  1291. [f coll]
  1292. (lazy-seq
  1293. (when-let [s (seq coll)]
  1294. (let [fst (first s)
  1295. fv (f fst)
  1296. run (cons fst (take-while #(= fv (f %)) (next s)))]
  1297. (cons run (partition-by f (seq (drop (count run) s))))))))
  1298. (defn frequencies
  1299. "Returns a map from distinct items in coll to the number of times
  1300. they appear."
  1301. {:added "1.2"
  1302. :static true}
  1303. [coll]
  1304. (persistent!
  1305. (reduce (fn [counts x]
  1306. (assoc! counts x (inc (get counts x 0))))
  1307. (transient {}) coll)))
  1308. (defn partiti

Large files files are truncated, but you can click here to view the full file