Skip to content

Commit f0b8531

Browse files
mfikesdnolen
authored andcommitted
CLJS-1556: Invalid code emit for obj literal
Certain legal ClojureScript expresssions involving #js object literals end up causing invalid JavaScript to be emitted. In particular, this can occur if such an object literal is in statement context. It can also occur if simply evaluating an object literal in expression context by itself in a REPL. At the root of the problem is that the opening brace associated with an object literal should not be at the beginning of a JavaScript statement. Otherwise, the brace may be interpreted as the start of a JavaScript block. This patch fixes the issue by simply wrapping all emitted object literals in parens.
1 parent 273bcd3 commit f0b8531

File tree

2 files changed

+10
-2
lines changed

2 files changed

+10
-2
lines changed

src/main/clojure/cljs/compiler.cljc

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -406,13 +406,13 @@
406406
(emit-wrap env
407407
(if (= js-type :object)
408408
(do
409-
(emits "{")
409+
(emits "({")
410410
(when-let [items (seq items)]
411411
(let [[[k v] & r] items]
412412
(emits "\"" (name k) "\": " v)
413413
(doseq [[k v] r]
414414
(emits ", \"" (name k) "\": " v))))
415-
(emits "}"))
415+
(emits "})"))
416416
(emits "[" (comma-sep items) "]"))))
417417

418418
(defmethod emit* :constant

src/test/cljs/cljs/core_test.cljs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2417,6 +2417,14 @@
24172417
(is (array? (aget #js {"foo" #js [1 2 3]} "foo")))
24182418
(is (= (seq (aget #js {"foo" #js [1 2 3]} "foo")) '(1 2 3)))))
24192419

2420+
(deftest test-1556
2421+
(testing "Testing CLJS-1556, JS object literal code emission, beginning of statement"
2422+
;; Really testing that this evaluates properly
2423+
(is (= 1 (do #js {:a 1}
2424+
1)))
2425+
(is (= 1 (aget #js {:a 1} "a")))
2426+
(is (= 1 (.-a #js {:a 1})))))
2427+
24202428
(deftest test-725
24212429
(testing "Testing CLJS-725, drop"
24222430
(is (= (apply vector (drop-while (partial = 1) [1 2 3])) [2 3]))

0 commit comments

Comments
 (0)