1.0.29.52: small UCD optimizations and related cleanups
[sbcl.git] / src / code / target-char.lisp
1 ;;;; character functions
2
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
5 ;;;;
6 ;;;; This software is derived from the CMU CL system, which was
7 ;;;; written at Carnegie Mellon University and released into the
8 ;;;; public domain. The software is in the public domain and is
9 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
10 ;;;; files for more information.
11
12 (in-package "SB!IMPL")
13
14 ;;; We compile some trivial character operations via inline expansion.
15 #!-sb-fluid
16 (declaim (inline standard-char-p graphic-char-p alpha-char-p
17                  upper-case-p lower-case-p both-case-p alphanumericp
18                  char-int))
19 (declaim (maybe-inline digit-char-p digit-weight))
20
21 (deftype char-code ()
22   `(integer 0 (,char-code-limit)))
23
24 #!+sb-unicode
25 (progn
26  (defvar *unicode-character-name-database*)
27  (defvar *unicode-character-name-huffman-tree*))
28
29 (macrolet
30     ((frob ()
31        (flet ((file (name type)
32                 (merge-pathnames (make-pathname
33                                   :directory
34                                   '(:relative :up :up "output")
35                                   :name name :type type)
36                                  sb!xc:*compile-file-truename*)))
37          (let ((character-database
38                 (with-open-file (stream (file "ucd" "dat")
39                                         :direction :input
40                                         :element-type '(unsigned-byte 8))
41                   (let* ((length (file-length stream))
42                          (array (make-array
43                                  length :element-type '(unsigned-byte 8))))
44                     (read-sequence array stream)
45                     array))))
46            `(progn
47               (declaim (type (simple-array (unsigned-byte 8) (*)) **character-database**))
48               (defglobal **character-database** ,character-database)
49               (defun !character-database-cold-init ()
50                 (setf **character-database** ,character-database))
51               ,(with-open-file (stream (file "ucd-names" "lisp-expr")
52                                        :direction :input
53                                        :element-type 'character)
54                                (let ((names (make-hash-table)))
55                                  #!+sb-unicode
56                                  (loop
57                                        for code-point = (read stream nil nil)
58                                        for char-name = (string-upcase (read stream nil nil))
59                                        while code-point
60                                        do (setf (gethash code-point names) char-name))
61                                  (let ((tree
62                                         #!+sb-unicode
63                                          (make-huffman-tree
64                                           (let (list)
65                                             (maphash (lambda (code name)
66                                                        (declare (ignore code))
67                                                        (push name list))
68                                                      names)
69                                             list)))
70                                        (code->name
71                                         (make-array (hash-table-count names)
72                                                     :fill-pointer 0))
73                                        (name->code nil))
74                                    (maphash (lambda (code name)
75                                               (vector-push
76                                                (cons code (huffman-encode name tree))
77                                                code->name))
78                                             names)
79                                    (setf name->code
80                                          (sort (copy-seq code->name) #'< :key #'cdr))
81                                    (setf code->name
82                                          (sort (copy-seq name->code) #'< :key #'car))
83                                    (setf names nil)
84                                    `(defun !character-name-database-cold-init ()
85                                       #!+sb-unicode
86                                       (setq *unicode-character-name-database*
87                                             (cons ',code->name ',name->code)
88                                             *unicode-character-name-huffman-tree* ',tree))))))))))
89   (frob))
90 #+sb-xc-host (!character-name-database-cold-init)
91
92 (defparameter *base-char-name-alist*
93   ;; Note: The *** markers here indicate character names which are
94   ;; required by the ANSI specification of #'CHAR-NAME. For the others,
95   ;; we prefer the ASCII standard name.
96   '((#x00 "Nul" "Null" "^@")
97     (#x01 "Soh" "^a")
98     (#x02 "Stx" "^b")
99     (#x03 "Etx" "^c")
100     (#x04 "Eot" "^d")
101     (#x05 "Enq" "^e")
102     (#x06 "Ack" "^f")
103     (#x07 "Bel" "Bell" "^g")
104     (#x08 "Backspace" "^h" "Bs") ; *** See Note above
105     (#x09 "Tab" "^i" "Ht") ; *** See Note above
106     (#x0A "Newline" "Linefeed" "^j" "Lf" "Nl") ; *** See Note above
107     (#x0B "Vt" "^k")
108     (#x0C "Page" "^l" "Form" "Formfeed" "Ff" "Np") ; *** See Note above
109     (#x0D "Return" "^m" "Cr") ; *** See Note above
110     (#x0E "So" "^n")
111     (#x0F "Si" "^o")
112     (#x10 "Dle" "^p")
113     (#x11 "Dc1" "^q")
114     (#x12 "Dc2" "^r")
115     (#x13 "Dc3" "^s")
116     (#x14 "Dc4" "^t")
117     (#x15 "Nak" "^u")
118     (#x16 "Syn" "^v")
119     (#x17 "Etb" "^w")
120     (#x18 "Can" "^x")
121     (#x19 "Em" "^y")
122     (#x1A "Sub" "^z")
123     (#x1B "Esc" "Escape" "^[" "Altmode" "Alt")
124     (#x1C "Fs" "^\\")
125     (#x1D "Gs" "^]")
126     (#x1E "Rs" "^^")
127     (#x1F "Us" "^_")
128     (#x20 "Space" "Sp") ; *** See Note above
129     (#x7f "Rubout" "Delete" "Del")
130     (#x80 "C80")
131     (#x81 "C81")
132     (#x82 "Break-Permitted")
133     (#x83 "No-Break-Permitted")
134     (#x84 "C84")
135     (#x85 "Next-Line")
136     (#x86 "Start-Selected-Area")
137     (#x87 "End-Selected-Area")
138     (#x88 "Character-Tabulation-Set")
139     (#x89 "Character-Tabulation-With-Justification")
140     (#x8A "Line-Tabulation-Set")
141     (#x8B "Partial-Line-Forward")
142     (#x8C "Partial-Line-Backward")
143     (#x8D "Reverse-Linefeed")
144     (#x8E "Single-Shift-Two")
145     (#x8F "Single-Shift-Three")
146     (#x90 "Device-Control-String")
147     (#x91 "Private-Use-One")
148     (#x92 "Private-Use-Two")
149     (#x93 "Set-Transmit-State")
150     (#x94 "Cancel-Character")
151     (#x95 "Message-Waiting")
152     (#x96 "Start-Guarded-Area")
153     (#x97 "End-Guarded-Area")
154     (#x98 "Start-String")
155     (#x99 "C99")
156     (#x9A "Single-Character-Introducer")
157     (#x9B "Control-Sequence-Introducer")
158     (#x9C "String-Terminator")
159     (#x9D "Operating-System-Command")
160     (#x9E "Privacy-Message")
161     (#x9F "Application-Program-Command"))) ; *** See Note above
162 \f
163 ;;;; UCD accessor functions
164 ;;;;
165 ;;;; FIXME: Document the format of the character database.
166
167 ;; (* 8 186) => 1488
168 ;; (+ 1488 (ash #x110000 -8)) => 5840
169 (defun ucd-index (char)
170   (let* ((cp (char-code char))
171          (cp-high (ash cp -8))
172          (page (aref **character-database** (+ 1488 cp-high))))
173     (+ 5840 (ash page 10) (ash (ldb (byte 8 0) cp) 2))))
174
175 (declaim (ftype (sfunction (t) (unsigned-byte 8)) ucd-value-0))
176 (defun ucd-value-0 (char)
177   (aref **character-database** (ucd-index char)))
178
179 (declaim (ftype (sfunction (t) (unsigned-byte 24)) ucd-value-1))
180 (defun ucd-value-1 (char)
181   (let ((index (ucd-index char))
182         (character-database **character-database**))
183     (dpb (aref character-database (+ index 3))
184          (byte 8 16)
185          (dpb (aref character-database (+ index 2))
186               (byte 8 8)
187               (aref character-database (1+ index))))))
188
189 (declaim (ftype (sfunction (t) (unsigned-byte 8)) ucd-general-category))
190 (defun ucd-general-category (char)
191   (aref **character-database** (* 8 (ucd-value-0 char))))
192
193 (defun ucd-decimal-digit (char)
194   (let ((decimal-digit (aref **character-database**
195                              (+ 3 (* 8 (ucd-value-0 char))))))
196     (when (< decimal-digit 10)
197       decimal-digit)))
198
199 (defun char-code (char)
200   #!+sb-doc
201   "Return the integer code of CHAR."
202   (char-code char))
203
204 (defun char-int (char)
205   #!+sb-doc
206   "Return the integer code of CHAR. (In SBCL this is the same as CHAR-CODE, as
207 there are no character bits or fonts.)"
208   (char-code char))
209
210 (defun code-char (code)
211   #!+sb-doc
212   "Return the character with the code CODE."
213   (code-char code))
214
215 (defun character (object)
216   #!+sb-doc
217   "Coerce OBJECT into a CHARACTER if possible. Legal inputs are characters,
218 strings and symbols of length 1."
219   (flet ((do-error (control args)
220            (error 'simple-type-error
221                   :datum object
222                   ;;?? how to express "symbol with name of length 1"?
223                   :expected-type '(or character (string 1))
224                   :format-control control
225                   :format-arguments args)))
226     (typecase object
227       (character object)
228       (string (if (= 1 (length (the string object)))
229                   (char object 0)
230                   (do-error
231                    "String is not of length one: ~S" (list object))))
232       (symbol (if (= 1 (length (symbol-name object)))
233                   (schar (symbol-name object) 0)
234                   (do-error
235                    "Symbol name is not of length one: ~S" (list object))))
236       (t (do-error "~S cannot be coerced to a character." (list object))))))
237
238 (defun char-name (char)
239   #!+sb-doc
240   "Return the name (a STRING) for a CHARACTER object."
241   (let ((char-code (char-code char)))
242     (or (second (assoc char-code *base-char-name-alist*))
243         #!+sb-unicode
244         (let ((h-code (cdr (binary-search char-code
245                                           (car *unicode-character-name-database*)
246                                           :key #'car))))
247           (cond
248             (h-code
249              (huffman-decode h-code *unicode-character-name-huffman-tree*))
250             ((< char-code #x10000)
251              (format nil "U~4,'0X" char-code))
252             (t
253              (format nil "U~8,'0X" char-code)))))))
254
255 (defun name-char (name)
256   #!+sb-doc
257   "Given an argument acceptable to STRING, NAME-CHAR returns a character whose
258 name is that string, if one exists. Otherwise, NIL is returned."
259   (or (let ((char-code (car (rassoc-if (lambda (names)
260                                          (member name names :test #'string-equal))
261                                        *base-char-name-alist*))))
262         (when char-code
263           (code-char char-code)))
264       #!+sb-unicode
265       (let ((encoding (huffman-encode (string-upcase name)
266                                        *unicode-character-name-huffman-tree*)))
267         (when encoding
268           (let* ((char-code
269                   (car (binary-search encoding
270                                       (cdr *unicode-character-name-database*)
271                                       :key #'cdr)))
272                  (name-string (string name))
273                  (name-length (length name-string)))
274             (cond
275               (char-code
276                (code-char char-code))
277               ((and (or (= name-length 9)
278                         (= name-length 5))
279                     (char-equal (char name-string 0) #\U)
280                     (loop for i from 1 below name-length
281                           always (digit-char-p (char name-string i) 16)))
282                (code-char (parse-integer name-string :start 1 :radix 16)))
283               (t
284                nil)))))))
285 \f
286 ;;;; predicates
287
288 (defun standard-char-p (char)
289   #!+sb-doc
290   "The argument must be a character object. STANDARD-CHAR-P returns T if the
291 argument is a standard character -- one of the 95 ASCII printing characters or
292 <return>."
293   (and (typep char 'base-char)
294        (let ((n (char-code (the base-char char))))
295          (or (< 31 n 127)
296              (= n 10)))))
297
298 (defun %standard-char-p (thing)
299   #!+sb-doc
300   "Return T if and only if THING is a standard-char. Differs from
301 STANDARD-CHAR-P in that THING doesn't have to be a character."
302   (and (characterp thing) (standard-char-p thing)))
303
304 (defun graphic-char-p (char)
305   #!+sb-doc
306   "The argument must be a character object. GRAPHIC-CHAR-P returns T if the
307 argument is a printing character (space through ~ in ASCII), otherwise returns
308 NIL."
309   (let ((n (char-code char)))
310     (or (< 31 n 127)
311         (< 159 n))))
312
313 (defun alpha-char-p (char)
314   #!+sb-doc
315   "The argument must be a character object. ALPHA-CHAR-P returns T if the
316 argument is an alphabetic character, A-Z or a-z; otherwise NIL."
317   (< (ucd-general-category char) 5))
318
319 (defun upper-case-p (char)
320   #!+sb-doc
321   "The argument must be a character object; UPPER-CASE-P returns T if the
322 argument is an upper-case character, NIL otherwise."
323   (= (ucd-value-0 char) 0))
324
325 (defun lower-case-p (char)
326   #!+sb-doc
327   "The argument must be a character object; LOWER-CASE-P returns T if the
328 argument is a lower-case character, NIL otherwise."
329   (= (ucd-value-0 char) 1))
330
331 (defun both-case-p (char)
332   #!+sb-doc
333   "The argument must be a character object. BOTH-CASE-P returns T if the
334 argument is an alphabetic character and if the character exists in both upper
335 and lower case. For ASCII, this is the same as ALPHA-CHAR-P."
336   (< (ucd-value-0 char) 2))
337
338 (defun digit-char-p (char &optional (radix 10.))
339   #!+sb-doc
340   "If char is a digit in the specified radix, returns the fixnum for which
341 that digit stands, else returns NIL."
342   (let ((m (- (char-code char) 48)))
343     (declare (fixnum m))
344     (cond ((<= radix 10.)
345            ;; Special-case decimal and smaller radices.
346            (if (and (>= m 0) (< m radix))  m  nil))
347           ;; Digits 0 - 9 are used as is, since radix is larger.
348           ((and (>= m 0) (< m 10)) m)
349           ;; Check for upper case A - Z.
350           ((and (>= (setq m (- m 7)) 10) (< m radix)) m)
351           ;; Also check lower case a - z.
352           ((and (>= (setq m (- m 32)) 10) (< m radix)) m)
353           ;; Else, fail.
354           (t (let ((number (ucd-decimal-digit char)))
355                (when (and number (< number radix))
356                  number))))))
357
358 (defun alphanumericp (char)
359   #!+sb-doc
360   "Given a character-object argument, ALPHANUMERICP returns T if the argument
361 is either numeric or alphabetic."
362   (let ((gc (ucd-general-category char)))
363     (or (< gc 5)
364         (= gc 12))))
365
366 (defun char= (character &rest more-characters)
367   #!+sb-doc
368   "Return T if all of the arguments are the same character."
369   (declare (truly-dynamic-extent more-characters))
370   (dolist (c more-characters t)
371     (declare (type character c))
372     (unless (eq c character) (return nil))))
373
374 (defun char/= (character &rest more-characters)
375   #!+sb-doc
376   "Return T if no two of the arguments are the same character."
377   (declare (truly-dynamic-extent more-characters))
378   (do* ((head character (car list))
379         (list more-characters (cdr list)))
380        ((null list) t)
381     (declare (type character head))
382     (dolist (c list)
383       (declare (type character c))
384       (when (eq head c) (return-from char/= nil)))))
385
386 (defun char< (character &rest more-characters)
387   #!+sb-doc
388   "Return T if the arguments are in strictly increasing alphabetic order."
389   (declare (truly-dynamic-extent more-characters))
390   (do* ((c character (car list))
391         (list more-characters (cdr list)))
392        ((null list) t)
393     (unless (< (char-int c)
394                (char-int (car list)))
395       (return nil))))
396
397 (defun char> (character &rest more-characters)
398   #!+sb-doc
399   "Return T if the arguments are in strictly decreasing alphabetic order."
400   (declare (truly-dynamic-extent more-characters))
401   (do* ((c character (car list))
402         (list more-characters (cdr list)))
403        ((null list) t)
404     (unless (> (char-int c)
405                (char-int (car list)))
406       (return nil))))
407
408 (defun char<= (character &rest more-characters)
409   #!+sb-doc
410   "Return T if the arguments are in strictly non-decreasing alphabetic order."
411   (declare (truly-dynamic-extent more-characters))
412   (do* ((c character (car list))
413         (list more-characters (cdr list)))
414        ((null list) t)
415     (unless (<= (char-int c)
416                 (char-int (car list)))
417       (return nil))))
418
419 (defun char>= (character &rest more-characters)
420   #!+sb-doc
421   "Return T if the arguments are in strictly non-increasing alphabetic order."
422   (declare (truly-dynamic-extent more-characters))
423   (do* ((c character (car list))
424         (list more-characters (cdr list)))
425        ((null list) t)
426     (unless (>= (char-int c)
427                 (char-int (car list)))
428       (return nil))))
429
430 ;;; EQUAL-CHAR-CODE is used by the following functions as a version of CHAR-INT
431 ;;;  which loses font, bits, and case info.
432
433 (defmacro equal-char-code (character)
434   (let ((ch (gensym)))
435     `(let ((,ch ,character))
436       (if (= (ucd-value-0 ,ch) 0)
437           (ucd-value-1 ,ch)
438           (char-code ,ch)))))
439
440 (defun two-arg-char-equal (c1 c2)
441   (= (equal-char-code c1) (equal-char-code c2)))
442
443 (defun char-equal (character &rest more-characters)
444   #!+sb-doc
445   "Return T if all of the arguments are the same character.
446 Case is ignored."
447   (declare (truly-dynamic-extent more-characters))
448   (do ((clist more-characters (cdr clist)))
449       ((null clist) t)
450     (unless (two-arg-char-equal (car clist) character)
451       (return nil))))
452
453 (defun two-arg-char-not-equal (c1 c2)
454   (/= (equal-char-code c1) (equal-char-code c2)))
455
456 (defun char-not-equal (character &rest more-characters)
457   #!+sb-doc
458   "Return T if no two of the arguments are the same character.
459 Case is ignored."
460   (declare (truly-dynamic-extent more-characters))
461   (do* ((head character (car list))
462         (list more-characters (cdr list)))
463        ((null list) t)
464     (unless (do* ((l list (cdr l)))
465                  ((null l) t)
466               (if (two-arg-char-equal head (car l))
467                   (return nil)))
468       (return nil))))
469
470 (defun two-arg-char-lessp (c1 c2)
471   (< (equal-char-code c1) (equal-char-code c2)))
472
473 (defun char-lessp (character &rest more-characters)
474   #!+sb-doc
475   "Return T if the arguments are in strictly increasing alphabetic order.
476 Case is ignored."
477   (declare (truly-dynamic-extent more-characters))
478   (do* ((c character (car list))
479         (list more-characters (cdr list)))
480        ((null list) t)
481     (unless (two-arg-char-lessp c (car list))
482       (return nil))))
483
484 (defun two-arg-char-greaterp (c1 c2)
485   (> (equal-char-code c1) (equal-char-code c2)))
486
487 (defun char-greaterp (character &rest more-characters)
488   #!+sb-doc
489   "Return T if the arguments are in strictly decreasing alphabetic order.
490 Case is ignored."
491   (declare (truly-dynamic-extent more-characters))
492   (do* ((c character (car list))
493         (list more-characters (cdr list)))
494        ((null list) t)
495     (unless (two-arg-char-greaterp c (car list))
496       (return nil))))
497
498 (defun two-arg-char-not-greaterp (c1 c2)
499   (<= (equal-char-code c1) (equal-char-code c2)))
500
501 (defun char-not-greaterp (character &rest more-characters)
502   #!+sb-doc
503   "Return T if the arguments are in strictly non-decreasing alphabetic order.
504 Case is ignored."
505   (declare (truly-dynamic-extent more-characters))
506   (do* ((c character (car list))
507         (list more-characters (cdr list)))
508        ((null list) t)
509     (unless (two-arg-char-not-greaterp c (car list))
510       (return nil))))
511
512 (defun two-arg-char-not-lessp (c1 c2)
513   (>= (equal-char-code c1) (equal-char-code c2)))
514
515 (defun char-not-lessp (character &rest more-characters)
516   #!+sb-doc
517   "Return T if the arguments are in strictly non-increasing alphabetic order.
518 Case is ignored."
519   (declare (truly-dynamic-extent more-characters))
520   (do* ((c character (car list))
521         (list more-characters (cdr list)))
522        ((null list) t)
523     (unless (two-arg-char-not-lessp c (car list))
524       (return nil))))
525 \f
526 ;;;; miscellaneous functions
527
528 (defun char-upcase (char)
529   #!+sb-doc
530   "Return CHAR converted to upper-case if that is possible. Don't convert
531 lowercase eszet (U+DF)."
532   (if (= (ucd-value-0 char) 1)
533       (code-char (ucd-value-1 char))
534       char))
535
536 (defun char-downcase (char)
537   #!+sb-doc
538   "Return CHAR converted to lower-case if that is possible."
539   (if (= (ucd-value-0 char) 0)
540       (code-char (ucd-value-1 char))
541       char))
542
543 (defun digit-char (weight &optional (radix 10))
544   #!+sb-doc
545   "All arguments must be integers. Returns a character object that represents
546 a digit of the given weight in the specified radix. Returns NIL if no such
547 character exists."
548   (and (typep weight 'fixnum)
549        (>= weight 0) (< weight radix) (< weight 36)
550        (code-char (if (< weight 10) (+ 48 weight) (+ 55 weight)))))