Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this code work eventhough it has no open brace

Tags:

clojure

Why does this code work?

(defn g []
     do (println 10) (println 20))

Note: There is no ( before the do.

like image 653
Tim Avatar asked Jul 01 '14 16:07

Tim


1 Answers

In theory this shouldn't even compile. The compiler ought to complain that do cannot be resolved since it is a special symbol not in the first position of a form.

This is a (likely unintended) consequence of using the same BodyExpr parsing code for both the do special form and the body of the fn* special form. When compiling a do special form, the leading do is dropped and the remaining forms compiled. Using this same parser for a function body means a single naked do can also appear first.

public static class BodyExpr implements Expr, MaybePrimitiveExpr{

    ...

    public Expr parse(C context, Object frms) {
        ISeq forms = (ISeq) frms;
        if(Util.equals(RT.first(forms), DO))
            forms = RT.next(forms);

    ....

You'll notice that if the do is repeated, this

(defn g [] do do (println 10) (println 20))
;=> CompilerException java.lang.RuntimeException: 
      Unable to resolve symbol: do in this context ...

does not compile, as expected.

like image 161
A. Webb Avatar answered Nov 15 '22 07:11

A. Webb