Search code examples
common-lispconstant-expression

Common Lisp: Is the interpreter or compiler allowed to coalesce identical constant expressions?


I'm reading the description of DEFVAR in the CLHS (http://clhs.lisp.se/Body/m_defpar.htm). I am trying to determine what is conforming behavior for something like

(defvar x '(1 2 3))
(defvar y '(1 2 3))
(nreverse x)

Can that reverse Y as well? That would be expected if the interpreter or compiler identifies the values of X and Y as being identical and just makes one instance, to which they both refer. What I'm wondering if such constant-folding is allowed by CLHS.

I read the CLHS for DEFVAR but I wasn't able to puzzle it out; I didn't see that the topic is addressed there. Is it addressed somewhere else in CLHS?

If coalescence of identical constant values is allowed, are the interpreter and compiler allowed to differ? (I.e. one coalesces and the other doesn't.)


Solution

  • These topics are addressed in the chapter on compilation: CLHS 3.2 Compilation

    Two things:

    a) the file compiler is allowed to coalesce similar literal data

    see: CLHS 3.2.4.4 Additional Constraints on Externalizable Objects

    In code compiled by the file compiler both variables could point to the same list.

    Note also that this is even possible with sublists.

    b) the effects of modifying literal data are undefined

    Means: it could work, it could not work, it could have other visible effects. For example a compiler could place literal data / compiled code in protected memory, where an error would be raised when tying to modify it. Another possible effect could be that shared literal data gets modified (see above).

    Literal data should be treated as immutable, but a compiler is not required to detect it and warn.

    This means that calling NREVERSE on literal data is not a standards conforming operation, according to the ANSI Common Lisp standard. NREVERSE is allowed to destructively modify its passed list, but literal data should be treated as immutable.

    See: CLHS 3.7.1 Modification of Literal Objects

    Note: when not using the file compiler

    CLHS 3.2.4 Literal Objects in Compiled Files says: The constraints on literal objects described in this section apply only to compile-file; eval and compile do not copy or coalesce constants..