Merge branch 'guarded-simplify'

This commit is contained in:
Paul deGrandis 2012-03-22 14:02:26 -04:00
commit 8cd50e5299
3 changed files with 29 additions and 9 deletions

View file

@ -48,13 +48,9 @@ Bugs can be reported using the github bug tracker.
* Rules for function definitions (make this more of a lint tool)
* Rules for collection lookup; "2 is a bad smell" [see this blog post](http://tech.puredanger.com/2011/10/12/2-is-a-smell/)
* Extract the "when to use" rules from [Joy of Clojure](http://joyofclojure.com/)
* gh-pages of the Marginalia docs as done [here](http://www.maybetechnology.com/2011/08/literate-programming-with-marginalia.html)
* Leiningen project.clj setting for rule exclusion
* Leiningen project.clj setting for a directory of rules to include
* More rules
* Remove reflection warnings (how?)
* Can core.logic be used to its full potential?
* Analyse ClojureScript files?
* Analyse ClojureScript files
## License

View file

@ -1,7 +1,6 @@
(ns jonase.kibit.core
"Kibit's core functionality uses core.logic to suggest idiomatic
replacements for patterns of code."
(:refer-clojure :exclude [==])
(:require [clojure.java.io :as io]
[clojure.walk :as walk]
[clojure.core.logic :as logic]
@ -50,21 +49,38 @@
:alt alt
:line (-> expr meta :line)}))))))
;; Guarding `simplify` allows for fine-grained control over what
;; gets passed to a reporter. This allows those using kibit
;; as a library or building out tool compatibility to shape
;; the results prior to reporting.
;;
;; Normally, you'll only want to report an alternative form if it differs
;; from the original expression form. You can use `identity` to short circuit
;; the guard.
;;
;; Simplify-guards take a map and return a map or nil
(defn unique-alt? [simplify-map]
(let [{:keys [expr alt line]} simplify-map]
(when-not (= alt expr)
simplify-map)))
;; This walks across all the forms within an expression,
;; checking each inner form. The outcome is a potential full alternative.
;; We check to see if there is indeed a difference in the alternative,
;; and if so, return a full simplify-map.
;; and if so, return a full simplify-map. See *Guarding simplify* above
;;
;; We build the simplify-map at the end because
;; Clojure 1.3 munges the metadata in transients (so also in clojure.walk).
(defn simplify
([expr]
(simplify expr all-rules))
(simplify expr all-rules unique-alt?))
([expr rules]
(simplify expr rules unique-alt?))
([expr rules simplify-guard]
(let [line-num (-> expr meta :line)
simp-partial #(simplify-one %1 rules)
alt (walk/postwalk #(or (-> % simp-partial :alt) %) expr)]
(when-not (= expr alt)
(simplify-guard
{:expr expr
:alt alt
:line line-num}))))

View file

@ -18,3 +18,11 @@
'(do [1 2 3]) '(do [1 2 3])
nil '(if (> 2 3) :one :two)))
(deftest simplify-deep
(is (= '(when (zero? 0) :one)
(:alt (kibit/simplify '(if (= 0 0) :one nil))))))
(deftest simplify-one
(is (= '(when (= 0 0) :one)
(:alt (kibit/simplify-one '(if (= 0 0) :one nil))))))