Hacker News new | ask | show | jobs
by lispm 3089 days ago
> CL type declarations tell the compiler it can remove runtime checks.

That's not true. To tell the compiler that it can remove runtime checks you declare the optimization quality SAFETY to 0.

The Common Lisp standard does not specify what type declarations do and what the interpreter or compiler does with it.

Some compilers will never check types. Some will use them when SAFETY is low as assertions and remove runtime checks. Some will use them as assertions both at compile and runtime.

> They are performance optimizations. If anything they decrease type safety.

That depends on the implementation and the compiler switches.

In SBCL by default it INCREASES type safety:

  * (defun foo (a) (declare (type (integer 0 100) a)) (+ a 10))
  WARNING: redefining COMMON-LISP-USER::FOO in DEFUN

  FOO
  * (foo -1)

  debugger invoked on a TYPE-ERROR in thread
  #<THREAD "main thread" RUNNING {1001950083}>:
    The value
      -1
    is not of type
      (MOD 101)
    when binding A

  Type HELP for debugger help, or (SB-EXT:EXIT) to exit from SBCL.

  restarts (invokable by number or by possibly-abbreviated name):
    0: [ABORT] Exit debugger, returning to top level.

  (FOO -1) [external]
     source: (SB-INT:NAMED-LAMBDA FOO
                 (A)
               (DECLARE (TYPE (INTEGER 0 100) A))
               (BLOCK FOO (+ A 10)))
  0]
1 comments

You're right. The standard leaves the interpretation of type declarations in CL up to the implementation. I was coming from a CCL perspective, and I should have checked the others.

In CCL:

  ? (defun foo (a) (declare (type (integer 0 100) a)) (+ a 10))
  FOO
  ? (foo -1)
  9
It's dangerous to assume the effect type declarations will have in CL. You have to test it.
Even in CCL it depends on the compiler settings:

  ? (declaim (optimize (safety 3)))
  NIL
  ? (defun foo (a) (declare (type (integer 0 100) a)) (+ a 10))
  FOO
  ? (foo "bar")
  > Error: The value "bar" is not of the expected type (MOD 101).
  > While executing: FOO, in process listener(1).
  > Type :POP to abort, :R for a list of available restarts.
  > Type :? for other options.
  1 > 
Type declaration added -> runtime safety increased...

Best read the implementation manual to see how it deals with optimization values and type declarations.