Incorporate some decomposition information in ucd table
[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 ;;; The first (* 8 395) => 3160 entries in **CHARACTER-DATABASE**
166 ;;; contain entries for the distinct character attributes:
167 ;;; specifically, indexes into the GC kinds, Bidi kinds, CCC kinds,
168 ;;; the decimal digit property, the digit property and the
169 ;;; bidi-mirrored boolean property.  (There are two spare bytes for
170 ;;; other information, should that become necessary)
171 ;;;
172 ;;; the next (ash #x110000 -8) entries contain single-byte indexes
173 ;;; into a table of 256-element 4-byte-sized entries.  These entries
174 ;;; follow directly on, and are of the form
175 ;;; {attribute-index[11b],transformed-code-point[21b]}x256, where the
176 ;;; attribute index is an index into the miscellaneous information
177 ;;; table, and the transformed code point is the code point of the
178 ;;; simple mapping of the character to its lowercase or uppercase
179 ;;; equivalent, as appropriate and if any.
180 ;;;
181 ;;; I feel the opacity of the above suggests the need for a diagram:
182 ;;;
183 ;;;         C  _______________________________________
184 ;;;           /                                       \
185 ;;;          L                                         \
186 ;;;  [***************|=============================|--------...]
187 ;;;                 (a)      \                       _
188 ;;;                         A \______________________/| B
189 ;;;
190 ;;; To look up information about a character, take the high 13 bits of
191 ;;; its code point, and index the character database with that and a
192 ;;; base of 3160 (going past the miscellaneous information[*], so
193 ;;; treating (a) as the start of the array).  This, labelled A, gives
194 ;;; us another index into the detailed pages[-], which we can use to
195 ;;; look up the details for the character in question: we add the low
196 ;;; 8 bits of the character, shifted twice (because we have four-byte
197 ;;; table entries) to 1024 times the `page' index, with a base of 6088
198 ;;; to skip over everything else.  This gets us to point B.  If we're
199 ;;; after a transformed code point (i.e. an upcase or downcase
200 ;;; operation), we can simply read it off now, beginning with an
201 ;;; offset of 11 bits from point B in some endianness; if we're
202 ;;; looking for miscellaneous information, we take the 11-bit value at
203 ;;; B, and index the character database once more to get to the
204 ;;; relevant miscellaneous information.
205 ;;;
206 ;;; As an optimization to the common case (pun intended) of looking up
207 ;;; case information for a character, the entries in C above are
208 ;;; sorted such that the characters which are UPPER-CASE-P in CL terms
209 ;;; have index values lower than all others, followed by those which
210 ;;; are LOWER-CASE-P in CL terms; this permits implementation of
211 ;;; character case tests without actually going to the trouble of
212 ;;; looking up the value associated with the index.  (Actually, this
213 ;;; isn't just a speed optimization; the information about whether a
214 ;;; character is BOTH-CASE-P is used just in the ordering and not
215 ;;; explicitly recorded in the database).
216 ;;;
217 ;;; The moral of all this?  Next time, don't just say "FIXME: document
218 ;;; this"
219 (defun ucd-index (char)
220   (let* ((cp (char-code char))
221          (cp-high (ash cp -8))
222          (page (aref **character-database** (+ 3160 cp-high))))
223     (+ 7512 (ash page 10) (ash (ldb (byte 8 0) cp) 2))))
224
225 (declaim (ftype (sfunction (t) (unsigned-byte 11)) ucd-value-0))
226 (defun ucd-value-0 (char)
227   (let ((index (ucd-index char))
228         (character-database **character-database**))
229     (dpb (aref character-database index)
230          (byte 8 3)
231          (ldb (byte 3 5) (aref character-database (+ index 1))))))
232
233 (declaim (ftype (sfunction (t) (unsigned-byte 21)) ucd-value-1))
234 (defun ucd-value-1 (char)
235   (let ((index (ucd-index char))
236         (character-database **character-database**))
237     (dpb (aref character-database (+ index 1))
238          (byte 5 16)
239          (dpb (aref character-database (+ index 2))
240               (byte 8 8)
241               (aref character-database (+ index 3))))))
242
243 (declaim (ftype (sfunction (t) (unsigned-byte 8)) ucd-general-category))
244 (defun ucd-general-category (char)
245   (aref **character-database** (* 8 (ucd-value-0 char))))
246
247 (defun ucd-decimal-digit (char)
248   (let ((decimal-digit (aref **character-database**
249                              (+ 3 (* 8 (ucd-value-0 char))))))
250     (when (< decimal-digit 10)
251       decimal-digit)))
252
253 (defun char-code (char)
254   #!+sb-doc
255   "Return the integer code of CHAR."
256   (char-code char))
257
258 (defun char-int (char)
259   #!+sb-doc
260   "Return the integer code of CHAR. (In SBCL this is the same as CHAR-CODE, as
261 there are no character bits or fonts.)"
262   (char-code char))
263
264 (defun code-char (code)
265   #!+sb-doc
266   "Return the character with the code CODE."
267   (code-char code))
268
269 (defun character (object)
270   #!+sb-doc
271   "Coerce OBJECT into a CHARACTER if possible. Legal inputs are characters,
272 strings and symbols of length 1."
273   (flet ((do-error (control args)
274            (error 'simple-type-error
275                   :datum object
276                   ;;?? how to express "symbol with name of length 1"?
277                   :expected-type '(or character (string 1))
278                   :format-control control
279                   :format-arguments args)))
280     (typecase object
281       (character object)
282       (string (if (= 1 (length (the string object)))
283                   (char object 0)
284                   (do-error
285                    "String is not of length one: ~S" (list object))))
286       (symbol (if (= 1 (length (symbol-name object)))
287                   (schar (symbol-name object) 0)
288                   (do-error
289                    "Symbol name is not of length one: ~S" (list object))))
290       (t (do-error "~S cannot be coerced to a character." (list object))))))
291
292 (defun char-name (char)
293   #!+sb-doc
294   "Return the name (a STRING) for a CHARACTER object."
295   (let ((char-code (char-code char)))
296     (or (second (assoc char-code *base-char-name-alist*))
297         #!+sb-unicode
298         (let ((h-code (cdr (binary-search char-code
299                                           (car *unicode-character-name-database*)
300                                           :key #'car))))
301           (cond
302             (h-code
303              (huffman-decode h-code *unicode-character-name-huffman-tree*))
304             ((< char-code #x10000)
305              (format nil "U~4,'0X" char-code))
306             (t
307              (format nil "U~8,'0X" char-code)))))))
308
309 (defun name-char (name)
310   #!+sb-doc
311   "Given an argument acceptable to STRING, NAME-CHAR returns a character whose
312 name is that string, if one exists. Otherwise, NIL is returned."
313   (or (let ((char-code (car (rassoc-if (lambda (names)
314                                          (member name names :test #'string-equal))
315                                        *base-char-name-alist*))))
316         (when char-code
317           (code-char char-code)))
318       #!+sb-unicode
319       (let ((encoding (huffman-encode (string-upcase name)
320                                        *unicode-character-name-huffman-tree*)))
321         (when encoding
322           (let* ((char-code
323                   (car (binary-search encoding
324                                       (cdr *unicode-character-name-database*)
325                                       :key #'cdr)))
326                  (name-string (string name))
327                  (name-length (length name-string)))
328             (cond
329               (char-code
330                (code-char char-code))
331               ((and (or (= name-length 9)
332                         (= name-length 5))
333                     (char-equal (char name-string 0) #\U)
334                     (loop for i from 1 below name-length
335                           always (digit-char-p (char name-string i) 16)))
336                (code-char (parse-integer name-string :start 1 :radix 16)))
337               (t
338                nil)))))))
339 \f
340 ;;;; predicates
341
342 (defun standard-char-p (char)
343   #!+sb-doc
344   "The argument must be a character object. STANDARD-CHAR-P returns T if the
345 argument is a standard character -- one of the 95 ASCII printing characters or
346 <return>."
347   (and (typep char 'base-char)
348        (let ((n (char-code (the base-char char))))
349          (or (< 31 n 127)
350              (= n 10)))))
351
352 (defun %standard-char-p (thing)
353   #!+sb-doc
354   "Return T if and only if THING is a standard-char. Differs from
355 STANDARD-CHAR-P in that THING doesn't have to be a character."
356   (and (characterp thing) (standard-char-p thing)))
357
358 (defun graphic-char-p (char)
359   #!+sb-doc
360   "The argument must be a character object. GRAPHIC-CHAR-P returns T if the
361 argument is a printing character (space through ~ in ASCII), otherwise returns
362 NIL."
363   (let ((n (char-code char)))
364     (or (< 31 n 127)
365         (< 159 n))))
366
367 (defun alpha-char-p (char)
368   #!+sb-doc
369   "The argument must be a character object. ALPHA-CHAR-P returns T if the
370 argument is an alphabetic character, A-Z or a-z; otherwise NIL."
371   (< (ucd-general-category char) 5))
372
373 (defun upper-case-p (char)
374   #!+sb-doc
375   "The argument must be a character object; UPPER-CASE-P returns T if the
376 argument is an upper-case character, NIL otherwise."
377   (< (ucd-value-0 char) 4))
378
379 (defun lower-case-p (char)
380   #!+sb-doc
381   "The argument must be a character object; LOWER-CASE-P returns T if the
382 argument is a lower-case character, NIL otherwise."
383   (< 3 (ucd-value-0 char) 8))
384
385 (defun both-case-p (char)
386   #!+sb-doc
387   "The argument must be a character object. BOTH-CASE-P returns T if the
388 argument is an alphabetic character and if the character exists in both upper
389 and lower case. For ASCII, this is the same as ALPHA-CHAR-P."
390   (< (ucd-value-0 char) 8))
391
392 (defun digit-char-p (char &optional (radix 10.))
393   #!+sb-doc
394   "If char is a digit in the specified radix, returns the fixnum for which
395 that digit stands, else returns NIL."
396   (let ((m (- (char-code char) 48)))
397     (declare (fixnum m))
398     (cond ((<= radix 10.)
399            ;; Special-case decimal and smaller radices.
400            (if (and (>= m 0) (< m radix))  m  nil))
401           ;; Digits 0 - 9 are used as is, since radix is larger.
402           ((and (>= m 0) (< m 10)) m)
403           ;; Check for upper case A - Z.
404           ((and (>= (setq m (- m 7)) 10) (< m radix)) m)
405           ;; Also check lower case a - z.
406           ((and (>= (setq m (- m 32)) 10) (< m radix)) m)
407           ;; Else, fail.
408           (t (let ((number (ucd-decimal-digit char)))
409                (when (and number (< number radix))
410                  number))))))
411
412 (defun alphanumericp (char)
413   #!+sb-doc
414   "Given a character-object argument, ALPHANUMERICP returns T if the argument
415 is either numeric or alphabetic."
416   (let ((gc (ucd-general-category char)))
417     (or (< gc 5)
418         (= gc 12))))
419
420 (defun char= (character &rest more-characters)
421   #!+sb-doc
422   "Return T if all of the arguments are the same character."
423   (declare (truly-dynamic-extent more-characters))
424   (dolist (c more-characters t)
425     (declare (type character c))
426     (unless (eq c character) (return nil))))
427
428 (defun char/= (character &rest more-characters)
429   #!+sb-doc
430   "Return T if no two of the arguments are the same character."
431   (declare (truly-dynamic-extent more-characters))
432   (do* ((head character (car list))
433         (list more-characters (cdr list)))
434        ((null list) t)
435     (declare (type character head))
436     (dolist (c list)
437       (declare (type character c))
438       (when (eq head c) (return-from char/= nil)))))
439
440 (defun char< (character &rest more-characters)
441   #!+sb-doc
442   "Return T if the arguments are in strictly increasing alphabetic order."
443   (declare (truly-dynamic-extent more-characters))
444   (do* ((c character (car list))
445         (list more-characters (cdr list)))
446        ((null list) t)
447     (unless (< (char-int c)
448                (char-int (car list)))
449       (return nil))))
450
451 (defun char> (character &rest more-characters)
452   #!+sb-doc
453   "Return T if the arguments are in strictly decreasing alphabetic order."
454   (declare (truly-dynamic-extent more-characters))
455   (do* ((c character (car list))
456         (list more-characters (cdr list)))
457        ((null list) t)
458     (unless (> (char-int c)
459                (char-int (car list)))
460       (return nil))))
461
462 (defun char<= (character &rest more-characters)
463   #!+sb-doc
464   "Return T if the arguments are in strictly non-decreasing alphabetic order."
465   (declare (truly-dynamic-extent more-characters))
466   (do* ((c character (car list))
467         (list more-characters (cdr list)))
468        ((null list) t)
469     (unless (<= (char-int c)
470                 (char-int (car list)))
471       (return nil))))
472
473 (defun char>= (character &rest more-characters)
474   #!+sb-doc
475   "Return T if the arguments are in strictly non-increasing alphabetic order."
476   (declare (truly-dynamic-extent more-characters))
477   (do* ((c character (car list))
478         (list more-characters (cdr list)))
479        ((null list) t)
480     (unless (>= (char-int c)
481                 (char-int (car list)))
482       (return nil))))
483
484 ;;; EQUAL-CHAR-CODE is used by the following functions as a version of CHAR-INT
485 ;;;  which loses font, bits, and case info.
486
487 (defmacro equal-char-code (character)
488   (let ((ch (gensym)))
489     `(let ((,ch ,character))
490       (if (= (ucd-value-0 ,ch) 0)
491           (ucd-value-1 ,ch)
492           (char-code ,ch)))))
493
494 (defun two-arg-char-equal (c1 c2)
495   (= (equal-char-code c1) (equal-char-code c2)))
496
497 (defun char-equal (character &rest more-characters)
498   #!+sb-doc
499   "Return T if all of the arguments are the same character.
500 Case is ignored."
501   (declare (truly-dynamic-extent more-characters))
502   (do ((clist more-characters (cdr clist)))
503       ((null clist) t)
504     (unless (two-arg-char-equal (car clist) character)
505       (return nil))))
506
507 (defun two-arg-char-not-equal (c1 c2)
508   (/= (equal-char-code c1) (equal-char-code c2)))
509
510 (defun char-not-equal (character &rest more-characters)
511   #!+sb-doc
512   "Return T if no two of the arguments are the same character.
513 Case is ignored."
514   (declare (truly-dynamic-extent more-characters))
515   (do* ((head character (car list))
516         (list more-characters (cdr list)))
517        ((null list) t)
518     (unless (do* ((l list (cdr l)))
519                  ((null l) t)
520               (if (two-arg-char-equal head (car l))
521                   (return nil)))
522       (return nil))))
523
524 (defun two-arg-char-lessp (c1 c2)
525   (< (equal-char-code c1) (equal-char-code c2)))
526
527 (defun char-lessp (character &rest more-characters)
528   #!+sb-doc
529   "Return T if the arguments are in strictly increasing alphabetic order.
530 Case is ignored."
531   (declare (truly-dynamic-extent more-characters))
532   (do* ((c character (car list))
533         (list more-characters (cdr list)))
534        ((null list) t)
535     (unless (two-arg-char-lessp c (car list))
536       (return nil))))
537
538 (defun two-arg-char-greaterp (c1 c2)
539   (> (equal-char-code c1) (equal-char-code c2)))
540
541 (defun char-greaterp (character &rest more-characters)
542   #!+sb-doc
543   "Return T if the arguments are in strictly decreasing alphabetic order.
544 Case is ignored."
545   (declare (truly-dynamic-extent more-characters))
546   (do* ((c character (car list))
547         (list more-characters (cdr list)))
548        ((null list) t)
549     (unless (two-arg-char-greaterp c (car list))
550       (return nil))))
551
552 (defun two-arg-char-not-greaterp (c1 c2)
553   (<= (equal-char-code c1) (equal-char-code c2)))
554
555 (defun char-not-greaterp (character &rest more-characters)
556   #!+sb-doc
557   "Return T if the arguments are in strictly non-decreasing alphabetic order.
558 Case is ignored."
559   (declare (truly-dynamic-extent more-characters))
560   (do* ((c character (car list))
561         (list more-characters (cdr list)))
562        ((null list) t)
563     (unless (two-arg-char-not-greaterp c (car list))
564       (return nil))))
565
566 (defun two-arg-char-not-lessp (c1 c2)
567   (>= (equal-char-code c1) (equal-char-code c2)))
568
569 (defun char-not-lessp (character &rest more-characters)
570   #!+sb-doc
571   "Return T if the arguments are in strictly non-increasing alphabetic order.
572 Case is ignored."
573   (declare (truly-dynamic-extent more-characters))
574   (do* ((c character (car list))
575         (list more-characters (cdr list)))
576        ((null list) t)
577     (unless (two-arg-char-not-lessp c (car list))
578       (return nil))))
579 \f
580 ;;;; miscellaneous functions
581
582 (defun char-upcase (char)
583   #!+sb-doc
584   "Return CHAR converted to upper-case if that is possible. Don't convert
585 lowercase eszet (U+DF)."
586   (if (< 3 (ucd-value-0 char) 8)
587       (code-char (ucd-value-1 char))
588       char))
589
590 (defun char-downcase (char)
591   #!+sb-doc
592   "Return CHAR converted to lower-case if that is possible."
593   (if (< (ucd-value-0 char) 4)
594       (code-char (ucd-value-1 char))
595       char))
596
597 (defun digit-char (weight &optional (radix 10))
598   #!+sb-doc
599   "All arguments must be integers. Returns a character object that represents
600 a digit of the given weight in the specified radix. Returns NIL if no such
601 character exists."
602   (and (typep weight 'fixnum)
603        (>= weight 0) (< weight radix) (< weight 36)
604        (code-char (if (< weight 10) (+ 48 weight) (+ 55 weight)))))