implement primary and canonical composition, and hence NFC/NFKC
[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               (read-ub8-vector (pathname)
38                 (with-open-file (stream pathname
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          (let ((character-database (read-ub8-vector (file "ucd" "dat")))
47                (decompositions (read-ub8-vector (file "decomp" "dat")))
48                (long-decompositions (read-ub8-vector (file "ldecomp" "dat"))))
49            `(progn
50               (declaim (type (simple-array (unsigned-byte 8) (*)) **character-database** **character-decompositions** **character-long-decompositions**))
51               (defglobal **character-database** ,character-database)
52               (defglobal **character-decompositions** ,decompositions)
53               (defglobal **character-long-decompositions** ,long-decompositions)
54               (defglobal **character-primary-compositions**
55                 (let ((table (make-hash-table))
56                       (info ,(read-ub8-vector (file "comp" "dat"))))
57                   (flet ((code (j)
58                            (dpb (aref info (* 4 j))
59                                 (byte 8 24)
60                                 (dpb (aref info (+ (* 4 j) 1))
61                                      (byte 8 16)
62                                      (dpb (aref info (+ (* 4 j) 2))
63                                           (byte 8 8)
64                                           (aref info (+ (* 4 j) 3)))))))
65                     (dotimes (i (/ (length info) 12) table)
66                       (setf (gethash (dpb (code (* 3 i)) (byte 21 21)
67                                           (code (1+ (* 3 i))))
68                                      table)
69                             (code-char (code (+ (* 3 i) 2))))))))
70               (defun !character-database-cold-init ()
71                 (setf **character-database** ,character-database))
72               ,(with-open-file (stream (file "ucd-names" "lisp-expr")
73                                        :direction :input
74                                        :element-type 'character)
75                                (let ((names (make-hash-table)))
76                                  #!+sb-unicode
77                                  (loop
78                                        for code-point = (read stream nil nil)
79                                        for char-name = (string-upcase (read stream nil nil))
80                                        while code-point
81                                        do (setf (gethash code-point names) char-name))
82                                  (let ((tree
83                                         #!+sb-unicode
84                                          (make-huffman-tree
85                                           (let (list)
86                                             (maphash (lambda (code name)
87                                                        (declare (ignore code))
88                                                        (push name list))
89                                                      names)
90                                             list)))
91                                        (code->name
92                                         (make-array (hash-table-count names)
93                                                     :fill-pointer 0))
94                                        (name->code nil))
95                                    (maphash (lambda (code name)
96                                               (vector-push
97                                                (cons code (huffman-encode name tree))
98                                                code->name))
99                                             names)
100                                    (setf name->code
101                                          (sort (copy-seq code->name) #'< :key #'cdr))
102                                    (setf code->name
103                                          (sort (copy-seq name->code) #'< :key #'car))
104                                    (setf names nil)
105                                    `(defun !character-name-database-cold-init ()
106                                       #!+sb-unicode
107                                       (setq *unicode-character-name-database*
108                                             (cons ',code->name ',name->code)
109                                             *unicode-character-name-huffman-tree* ',tree))))))))))
110   (frob))
111 #+sb-xc-host (!character-name-database-cold-init)
112
113 (defparameter *base-char-name-alist*
114   ;; Note: The *** markers here indicate character names which are
115   ;; required by the ANSI specification of #'CHAR-NAME. For the others,
116   ;; we prefer the ASCII standard name.
117   '((#x00 "Nul" "Null" "^@")
118     (#x01 "Soh" "^a")
119     (#x02 "Stx" "^b")
120     (#x03 "Etx" "^c")
121     (#x04 "Eot" "^d")
122     (#x05 "Enq" "^e")
123     (#x06 "Ack" "^f")
124     (#x07 "Bel" "Bell" "^g")
125     (#x08 "Backspace" "^h" "Bs") ; *** See Note above
126     (#x09 "Tab" "^i" "Ht") ; *** See Note above
127     (#x0A "Newline" "Linefeed" "^j" "Lf" "Nl") ; *** See Note above
128     (#x0B "Vt" "^k")
129     (#x0C "Page" "^l" "Form" "Formfeed" "Ff" "Np") ; *** See Note above
130     (#x0D "Return" "^m" "Cr") ; *** See Note above
131     (#x0E "So" "^n")
132     (#x0F "Si" "^o")
133     (#x10 "Dle" "^p")
134     (#x11 "Dc1" "^q")
135     (#x12 "Dc2" "^r")
136     (#x13 "Dc3" "^s")
137     (#x14 "Dc4" "^t")
138     (#x15 "Nak" "^u")
139     (#x16 "Syn" "^v")
140     (#x17 "Etb" "^w")
141     (#x18 "Can" "^x")
142     (#x19 "Em" "^y")
143     (#x1A "Sub" "^z")
144     (#x1B "Esc" "Escape" "^[" "Altmode" "Alt")
145     (#x1C "Fs" "^\\")
146     (#x1D "Gs" "^]")
147     (#x1E "Rs" "^^")
148     (#x1F "Us" "^_")
149     (#x20 "Space" "Sp") ; *** See Note above
150     (#x7f "Rubout" "Delete" "Del")
151     (#x80 "C80")
152     (#x81 "C81")
153     (#x82 "Break-Permitted")
154     (#x83 "No-Break-Permitted")
155     (#x84 "C84")
156     (#x85 "Next-Line")
157     (#x86 "Start-Selected-Area")
158     (#x87 "End-Selected-Area")
159     (#x88 "Character-Tabulation-Set")
160     (#x89 "Character-Tabulation-With-Justification")
161     (#x8A "Line-Tabulation-Set")
162     (#x8B "Partial-Line-Forward")
163     (#x8C "Partial-Line-Backward")
164     (#x8D "Reverse-Linefeed")
165     (#x8E "Single-Shift-Two")
166     (#x8F "Single-Shift-Three")
167     (#x90 "Device-Control-String")
168     (#x91 "Private-Use-One")
169     (#x92 "Private-Use-Two")
170     (#x93 "Set-Transmit-State")
171     (#x94 "Cancel-Character")
172     (#x95 "Message-Waiting")
173     (#x96 "Start-Guarded-Area")
174     (#x97 "End-Guarded-Area")
175     (#x98 "Start-String")
176     (#x99 "C99")
177     (#x9A "Single-Character-Introducer")
178     (#x9B "Control-Sequence-Introducer")
179     (#x9C "String-Terminator")
180     (#x9D "Operating-System-Command")
181     (#x9E "Privacy-Message")
182     (#x9F "Application-Program-Command"))) ; *** See Note above
183 \f
184 ;;;; UCD accessor functions
185
186 ;;; The first (* 8 396) => 3168 entries in **CHARACTER-DATABASE**
187 ;;; contain entries for the distinct character attributes:
188 ;;; specifically, indexes into the GC kinds, Bidi kinds, CCC kinds,
189 ;;; the decimal digit property, the digit property and the
190 ;;; bidi-mirrored boolean property.  (There are two spare bytes for
191 ;;; other information, should that become necessary)
192 ;;;
193 ;;; the next (ash #x110000 -8) entries contain single-byte indexes
194 ;;; into a table of 256-element 4-byte-sized entries.  These entries
195 ;;; follow directly on, and are of the form
196 ;;; {attribute-index[11b],transformed-code-point[21b]}x256, where the
197 ;;; attribute index is an index into the miscellaneous information
198 ;;; table, and the transformed code point is the code point of the
199 ;;; simple mapping of the character to its lowercase or uppercase
200 ;;; equivalent, as appropriate and if any.
201 ;;;
202 ;;; I feel the opacity of the above suggests the need for a diagram:
203 ;;;
204 ;;;         C  _______________________________________
205 ;;;           /                                       \
206 ;;;          L                                         \
207 ;;;  [***************|=============================|--------...]
208 ;;;                 (a)      \                       _
209 ;;;                         A \______________________/| B
210 ;;;
211 ;;; To look up information about a character, take the high 13 bits of
212 ;;; its code point, and index the character database with that and a
213 ;;; base of 3168 (going past the miscellaneous information[*], so
214 ;;; treating (a) as the start of the array).  This, labelled A, gives
215 ;;; us another index into the detailed pages[-], which we can use to
216 ;;; look up the details for the character in question: we add the low
217 ;;; 8 bits of the character, shifted twice (because we have four-byte
218 ;;; table entries) to 1024 times the `page' index, with a base of 7520
219 ;;; to skip over everything else.  This gets us to point B.  If we're
220 ;;; after a transformed code point (i.e. an upcase or downcase
221 ;;; operation), we can simply read it off now, beginning with an
222 ;;; offset of 11 bits from point B in some endianness; if we're
223 ;;; looking for miscellaneous information, we take the 11-bit value at
224 ;;; B, and index the character database once more to get to the
225 ;;; relevant miscellaneous information.
226 ;;;
227 ;;; As an optimization to the common case (pun intended) of looking up
228 ;;; case information for a character, the entries in C above are
229 ;;; sorted such that the characters which are UPPER-CASE-P in CL terms
230 ;;; have index values lower than all others, followed by those which
231 ;;; are LOWER-CASE-P in CL terms; this permits implementation of
232 ;;; character case tests without actually going to the trouble of
233 ;;; looking up the value associated with the index.  (Actually, this
234 ;;; isn't just a speed optimization; the information about whether a
235 ;;; character is BOTH-CASE-P is used just in the ordering and not
236 ;;; explicitly recorded in the database).
237 ;;;
238 ;;; The moral of all this?  Next time, don't just say "FIXME: document
239 ;;; this"
240 (defun ucd-index (char)
241   (let* ((cp (char-code char))
242          (cp-high (ash cp -8))
243          (page (aref **character-database** (+ 3168 cp-high))))
244     (+ 7520 (ash page 10) (ash (ldb (byte 8 0) cp) 2))))
245
246 (declaim (ftype (sfunction (t) (unsigned-byte 11)) ucd-value-0))
247 (defun ucd-value-0 (char)
248   (let ((index (ucd-index char))
249         (character-database **character-database**))
250     (dpb (aref character-database index)
251          (byte 8 3)
252          (ldb (byte 3 5) (aref character-database (+ index 1))))))
253
254 (declaim (ftype (sfunction (t) (unsigned-byte 21)) ucd-value-1))
255 (defun ucd-value-1 (char)
256   (let ((index (ucd-index char))
257         (character-database **character-database**))
258     (dpb (aref character-database (+ index 1))
259          (byte 5 16)
260          (dpb (aref character-database (+ index 2))
261               (byte 8 8)
262               (aref character-database (+ index 3))))))
263
264 (declaim (ftype (sfunction (t) (unsigned-byte 8)) ucd-general-category))
265 (defun ucd-general-category (char)
266   (aref **character-database** (* 8 (ucd-value-0 char))))
267
268 (defun ucd-decimal-digit (char)
269   (let ((decimal-digit (aref **character-database**
270                              (+ 3 (* 8 (ucd-value-0 char))))))
271     (when (< decimal-digit 10)
272       decimal-digit)))
273 (declaim (ftype (sfunction (t) (unsigned-byte 8)) ucd-ccc))
274 (defun ucd-ccc (char)
275   (aref **character-database** (+ 2 (* 8 (ucd-value-0 char)))))
276
277 (defun char-code (char)
278   #!+sb-doc
279   "Return the integer code of CHAR."
280   (char-code char))
281
282 (defun char-int (char)
283   #!+sb-doc
284   "Return the integer code of CHAR. (In SBCL this is the same as CHAR-CODE, as
285 there are no character bits or fonts.)"
286   (char-code char))
287
288 (defun code-char (code)
289   #!+sb-doc
290   "Return the character with the code CODE."
291   (code-char code))
292
293 (defun character (object)
294   #!+sb-doc
295   "Coerce OBJECT into a CHARACTER if possible. Legal inputs are characters,
296 strings and symbols of length 1."
297   (flet ((do-error (control args)
298            (error 'simple-type-error
299                   :datum object
300                   ;;?? how to express "symbol with name of length 1"?
301                   :expected-type '(or character (string 1))
302                   :format-control control
303                   :format-arguments args)))
304     (typecase object
305       (character object)
306       (string (if (= 1 (length (the string object)))
307                   (char object 0)
308                   (do-error
309                    "String is not of length one: ~S" (list object))))
310       (symbol (if (= 1 (length (symbol-name object)))
311                   (schar (symbol-name object) 0)
312                   (do-error
313                    "Symbol name is not of length one: ~S" (list object))))
314       (t (do-error "~S cannot be coerced to a character." (list object))))))
315
316 (defun char-name (char)
317   #!+sb-doc
318   "Return the name (a STRING) for a CHARACTER object."
319   (let ((char-code (char-code char)))
320     (or (second (assoc char-code *base-char-name-alist*))
321         #!+sb-unicode
322         (let ((h-code (cdr (binary-search char-code
323                                           (car *unicode-character-name-database*)
324                                           :key #'car))))
325           (cond
326             (h-code
327              (huffman-decode h-code *unicode-character-name-huffman-tree*))
328             ((< char-code #x10000)
329              (format nil "U~4,'0X" char-code))
330             (t
331              (format nil "U~8,'0X" char-code)))))))
332
333 (defun name-char (name)
334   #!+sb-doc
335   "Given an argument acceptable to STRING, NAME-CHAR returns a character whose
336 name is that string, if one exists. Otherwise, NIL is returned."
337   (or (let ((char-code (car (rassoc-if (lambda (names)
338                                          (member name names :test #'string-equal))
339                                        *base-char-name-alist*))))
340         (when char-code
341           (code-char char-code)))
342       #!+sb-unicode
343       (let ((encoding (huffman-encode (string-upcase name)
344                                        *unicode-character-name-huffman-tree*)))
345         (when encoding
346           (let* ((char-code
347                   (car (binary-search encoding
348                                       (cdr *unicode-character-name-database*)
349                                       :key #'cdr)))
350                  (name-string (string name))
351                  (name-length (length name-string)))
352             (cond
353               (char-code
354                (code-char char-code))
355               ((and (or (= name-length 9)
356                         (= name-length 5))
357                     (char-equal (char name-string 0) #\U)
358                     (loop for i from 1 below name-length
359                           always (digit-char-p (char name-string i) 16)))
360                (code-char (parse-integer name-string :start 1 :radix 16)))
361               (t
362                nil)))))))
363 \f
364 ;;;; predicates
365
366 (defun standard-char-p (char)
367   #!+sb-doc
368   "The argument must be a character object. STANDARD-CHAR-P returns T if the
369 argument is a standard character -- one of the 95 ASCII printing characters or
370 <return>."
371   (and (typep char 'base-char)
372        (let ((n (char-code (the base-char char))))
373          (or (< 31 n 127)
374              (= n 10)))))
375
376 (defun %standard-char-p (thing)
377   #!+sb-doc
378   "Return T if and only if THING is a standard-char. Differs from
379 STANDARD-CHAR-P in that THING doesn't have to be a character."
380   (and (characterp thing) (standard-char-p thing)))
381
382 (defun graphic-char-p (char)
383   #!+sb-doc
384   "The argument must be a character object. GRAPHIC-CHAR-P returns T if the
385 argument is a printing character (space through ~ in ASCII), otherwise returns
386 NIL."
387   (let ((n (char-code char)))
388     (or (< 31 n 127)
389         (< 159 n))))
390
391 (defun alpha-char-p (char)
392   #!+sb-doc
393   "The argument must be a character object. ALPHA-CHAR-P returns T if the
394 argument is an alphabetic character, A-Z or a-z; otherwise NIL."
395   (< (ucd-general-category char) 5))
396
397 (defun upper-case-p (char)
398   #!+sb-doc
399   "The argument must be a character object; UPPER-CASE-P returns T if the
400 argument is an upper-case character, NIL otherwise."
401   (< (ucd-value-0 char) 4))
402
403 (defun lower-case-p (char)
404   #!+sb-doc
405   "The argument must be a character object; LOWER-CASE-P returns T if the
406 argument is a lower-case character, NIL otherwise."
407   (< 3 (ucd-value-0 char) 8))
408
409 (defun both-case-p (char)
410   #!+sb-doc
411   "The argument must be a character object. BOTH-CASE-P returns T if the
412 argument is an alphabetic character and if the character exists in both upper
413 and lower case. For ASCII, this is the same as ALPHA-CHAR-P."
414   (< (ucd-value-0 char) 8))
415
416 (defun digit-char-p (char &optional (radix 10.))
417   #!+sb-doc
418   "If char is a digit in the specified radix, returns the fixnum for which
419 that digit stands, else returns NIL."
420   (let ((m (- (char-code char) 48)))
421     (declare (fixnum m))
422     (cond ((<= radix 10.)
423            ;; Special-case decimal and smaller radices.
424            (if (and (>= m 0) (< m radix))  m  nil))
425           ;; Digits 0 - 9 are used as is, since radix is larger.
426           ((and (>= m 0) (< m 10)) m)
427           ;; Check for upper case A - Z.
428           ((and (>= (setq m (- m 7)) 10) (< m radix)) m)
429           ;; Also check lower case a - z.
430           ((and (>= (setq m (- m 32)) 10) (< m radix)) m)
431           ;; Else, fail.
432           (t (let ((number (ucd-decimal-digit char)))
433                (when (and number (< number radix))
434                  number))))))
435
436 (defun alphanumericp (char)
437   #!+sb-doc
438   "Given a character-object argument, ALPHANUMERICP returns T if the argument
439 is either numeric or alphabetic."
440   (let ((gc (ucd-general-category char)))
441     (or (< gc 5)
442         (= gc 12))))
443
444 (defun char= (character &rest more-characters)
445   #!+sb-doc
446   "Return T if all of the arguments are the same character."
447   (declare (truly-dynamic-extent more-characters))
448   (dolist (c more-characters t)
449     (declare (type character c))
450     (unless (eq c character) (return nil))))
451
452 (defun char/= (character &rest more-characters)
453   #!+sb-doc
454   "Return T if no two of the arguments are the same character."
455   (declare (truly-dynamic-extent more-characters))
456   (do* ((head character (car list))
457         (list more-characters (cdr list)))
458        ((null list) t)
459     (declare (type character head))
460     (dolist (c list)
461       (declare (type character c))
462       (when (eq head c) (return-from char/= nil)))))
463
464 (defun char< (character &rest more-characters)
465   #!+sb-doc
466   "Return T if the arguments are in strictly increasing alphabetic order."
467   (declare (truly-dynamic-extent more-characters))
468   (do* ((c character (car list))
469         (list more-characters (cdr list)))
470        ((null list) t)
471     (unless (< (char-int c)
472                (char-int (car list)))
473       (return nil))))
474
475 (defun char> (character &rest more-characters)
476   #!+sb-doc
477   "Return T if the arguments are in strictly decreasing alphabetic order."
478   (declare (truly-dynamic-extent more-characters))
479   (do* ((c character (car list))
480         (list more-characters (cdr list)))
481        ((null list) t)
482     (unless (> (char-int c)
483                (char-int (car list)))
484       (return nil))))
485
486 (defun char<= (character &rest more-characters)
487   #!+sb-doc
488   "Return T if the arguments are in strictly non-decreasing alphabetic order."
489   (declare (truly-dynamic-extent more-characters))
490   (do* ((c character (car list))
491         (list more-characters (cdr list)))
492        ((null list) t)
493     (unless (<= (char-int c)
494                 (char-int (car list)))
495       (return nil))))
496
497 (defun char>= (character &rest more-characters)
498   #!+sb-doc
499   "Return T if the arguments are in strictly non-increasing alphabetic order."
500   (declare (truly-dynamic-extent more-characters))
501   (do* ((c character (car list))
502         (list more-characters (cdr list)))
503        ((null list) t)
504     (unless (>= (char-int c)
505                 (char-int (car list)))
506       (return nil))))
507
508 ;;; EQUAL-CHAR-CODE is used by the following functions as a version of CHAR-INT
509 ;;;  which loses font, bits, and case info.
510
511 (defmacro equal-char-code (character)
512   (let ((ch (gensym)))
513     `(let ((,ch ,character))
514       (if (= (ucd-value-0 ,ch) 0)
515           (ucd-value-1 ,ch)
516           (char-code ,ch)))))
517
518 (defun two-arg-char-equal (c1 c2)
519   (= (equal-char-code c1) (equal-char-code c2)))
520
521 (defun char-equal (character &rest more-characters)
522   #!+sb-doc
523   "Return T if all of the arguments are the same character.
524 Case is ignored."
525   (declare (truly-dynamic-extent more-characters))
526   (do ((clist more-characters (cdr clist)))
527       ((null clist) t)
528     (unless (two-arg-char-equal (car clist) character)
529       (return nil))))
530
531 (defun two-arg-char-not-equal (c1 c2)
532   (/= (equal-char-code c1) (equal-char-code c2)))
533
534 (defun char-not-equal (character &rest more-characters)
535   #!+sb-doc
536   "Return T if no two of the arguments are the same character.
537 Case is ignored."
538   (declare (truly-dynamic-extent more-characters))
539   (do* ((head character (car list))
540         (list more-characters (cdr list)))
541        ((null list) t)
542     (unless (do* ((l list (cdr l)))
543                  ((null l) t)
544               (if (two-arg-char-equal head (car l))
545                   (return nil)))
546       (return nil))))
547
548 (defun two-arg-char-lessp (c1 c2)
549   (< (equal-char-code c1) (equal-char-code c2)))
550
551 (defun char-lessp (character &rest more-characters)
552   #!+sb-doc
553   "Return T if the arguments are in strictly increasing alphabetic order.
554 Case is ignored."
555   (declare (truly-dynamic-extent more-characters))
556   (do* ((c character (car list))
557         (list more-characters (cdr list)))
558        ((null list) t)
559     (unless (two-arg-char-lessp c (car list))
560       (return nil))))
561
562 (defun two-arg-char-greaterp (c1 c2)
563   (> (equal-char-code c1) (equal-char-code c2)))
564
565 (defun char-greaterp (character &rest more-characters)
566   #!+sb-doc
567   "Return T if the arguments are in strictly decreasing alphabetic order.
568 Case is ignored."
569   (declare (truly-dynamic-extent more-characters))
570   (do* ((c character (car list))
571         (list more-characters (cdr list)))
572        ((null list) t)
573     (unless (two-arg-char-greaterp c (car list))
574       (return nil))))
575
576 (defun two-arg-char-not-greaterp (c1 c2)
577   (<= (equal-char-code c1) (equal-char-code c2)))
578
579 (defun char-not-greaterp (character &rest more-characters)
580   #!+sb-doc
581   "Return T if the arguments are in strictly non-decreasing alphabetic order.
582 Case is ignored."
583   (declare (truly-dynamic-extent more-characters))
584   (do* ((c character (car list))
585         (list more-characters (cdr list)))
586        ((null list) t)
587     (unless (two-arg-char-not-greaterp c (car list))
588       (return nil))))
589
590 (defun two-arg-char-not-lessp (c1 c2)
591   (>= (equal-char-code c1) (equal-char-code c2)))
592
593 (defun char-not-lessp (character &rest more-characters)
594   #!+sb-doc
595   "Return T if the arguments are in strictly non-increasing alphabetic order.
596 Case is ignored."
597   (declare (truly-dynamic-extent more-characters))
598   (do* ((c character (car list))
599         (list more-characters (cdr list)))
600        ((null list) t)
601     (unless (two-arg-char-not-lessp c (car list))
602       (return nil))))
603 \f
604 ;;;; miscellaneous functions
605
606 (defun char-upcase (char)
607   #!+sb-doc
608   "Return CHAR converted to upper-case if that is possible. Don't convert
609 lowercase eszet (U+DF)."
610   (if (< 3 (ucd-value-0 char) 8)
611       (code-char (ucd-value-1 char))
612       char))
613
614 (defun char-downcase (char)
615   #!+sb-doc
616   "Return CHAR converted to lower-case if that is possible."
617   (if (< (ucd-value-0 char) 4)
618       (code-char (ucd-value-1 char))
619       char))
620
621 (defun digit-char (weight &optional (radix 10))
622   #!+sb-doc
623   "All arguments must be integers. Returns a character object that represents
624 a digit of the given weight in the specified radix. Returns NIL if no such
625 character exists."
626   (and (typep weight 'fixnum)
627        (>= weight 0) (< weight radix) (< weight 36)
628        (code-char (if (< weight 10) (+ 48 weight) (+ 55 weight)))))
629 \f
630 (defun char-decomposition-info (char)
631   (aref **character-database** (+ 6 (* 8 (ucd-value-0 char)))))
632
633 (defun char-decomposition (char)
634   (let* ((cp (char-code char))
635          (cp-high (ash cp -8))
636          (decompositions **character-decompositions**)
637          (long-decompositions **character-long-decompositions**)
638          (index (+ #x1100
639                    (ash (aref decompositions cp-high) 10)
640                    (ash (ldb (byte 8 0) cp) 2)))
641          (v0 (aref decompositions index))
642          (v1 (aref decompositions (+ index 1)))
643          (v2 (aref decompositions (+ index 2)))
644          (v3 (aref decompositions (+ index 3)))
645          (length (dpb v0 (byte 8 3) (ldb (byte 3 5) v1)))
646          (entry (dpb (ldb (byte 5 0) v1) (byte 5 16)
647                      (dpb v2 (byte 8 8) v3))))
648     (if (= length 1)
649         (string (code-char entry))
650         (if (<= #xac00 cp #xd7a3)
651             ;; see Unicode 6.2, section 3-12
652             (let* ((sbase #xac00)
653                    (lbase #x1100)
654                    (vbase #x1161)
655                    (tbase #x11a7)
656                    (lcount 19)
657                    (vcount 21)
658                    (tcount 28)
659                    (ncount (* vcount tcount))
660                    (scount (* lcount ncount))
661                    (sindex (- cp sbase))
662                    (lindex (floor sindex ncount))
663                    (vindex (floor (mod sindex ncount) tcount))
664                    (tindex (mod sindex tcount))
665                    (result (make-string length)))
666               (declare (ignore scount))
667               (setf (char result 0) (code-char (+ lbase lindex)))
668               (setf (char result 1) (code-char (+ vbase vindex)))
669               (when (> tindex 0)
670                 (setf (char result 2) (code-char (+ tbase tindex))))
671               result)
672             (let ((result (make-string length))
673                   (e (* 4 entry)))
674               (dotimes (i length result)
675                 (let ((code (dpb (aref long-decompositions (+ e 1))
676                                  (byte 8 16)
677                                  (dpb (aref long-decompositions (+ e 2))
678                                       (byte 8 8)
679                                       (aref long-decompositions (+ e 3))))))
680                   (setf (char result i) (code-char code)))
681                 (incf e 4)))))))
682
683 (defun decompose-char (char)
684   (if (= (char-decomposition-info char) 0)
685       (string char)
686       (char-decomposition char)))
687
688 (defun decompose-string (string &optional (kind :canonical))
689   (declare (type (member :canonical :compatibility) kind))
690   (flet ((canonical (char)
691            (= 1 (char-decomposition-info char)))
692          (compat (char)
693            (/= 0 (char-decomposition-info char))))
694     (let (result
695           (fun (ecase kind
696                  (:canonical #'canonical)
697                  (:compatibility #'compat))))
698       (do* ((start 0 (1+ end))
699             (end (position-if fun string :start start)
700                  (position-if fun string :start start)))
701            ((null end) (push (subseq string start end) result))
702         (unless (= start end)
703           (push (subseq string start end) result))
704         ;; FIXME: this recursive call to DECOMPOSE-STRING is necessary
705         ;; for correctness given our direct encoding of the
706         ;; decomposition data in UnicodeData.txt.  It would, however,
707         ;; be straightforward enough to perform the recursion in table
708         ;; construction, and then have this simply revert to a single
709         ;; lookup.  (Wait for tests to be hooked in, then implement).
710         (push (decompose-string (decompose-char (char string end)) kind)
711               result))
712       (apply 'concatenate 'string (nreverse result)))))
713
714 (defun sort-combiners (string)
715   (let (result (start 0) first-cc first-non-cc)
716     (tagbody
717      again
718        (setf first-cc (position 0 string :key #'ucd-ccc :test #'/= :start start))
719        (when first-cc
720          (setf first-non-cc (position 0 string :key #'ucd-ccc :test #'= :start first-cc)))
721        (push (subseq string start first-cc) result)
722        (when first-cc
723          (push (stable-sort (subseq string first-cc first-non-cc) #'< :key #'ucd-ccc) result))
724        (when first-non-cc
725          (setf start first-non-cc first-cc nil first-non-cc nil)
726          (go again)))
727     (apply 'concatenate 'string (nreverse result))))
728
729 (defun primary-composition (char1 char2)
730   (let ((c1 (char-code char1))
731         (c2 (char-code char2)))
732     (cond
733       ((gethash (dpb (char-code char1) (byte 21 21) (char-code char2))
734                 **character-primary-compositions**))
735       ((and (<= #x1100 c1) (<= c1 #x1112)
736             (<= #x1161 c2) (<= c2 #x1175))
737        (let ((lindex (- c1 #x1100))
738              (vindex (- c2 #x1161)))
739          (code-char (+ #xac00 (* lindex 588) (* vindex 28)))))
740       ((and (<= #xac00 c1) (<= c1 #.(+ #xac00 11171))
741             (<= #x11a8 c2) (<= c2 #x11c2)
742             (= 0 (rem (- c1 #xac00) 28)))
743        (code-char (+ c1 (- c2 #x11a7)))))))
744
745 ;;; This implements a sequence data structure, specialized for
746 ;;; efficient deletion of characters at an index, along with tolerable
747 ;;; random access.  The purpose is to support the canonical
748 ;;; composition algorithm from Unicode, which involves replacing (not
749 ;;; necessarily consecutive) pairs of code points with a single code
750 ;;; point (e.g. [#\e #\combining_acute_accent] with
751 ;;; #\latin_small_letter_e_with_acute).  The data structure is a list
752 ;;; of three-element lists, each denoting a chunk of string data
753 ;;; starting at the first index and ending at the second.
754 ;;;
755 ;;; Actually, the implementation isn't particularly efficient, and
756 ;;; would probably benefit from being rewritten in terms of displaced
757 ;;; arrays, which would substantially reduce copying.
758 ;;;
759 ;;; (also, generic sequences.  *sigh*.)
760 (defun lref (lstring index)
761   (dolist (l lstring)
762     (when (and (<= (first l) index)
763                (< index (second l)))
764       (return (aref (third l) (- index (first l)))))))
765 (defun (setf lref) (newchar lstring index)
766   (dolist (l lstring)
767     (when (and (<= (first l) index)
768                (< index (second l)))
769       (return (setf (aref (third l) (- index (first l))) newchar)))))
770 (defun llength (lstring)
771   (second (first (last lstring))))
772 (defun lstring (lstring)
773   (let ((result (make-string (llength lstring))))
774     (dolist (l lstring result)
775       (replace result (third l) :start1 (first l) :end1 (second l)))))
776 (defun ldelete (lstring index)
777   (do* ((ls lstring (cdr ls))
778         (l (car ls) (car ls))
779         so-fars)
780        ((and (<= (first l) index)
781              (< index (second l)))
782         (append
783          (nreverse so-fars)
784          (cond
785            ((= (first l) index)
786             (list (list (first l) (1- (second l)) (subseq (third l) 1))))
787            ((= index (1- (second l)))
788             (list (list (first l) (1- (second l)) (subseq (third l) 0 (1- (length (third l)))))))
789            (t
790             (list
791              (list (first l) index
792                    (subseq (third l) 0 (- index (first l))))
793              (list index (1- (second l))
794                    (subseq (third l) (1+ (- index (first l))))))))
795          (mapcar (lambda (x) (list (1- (first x)) (1- (second x)) (third x)))
796                  (cdr ls))))
797     (push l so-fars)))
798
799 (defun canonically-compose (string)
800   (labels ()
801     (let* ((result (list (list 0 (length string) string)))
802            (previous-starter-index (position 0 string :key #'ucd-ccc))
803            (i (and previous-starter-index (1+ previous-starter-index))))
804       (when (or (not i) (= i (length string)))
805         (return-from canonically-compose string))
806       (tagbody
807        again
808          (when (and (>= (- i previous-starter-index) 2)
809                     ;; test for Blocked (Unicode 3.11 para. D115)
810                     ;;
811                     ;; (assumes here that string has sorted combiners,
812                     ;; so can look back just one step)
813                     (>= (ucd-ccc (lref result (1- i)))
814                         (ucd-ccc (lref result i))))
815            (when (= (ucd-ccc (lref result i)) 0)
816              (setf previous-starter-index i))
817            (incf i)
818            (go next))
819
820          (let ((comp (primary-composition (lref result previous-starter-index)
821                                           (lref result i))))
822            (cond
823              (comp
824               (setf (lref result previous-starter-index) comp)
825               (setf result (ldelete result i)))
826              (t
827               (when (= (ucd-ccc (lref result i)) 0)
828                 (setf previous-starter-index i))
829               (incf i))))
830        next
831          (unless (= i (llength result))
832            (go again)))
833       (if (= i (length string))
834           string
835           (lstring result)))))
836
837 (defun normalize-string (string &optional (form :nfd))
838   (declare (type (member :nfd :nfkd :nfc :nfkc) form))
839   (etypecase string
840     #!+sb-unicode
841     (base-string string)
842     ((or (array character (*)) #!-sb-unicode base-string)
843      (ecase form
844        ((:nfc)
845         (canonically-compose (sort-combiners (decompose-string string))))
846        ((:nfd)
847         (sort-combiners (decompose-string string)))
848        ((:nfkc)
849         (canonically-compose (sort-combiners (decompose-string string :compatibility))))
850        ((:nfkd)
851         (sort-combiners (decompose-string string :compatibility)))))
852     ((array nil (*)) string)))