Debian Codegraph @

clib/unicode.ml

raw symbols SCIP
1 (************************************************************************)
2 (* * The Rocq Prover / The Rocq Development Team *)
3 (* v * Copyright INRIA, CNRS and contributors *)
4 (* <O___,, * (see version control and CREDITS file for authors & dates) *)
5 (* \VV/ **************************************************************)
6 (* // * This file is distributed under the terms of the *)
7 (* * GNU Lesser General Public License Version 2.1 *)
8 (* * (see LICENSE file for the text of the license) *)
9 (************************************************************************)
10
11 (** Unicode utilities *)
12
13 type status = Letter | IdentPart | Symbol | IdentSep | Separator | Control | Unknown
14
15 (* The following table stores classes of Unicode characters that
16 are used by the lexer. There are 5 different classes so 3 bits
17 are allocated for each character. We encode the masks of 8
18 characters per word, thus using 24 bits over the 31 available
19 bits. (This choice seems to be a good trade-off between speed
20 and space after some benchmarks.) *)
21
22 (* A 256 KiB table, initially filled with zeros. *)
23 let table = Array.make (1 lsl 17) 0
24
25 (* Associate a 2-bit pattern to each status at position [i].
26 Only the 3 lowest bits of [i] are taken into account to
27 define the position of the pattern in the word.
28 Notice that pattern "00" means "undefined". *)
29 let mask i = function
30 | Letter -> 1 lsl ((i land 7) * 3) (* 001 *)
31 | IdentPart -> 2 lsl ((i land 7) * 3) (* 010 *)
32 | Symbol -> 3 lsl ((i land 7) * 3) (* 011 *)
33 | IdentSep -> 4 lsl ((i land 7) * 3) (* 100 *)
34 | Separator -> 5 lsl ((i land 7) * 3) (* 101 *)
35 | Control -> 6 lsl ((i land 7) * 3) (* 110 *)
36 | Unknown -> 0 lsl ((i land 7) * 3) (* 000 *)
37
38 (* Helper to reset 3 bits in a word. *)
39 let reset_mask i =
40 lnot (7 lsl ((i land 7) * 3))
41
42 (* Initialize the lookup table from a list of segments, assigning
43 a status to every character of each segment. The order of these
44 assignments is relevant: it is possible to assign status [s] to
45 a segment [(c1, c2)] and later assign [s'] to [c] even if [c] is
46 between [c1] and [c2]. *)
47 let mk_lookup_table_from_unicode_tables_for status tables =
48 List.iter
49 (List.iter
50 (fun (c1, c2) ->
51 for i = c1 to c2 do
52 table.(i lsr 3) <-
53 (table.(i lsr 3) land (reset_mask i)) lor (mask i status)
54 done))
55 tables
56
57 (* Look up into the table and interpret the found pattern. *)
58 let lookup x =
59 let v = (table.(x lsr 3) lsr ((x land 7) * 3)) land 7 in
60 if v = 1 then Letter
61 else if v = 2 then IdentPart
62 else if v = 3 then Symbol
63 else if v = 4 then IdentSep
64 else if v = 5 then Separator
65 else if v = 6 then Control
66 else Unknown
67
68 (* [classify] discriminates between 5 different kinds of
69 symbols based on the standard unicode classification (extracted from
70 Camomile). *)
71 let classify =
72 let single c = [ (c, c) ] in
73 (* General tables. *)
74 mk_lookup_table_from_unicode_tables_for Symbol
75 [
76 Unicodetable.sk; (* Symbol, modifiers. *)
77 Unicodetable.sm; (* Symbol, maths. *)
78 Unicodetable.sc; (* Symbol, currency. *)
79 Unicodetable.so; (* Symbol, modifier. *)
80 Unicodetable.pd; (* Punctuation, dash. *)
81 Unicodetable.pc; (* Punctuation, connector. *)
82 Unicodetable.pe; (* Punctuation, open. *)
83 Unicodetable.ps; (* Punctution, close. *)
84 Unicodetable.pi; (* Punctuation, initial quote. *)
85 Unicodetable.pf; (* Punctuation, final quote. *)
86 Unicodetable.po; (* Punctuation, other. *)
87 ];
88 mk_lookup_table_from_unicode_tables_for Letter
89 [
90 Unicodetable.lu; (* Letter, uppercase. *)
91 Unicodetable.ll; (* Letter, lowercase. *)
92 Unicodetable.lt; (* Letter, titlecase. *)
93 Unicodetable.lo; (* Letter, others. *)
94 Unicodetable.lm; (* Letter, modifier. *)
95 ];
96 mk_lookup_table_from_unicode_tables_for IdentPart
97 [
98 Unicodetable.nd; (* Number, decimal digits. *)
99 Unicodetable.nl; (* Number, letter. *)
100 Unicodetable.no; (* Number, other. *)
101 Unicodetable.mn; (* Non-spacing marks. *)
102 ];
103
104 (* Exceptions from Number, other. *)
105 mk_lookup_table_from_unicode_tables_for Symbol
106 [
107 [(0x000B2, 0x000B3)]; (* Superscript 2-3. *)
108 single 0x000B9; (* Superscript 1. *)
109 single 0x02070; (* Superscript 0. *)
110 [(0x02074, 0x02079)]; (* Superscript 4-9. *)
111 ];
112 mk_lookup_table_from_unicode_tables_for Separator
113 [
114 Unicodetable.zs; (* Separator, Space. *)
115 Unicodetable.zl; (* Separator, Line. *)
116 Unicodetable.zp; (* Separator, Paragraph. *)
117 ];
118 mk_lookup_table_from_unicode_tables_for Control
119 [
120 Unicodetable.cc; (* Other, Control. *)
121 ];
122 mk_lookup_table_from_unicode_tables_for IdentSep
123 [
124 single 0x005F; (* Underscore. *)
125 single 0x00A0; (* Non breaking space, overrides Sep *)
126 ];
127 mk_lookup_table_from_unicode_tables_for IdentPart
128 [
129 single 0x0027; (* Single quote. *)
130 ];
131 (* Lookup *)
132 lookup
133
134 exception End_of_input
135
136 let utf8_of_unicode n =
137 if n < 128 then
138 String.make 1 (Char.chr n)
139 else
140 let (m,s) = if n < 2048 then (2,192) else if n < 65536 then (3,224) else (4,240) in
141 String.init m (fun i ->
142 let j = (n lsr ((m - 1 - i) * 6)) land 63 in
143 Char.chr (j + if i = 0 then s else 128))
144
145 (* If [s] is some UTF-8 encoded string
146 and [i] is a position of some UTF-8 character within [s]
147 then [next_utf8 s i] returns [(j,n)] where:
148 - [j] indicates the position of the next UTF-8 character
149 - [n] represents the UTF-8 character at index [i] *)
150 let next_utf8 s i =
151 let err () = invalid_arg "utf8" in
152 let l = String.length s - i in
153 if l = 0 then raise End_of_input
154 else let a = Char.code s.[i] in if a <= 0x7F then
155 1, a
156 else if a land 0x40 = 0 || l = 1 then err ()
157 else let b = Char.code s.[i+1] in if b land 0xC0 <> 0x80 then err ()
158 else if a land 0x20 = 0 then
159 2, (a land 0x1F) lsl 6 + (b land 0x3F)
160 else if l = 2 then err ()
161 else let c = Char.code s.[i+2] in if c land 0xC0 <> 0x80 then err ()
162 else if a land 0x10 = 0 then
163 3, (a land 0x0F) lsl 12 + (b land 0x3F) lsl 6 + (c land 0x3F)
164 else if l = 3 then err ()
165 else let d = Char.code s.[i+3] in if d land 0xC0 <> 0x80 then err ()
166 else if a land 0x08 = 0 then
167 4, (a land 0x07) lsl 18 + (b land 0x3F) lsl 12 +
168 (c land 0x3F) lsl 6 + (d land 0x3F)
169 else err ()
170
171 let is_utf8 s =
172 let rec check i =
173 let (off, _) = next_utf8 s i in
174 check (i + off)
175 in
176 try check 0 with End_of_input -> true | Invalid_argument _ -> false
177
178 (* Escape string if it contains non-utf8 characters *)
179
180 let escaped_non_utf8 s =
181 let mk_escape x = Printf.sprintf "%%%X" x in
182 let buff = Buffer.create (String.length s * 3) in
183 let rec process_trailing_aux i j =
184 if i = j then i else
185 match String.unsafe_get s i with
186 | '\128'..'\191' -> process_trailing_aux (i+1) j
187 | _ -> i in
188 let process_trailing i n =
189 let j = if i+n-1 >= String.length s then i+1 else process_trailing_aux (i+1) (i+n) in
190 (if j = i+n then
191 Buffer.add_string buff (String.sub s i n)
192 else
193 let v = Array.init (j-i) (fun k -> mk_escape (Char.code s.[i+k])) in
194 Buffer.add_string buff (String.concat "" (Array.to_list v)));
195 j in
196 let rec process i =
197 if i >= String.length s then Buffer.contents buff else
198 let c = String.unsafe_get s i in
199 match c with
200 | '\000'..'\127' -> Buffer.add_char buff c; process (i+1)
201 | '\128'..'\191' | '\248'..'\255' -> Buffer.add_string buff (mk_escape (Char.code c)); process (i+1)
202 | '\192'..'\223' -> process (process_trailing i 2)
203 | '\224'..'\239' -> process (process_trailing i 3)
204 | '\240'..'\247' -> process (process_trailing i 4)
205 in
206 process 0
207
208 let escaped_if_non_utf8 s =
209 if is_utf8 s then s else escaped_non_utf8 s
210
211 (* Check the well-formedness of an identifier *)
212
213 let is_valid_ident_initial = function
214 | Letter | IdentSep -> true
215 | IdentPart | Symbol | Separator | Control | Unknown -> false
216
217 let initial_refutation j n s =
218 if is_valid_ident_initial (classify n) then None
219 else
220 let c = String.sub s 0 j in
221 Some (false,
222 "Invalid character '"^c^"' at beginning of identifier \""^s^"\".")
223
224 let is_valid_ident_trailing = function
225 | Letter | IdentSep | IdentPart -> true
226 | Symbol | Separator | Control | Unknown -> false
227
228 let trailing_refutation i j n s =
229 if is_valid_ident_trailing (classify n) then None
230 else
231 let c = String.sub s i j in
232 Some (false,
233 "Invalid character '"^c^"' in identifier \""^s^"\".")
234
235 let is_unknown = function
236 | Unknown -> true
237 | Letter | IdentSep | IdentPart | Symbol | Separator | Control -> false
238
239 let is_ident_part = function
240 | IdentPart -> true
241 | Letter | IdentSep | Symbol | Unknown | Separator | Control -> false
242
243 let is_ident_sep = function
244 | IdentSep -> true
245 | Letter | IdentPart | Symbol | Unknown | Separator | Control -> false
246
247 let is_letter = function
248 | Letter -> true
249 | IdentSep | IdentPart | Symbol | Unknown | Separator | Control -> false
250
251 let ident_refutation s =
252 if s = ".." then None else try
253 let j, n = next_utf8 s 0 in
254 match initial_refutation j n s with
255 |None ->
256 begin try
257 let rec aux i =
258 let j, n = next_utf8 s i in
259 match trailing_refutation i j n s with
260 |None -> aux (i + j)
261 |x -> x
262 in aux j
263 with End_of_input -> None
264 end
265 |x -> x
266 with
267 | End_of_input -> Some (true,"The empty string is not an identifier.")
268 | Invalid_argument _ -> Some (true,escaped_non_utf8 s^": invalid utf8 sequence.")
269
270 let lowercase_unicode =
271 let tree = Segmenttree.make Unicodetable.to_lower in
272 fun unicode ->
273 try
274 match Segmenttree.lookup unicode tree with
275 | `Abs c -> c
276 | `Delta d -> unicode + d
277 with Not_found -> unicode
278
279 let lowercase_first_char s =
280 assert (s <> "");
281 let j, n = next_utf8 s 0 in
282 utf8_of_unicode (lowercase_unicode n)
283
284 let split_at_first_letter s =
285 let n, v = next_utf8 s 0 in
286 if ((* optim *) n = 1 && s.[0] != '_') || not (is_ident_sep (classify v)) then None
287 else begin
288 let n = ref n in
289 let p = ref 0 in
290 while !n < String.length s &&
291 let n', v = next_utf8 s !n in
292 p := n';
293 (* Test if not letter *)
294 ((* optim *) n' = 1 && (s.[!n] = '_' || s.[!n] = '\''))
295 || let st = classify v in
296 is_ident_sep st || is_ident_part st
297 do n := !n + !p
298 done;
299 let s1 = String.sub s 0 !n in
300 let s2 = String.sub s !n (String.length s - !n) in
301 Some (s1,s2)
302 end
303
304 (** For extraction, we need to encode unicode character into ascii ones *)
305
306 let is_basic_ascii s =
307 let ok = ref true in
308 String.iter (fun c -> if Char.code c >= 128 then ok := false) s;
309 !ok
310
311 let ascii_of_ident s =
312 let len = String.length s in
313 let has_UU i =
314 i+2 < len && s.[i]='_' && s.[i+1]='U' && s.[i+2]='U'
315 in
316 let i = ref 0 in
317 while !i < len && Char.code s.[!i] < 128 && not (has_UU !i) do
318 incr i
319 done;
320 if !i = len then s else
321 let out = Buffer.create (2*len) in
322 Buffer.add_substring out s 0 !i;
323 while !i < len do
324 let j, n = next_utf8 s !i in
325 if n >= 128 then
326 (Printf.bprintf out "_UU%04x_" n; i := !i + j)
327 else if has_UU !i then
328 (Buffer.add_string out "_UUU"; i := !i + 3)
329 else
330 (Buffer.add_char out s.[!i]; incr i)
331 done;
332 Buffer.contents out
333
334 (* Compute length of an UTF-8 encoded string
335 Rem 1 : utf8_length <= String.length (equal if pure ascii)
336 Rem 2 : if used for an iso8859_1 encoded string, the result is
337 wrong in very rare cases. Such a wrong case corresponds to any
338 sequence of a character in range 192..253 immediately followed by a
339 character in range 128..191 (typical case in french is "déçu" which
340 is counted 3 instead of 4); then no real harm to use always
341 utf8_length even if using an iso8859_1 encoding *)
342
343 (** FIXME: duplicate code with Pp *)
344
345 let utf8_length s =
346 let len = String.length s
347 and cnt = ref 0
348 and nc = ref 0
349 and p = ref 0 in
350 while !p < len do
351 begin
352 match s.[!p] with
353 | '\000'..'\127' -> nc := 0 (* ascii char *)
354 | '\128'..'\191' -> nc := 0 (* cannot start with a continuation byte *)
355 | '\192'..'\223' -> nc := 1 (* expect 1 continuation byte *)
356 | '\224'..'\239' -> nc := 2 (* expect 2 continuation bytes *)
357 | '\240'..'\247' -> nc := 3 (* expect 3 continuation bytes *)
358 | '\248'..'\255' -> nc := 0 (* invalid byte *)
359 end ;
360 incr p ;
361 while !p < len && !nc > 0 do
362 match s.[!p] with
363 | '\128'..'\191' (* next continuation byte *) -> incr p ; decr nc
364 | _ (* not a continuation byte *) -> nc := 0
365 done ;
366 incr cnt
367 done ;
368 !cnt
369
370 (* Variant of String.sub for UTF8 character positions *)
371 let utf8_sub s start_u len_u =
372 let len_b = String.length s
373 and end_u = start_u + len_u
374 and cnt = ref 0
375 and nc = ref 0
376 and p = ref 0 in
377 let start_b = ref len_b in
378 while !p < len_b && !cnt < end_u do
379 if !cnt <= start_u then start_b := !p ;
380 begin
381 match s.[!p] with
382 | '\000'..'\127' -> nc := 0 (* ascii char *)
383 | '\128'..'\191' -> nc := 0 (* cannot start with a continuation byte *)
384 | '\192'..'\223' -> nc := 1 (* expect 1 continuation byte *)
385 | '\224'..'\239' -> nc := 2 (* expect 2 continuation bytes *)
386 | '\240'..'\247' -> nc := 3 (* expect 3 continuation bytes *)
387 | '\248'..'\255' -> nc := 0 (* invalid byte *)
388 end ;
389 incr p ;
390 while !p < len_b && !nc > 0 do
391 match s.[!p] with
392 | '\128'..'\191' (* next continuation byte *) -> incr p ; decr nc
393 | _ (* not a continuation byte *) -> nc := 0
394 done ;
395 incr cnt
396 done ;
397 let end_b = !p in
398 String.sub s !start_b (end_b - !start_b)