]> git.eshelyaron.com Git - emacs.git/commitdiff
* doc/lispref/functions.texi (Declare Form): Improve declare type.
authorAndrea Corallo <acorallo@gnu.org>
Wed, 1 May 2024 18:03:02 +0000 (20:03 +0200)
committerEshel Yaron <me@eshelyaron.com>
Mon, 6 May 2024 16:30:53 +0000 (18:30 +0200)
(cherry picked from commit fccd35f2c89a50675ed8c14d4814b603fd4fa166)

doc/lispref/functions.texi

index b5e234fa06817a7c1026e1ebab81c82f0b165e28..1816ea93e3d89cf869edbe4e4e055eb5f18fb05f 100644 (file)
@@ -2716,6 +2716,45 @@ native compiler (@pxref{Native-Compilation}) for improving code
 generation and for deriving more precisely the type of other functions
 without type declaration.
 
+@var{type} is a type specifier in the form @code{(function (ARG-1-TYPE
+... ARG-N-TYPE) RETURN-TYPE)}.  Argument types can be interleaved with
+symbols @code{&optional} and @code{&rest} to match the @pxref{Argument
+List} of the function.
+
+Here's an example of using @code{type} inside @code{declare} to declare
+a function @code{positive-p} that takes an argument of type @var{number}
+and return a @var{boolean}:
+
+@lisp
+(defun positive-p (x)
+  (declare (type (function (number) boolean)))
+  (when (> x 0)
+    t))
+@end lisp
+
+Similarly this declares a function @code{cons-or-number} that: expects a
+first argument being a @var{cons} or a @var{number}, a second optional
+argument of type @var{string} and return one of the symbols
+@code{is-cons} or @code{is-number}:
+
+@lisp
+(defun cons-or-number (x &optional err-msg)
+  (declare (type (function ((or cons number) &optional string)
+                          (member is-cons is-number))))
+  (if (consp x)
+      'is-cons
+    (if (numberp x)
+       'is-number
+      (error (or err-msg "Unexpected input")))))
+@end lisp
+
+More types are described in @pxref{Lisp Data Types}.
+
+Declaring a function with an incorrect type produces undefined behavior.
+Note also that when redefining (or advising) a type declared function
+the replacement should respect the original signature to avoid undefined
+behavior.
+
 @item no-font-lock-keyword
 This is valid for macros only.  Macros with this declaration are
 highlighted by font-lock (@pxref{Font Lock Mode}) as normal functions,