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