Skip to content

Commit

Permalink
Forbid nilable primitive type hints
Browse files Browse the repository at this point in the history
  • Loading branch information
vemv committed May 21, 2019
1 parent f515ecf commit c3162b8
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 7 deletions.
22 changes: 15 additions & 7 deletions src/nedap/utils/spec/impl/parsing.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,12 @@
:type-annotation (cond
(primitive? inferred-class clj?) inferred-class
clj? (#?(:clj resolve :cljs fail) inferred-class)
true inferred-class)})))
true inferred-class)

:was-primitive? (primitive? s clj?)})))

(def forbidden-primitives-message
"Primitive type hints aren't nilable. That would emit code that would fail opaquely.")

(defn extract-specs-from-metadata [metadata-map clj?]
{:post [(check! #{0 1} (->> metadata-map
Expand Down Expand Up @@ -213,12 +218,15 @@
{:spec v
:type-annotation nil}))))
(filter some?)
(map (fn [{:keys [spec] :as result}]
(cond-> result
nilable? (assoc :spec (list (if clj?
'clojure.spec.alpha/nilable
'cljs.spec.alpha/nilable)
spec))))))))
(map (fn [{:keys [spec was-primitive?] :as result}]
(cond
nilable? (do
(assert (not was-primitive?) forbidden-primitives-message)
(assoc result :spec (list (if clj?
'clojure.spec.alpha/nilable
'cljs.spec.alpha/nilable)
spec)))
true result))))))

(defn ^{:author "Rich Hickey"
:license "Eclipse Public License 1.0"
Expand Down
13 changes: 13 additions & 0 deletions test/unit/nedap/utils/speced/defn.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
[clojure.string :as string]
#?(:clj [clojure.test :refer [deftest testing are is use-fixtures]] :cljs [cljs.test :refer-macros [deftest testing is are] :refer [use-fixtures]])
[nedap.utils.speced :as sut]
[nedap.utils.spec.impl.parsing :as impl.parsing]
[unit.nedap.test-helpers :refer [every-and-at-least-one?]])
#?(:cljs
(:require-macros [unit.nedap.utils.speced.defn :refer [the-defns]])))
Expand Down Expand Up @@ -752,3 +753,15 @@
(let [the-class (Class/forName "[B")]
(is (-> #'bytes-defn meta :tag #{the-class}))
(is (= the-class (-> #'bytes-defn meta :arglists first meta :tag #{the-class})))))))))

#?(:clj
(deftest nilable-primitive-specs
(testing "^:nedap.utils.speced/nilable <primitive hint> is forbidden"
(are [input] (try
(eval input)
false
(catch Exception e
(-> e .getCause .getMessage (string/includes? impl.parsing/forbidden-primitives-message))))
'(nedap.utils.speced/defn nilable-primitive-specs-1 ^:nedap.utils.speced/nilable ^double [])

'(nedap.utils.speced/defn nilable-primitive-specs-1 [^:nedap.utils.speced/nilable ^double x])))))

0 comments on commit c3162b8

Please sign in to comment.