1-- The parser-support text layer is deliberately byte-oriented. D181--D184
2-- add the hosted text identities, literals, indexing, direct ranges and
3-- scalar traversal without changing this module's opaque positions or
4-- bounded byte views.
5-- D182 also accepts this exact public position identity for O(1) utf8
6-- indexing; a position used that way must begin a codepoint.
7
8import core/cmp
9import core/mem
10
11position_value: type = struct
12 offset: usize
13end position_value
14
15--- Opaque byte offset for scanning. It does not retain or validate a source;
16--- when used to index UTF-8 it must identify a codepoint boundary.
17public position: type = position_value
18--- The supplied bytes are not well-formed UTF-8.
19public invalid_text: atom
20--- The bytes are empty or are not the digits the parse reads: a byte
21--- other than a digit, a sign where none is read, or a `-` without digits.
22public invalid_number: atom
23--- The parsed value is outside the type it is parsed into: above its
24--- maximum, or for a signed type below its minimum.
25public number_overflow: atom
26--- The value is not a Unicode scalar: it is a surrogate, U+D800 to U+DFFF,
27--- or above U+10FFFF, and so has no UTF-8 encoding.
28public invalid_scalar: atom
29
30byte_view: type = []u8
31
32--- The zero-offset position sentinel. It has the same offset as `first`; it
33--- is not a separate invalid-position tag.
34public nowhere: position = (offset: 0)
35
36--- Return a cursor at byte offset zero, including for an empty source.
37public first: (source: []u8) -> (result: position) =
38 _ = source
39 result = (offset: 0)
40end first
41
42--- Return whether the byte offset is at or beyond the source length.
43public at_end: (source: []u8, cursor: position) -> (yes: bool) =
44 yes = cursor.offset >= lenof source
45end at_end
46
47--- Return the byte offset stored in a position. Index `utf8` with the
48--- position itself: a `usize` index into `utf8` counts scalars, not bytes.
49public offset: (cursor: position) -> (bytes: usize) =
50 bytes = cursor.offset
51end offset
52
53--- Copy a position out of aggregate storage without borrowing that storage.
54--- This matters to scanners that retain the token start while advancing the
55--- cursor field from which it was read.
56public copied: (cursor: position) -> (result: position) =
57 result = (offset: cursor.offset)
58end copied
59
60--- Construct a position at a byte offset into `source`. Does not check bounds
61--- or UTF-8 boundaries; later operations enforce their own requirements. The
62--- source names the coordinate space, although the position stores only the
63--- offset.
64public from_offset: (source: []u8, offset: usize) -> (result: position) =
65 _ = source
66 result = (offset: offset)
67end from_offset
68
69--- Return a cursor one byte later. This is byte traversal, not Unicode-scalar
70--- traversal; offset overflow follows ordinary checked arithmetic.
71public next: (cursor: position) -> (result: position) =
72 result = (offset: cursor.offset + 1)
73end next
74
75--- Advance the cursor by one byte in place. Does not validate the source or
76--- skip a whole UTF-8 scalar.
77public advance: (inout cursor: position) -> none =
78 inc cursor.offset
79end advance
80
81--- Read one source byte at the cursor. Reports `mem.out_of_bounds` before
82--- reading outside the source.
83public byte: (source: []u8, cursor: position)
84 -> (value: u8) ! mem.out_of_bounds =
85 fail mem.out_of_bounds when at_end(source, cursor)
86 value = source[cursor.offset]
87end byte
88
89--- Lend bytes between two cursor offsets, with an exclusive end. Requires an
90--- ordered interval within the source; invalid ranges follow the language's
91--- checked range behavior.
92public slice: (source: []u8, begins: position, ends: position)
93 -> (result: []u8 from source) =
94 result = source[begins.offset..<ends.offset]
95end slice
96
97--- Report whether the bytes are well-formed UTF-8: shortest-form encodings
98--- of Unicode scalars, with no surrogate and nothing above U+10FFFF. This is
99--- the check `from_bytes` makes; the `utf8(bytes)` conversion makes it too
100--- but traps instead of reporting.
101public valid: (source: []u8) -> (yes: bool) =
102 mut cursor: usize = 0
103 while cursor < lenof source do
104 lead: u8 = source[cursor]
105 if lead < 128 then
106 cursor += 1
107 elsif lead < 194 then
108 yes = false
109 return
110 elsif lead < 224 then
111 if lenof source - cursor < 2 then
112 yes = false
113 return
114 end if
115 second: u8 = source[cursor + 1]
116 if second < 128 or second > 191 then
117 yes = false
118 return
119 end if
120 cursor += 2
121 elsif lead < 240 then
122 if lenof source - cursor < 3 then
123 yes = false
124 return
125 end if
126 second: u8 = source[cursor + 1]
127 third: u8 = source[cursor + 2]
128 if second < 128 or second > 191
129 or third < 128 or third > 191
130 then
131 yes = false
132 return
133 end if
134 if lead == 224 and second < 160 then
135 yes = false
136 return
137 end if
138 if lead == 237 and second > 159 then
139 yes = false
140 return
141 end if
142 cursor += 3
143 elsif lead <= 244 then
144 if lenof source - cursor < 4 then
145 yes = false
146 return
147 end if
148 second: u8 = source[cursor + 1]
149 third: u8 = source[cursor + 2]
150 fourth: u8 = source[cursor + 3]
151 if second < 128 or second > 191
152 or third < 128 or third > 191
153 or fourth < 128 or fourth > 191
154 then
155 yes = false
156 return
157 end if
158 if lead == 240 and second < 144 then
159 yes = false
160 return
161 end if
162 if lead == 244 and second > 143 then
163 yes = false
164 return
165 end if
166 cursor += 4
167 else
168 yes = false
169 return
170 end if
171 end while
172 yes = true
173end valid
174
175-- The checked adapters report foreign or file-data defects before the
176-- view establishes utf8's invariant, which `valid` has then checked once.
177-- Their result is a source-derived view; no allocation, copy or canonical
178-- empty carrier is introduced.
179--- Validate a byte slice and lend it as UTF-8. Reports `invalid_text` when
180--- the bytes are not well-formed UTF-8; the `utf8(bytes)` conversion traps
181--- on them instead.
182---
183--- The result is a view of `source`: nothing is allocated or copied.
184--- The caller keeps the bytes alive and valid for as long as the view
185--- is used.
186public from_bytes: (source: []u8)
187 -> (result: utf8 from source) ! invalid_text =
188 fail invalid_text when not valid(source)
189 unchecked begin
190 -- `valid` has just read every byte, so they are not read again
191 -- (D949).
192 result = compiler.utf8_unvalidated(source)
193 end unchecked
194end from_bytes
195
196--- Validate a terminated C string and lend it as UTF-8. The pointer must
197--- remain readable through its terminator; invalid UTF-8 reports
198--- `invalid_text`.
199public from_c: (source: cstring)
200 -> (result: utf8 from source) ! invalid_text =
201 raw: []u8 = byte_view(source)
202 result = try from_bytes(raw)
203end from_c
204
205--- Lend the encoded bytes of a UTF-8 view without copying or allocating.
206public bytes: (source: utf8) -> (result: []u8 from source) =
207 result = byte_view(source)
208end bytes
209
210-- A host string's representation. Every system this compiler targets
211-- names files and passes arguments as bytes, so it is the bytes. A
212-- system that names them in 16-bit units, as Windows does, fixes its own
213-- representation here under `fixed if compiler.os`, and the operations
214-- below keep their meaning over it.
215os_string_value: type = struct
216 bytes: []u8
217end os_string_value
218
219--- A host string: a path, a process argument or a directory entry's name,
220--- in the representation its system gives and takes, and not converted on
221--- the way through. On Linux, Darwin and FreeBSD it is bytes, which need
222--- not be UTF-8. `from_os_string` is the checked conversion to `utf8`,
223--- `os_string_bytes` the conversion to bytes, and `os_string_equal` compares
224--- one with a literal. It lends what it was made from: an argument lends the
225--- process's storage, an entry its directory's buffer, and `os_string_over`
226--- the caller's bytes. A NUL cannot be in a path or an argument, and the
227--- system refuses one when it is given a host string holding one.
228public os_string: type = os_string_value
229
230--- A host string over the caller's bytes, which it lends. Any bytes are
231--- one; the system says whether it accepts them when it is given them.
232--- A literal path is `text.os_string_over("input.txt")`.
233public os_string_over: (source: []u8) -> (result: os_string from source) =
234 result = (bytes: source)
235end os_string_over
236
237--- The host string's bytes, as the system gave them, lent. Nothing is
238--- validated or copied.
239public os_string_bytes: (source: os_string) -> (result: []u8 from source) =
240 result = source.bytes
241end os_string_bytes
242
243--- One environment variable: its name and its value, host strings as the
244--- system keeps them. `core/io`'s environments lend it, and
245--- `platform/posix` reads and passes it, which is why it is declared here,
246--- below both (D1951).
247public os_variable: type = struct
248 name: os_string
249 value: os_string
250end os_variable
251
252--- The host string as UTF-8 text, lent: the checked conversion, which
253--- reports `invalid_text` when its bytes are not UTF-8, as `from_bytes`
254--- does. A host string that is not text is still a working path or
255--- argument; it is only not `utf8`.
256public from_os_string: (source: os_string)
257 -> (result: utf8 from source) ! invalid_text =
258 result = try from_bytes(source.bytes)
259end from_os_string
260
261--- Whether the host string spells exactly the text `literal`, compared as
262--- the system stores it, with no normalization: `--verbose` against an
263--- argument, for one.
264public os_string_equal: (value: os_string, literal: utf8) -> (yes: bool) =
265 have: []u8 = value.bytes
266 wanted: []u8 = bytes(literal)
267 yes = false
268 return when lenof have <> lenof wanted
269 mut index: usize = 0
270 while index < lenof wanted do
271 return when have[index] <> wanted[index]
272 inc index
273 end while
274 yes = true
275end os_string_equal
276
277--- Compare UTF-8 values by their encoded bytes. Does not normalize Unicode
278--- spelling.
279---
280--- Equality and containment are exact encoded-byte operations. Valid UTF-8
281--- has one shortest-form encoding per scalar sequence, so neither operation
282--- needs normalization or locale authority.
283public equal: (left: utf8, right: utf8) -> (yes: bool) =
284 left_bytes: []u8 = bytes(left)
285 right_bytes: []u8 = bytes(right)
286 if lenof left_bytes <> lenof right_bytes then
287 yes = false
288 return
289 end if
290 mut index: usize = 0
291 while index < lenof left_bytes do
292 if left_bytes[index] <> right_bytes[index] then
293 yes = false
294 return
295 end if
296 inc index
297 end while
298 yes = true
299end equal
300
301--- Test whether the sought UTF-8 byte sequence occurs in the source. Empty
302--- text matches; no normalization or allocation is performed.
303---
304--- Two-Way search uses a critical split of the sought bytes. Its two
305--- lexicographic passes and the search each take linear time; only scalar
306--- counters are kept, so neither a table nor a caller allocator is needed.
307public contains: (source: utf8, sought: utf8) -> (yes: bool) =
308 source_bytes: []u8 = bytes(source)
309 sought_bytes: []u8 = bytes(sought)
310 if lenof sought_bytes == 0 then
311 yes = true
312 return
313 end if
314 if lenof sought_bytes > lenof source_bytes then
315 yes = false
316 return
317 end if
318 yes = first_match(source_bytes, sought_bytes) < lenof source_bytes
319end contains
320
321-- Where `sought_bytes`, nonempty and no longer than `source_bytes`, first
322-- occurs there, or the length of `source_bytes` when it does not occur:
323-- `contains`'s Two-Way search, which every `find` shares.
324first_match: (source_bytes: []u8, sought_bytes: []u8) -> (found: usize) =
325 sought_length: usize = lenof sought_bytes
326 mut cut: usize = 0
327 mut period: usize = 1
328 mut pass: usize = 0
329 while pass < 2 do
330 mut maximum: usize = 0
331 mut candidate: usize = 1
332 mut matched: usize = 0
333 mut local_period: usize = 1
334 while candidate < sought_length
335 and matched < sought_length - candidate
336 do
337 current: u8 = sought_bytes[candidate + matched]
338 best: u8 = sought_bytes[maximum + matched]
339 if (pass == 0 and current < best)
340 or (pass == 1 and best < current)
341 then
342 candidate += matched + 1
343 matched = 0
344 local_period = candidate - maximum
345 elsif current == best then
346 if matched + 1 == local_period then
347 candidate += local_period
348 matched = 0
349 else
350 inc matched
351 end if
352 else
353 maximum = candidate
354 inc candidate
355 matched = 0
356 local_period = 1
357 end if
358 end while
359 if pass == 0 or maximum >= cut then
360 cut = maximum
361 period = local_period
362 end if
363 inc pass
364 end while
365
366 -- A period of the right half is a period of the whole sought value
367 -- precisely when the left half agrees with its shifted copy.
368 mut periodic: bool = cut <= sought_length - period
369 mut offset: usize = 0
370 while periodic and offset < cut do
371 if sought_bytes[offset] <> sought_bytes[offset + period] then
372 periodic = false
373 end if
374 inc offset
375 end while
376 if not periodic then
377 if cut > sought_length - cut then
378 period = cut + 1
379 else
380 period = sought_length - cut + 1
381 end if
382 end if
383
384 mut start: usize = 0
385 mut memory: usize = 0
386 last: usize = lenof source_bytes - sought_length
387 while start <= last do
388 mut index: usize = cut
389 if periodic and memory > index then
390 index = memory
391 end if
392 while index < sought_length
393 and sought_bytes[index] == source_bytes[start + index]
394 do
395 inc index
396 end while
397 if index < sought_length then
398 start += index - cut + 1
399 memory = 0
400 else
401 index = memory
402 while index < cut
403 and sought_bytes[index] == source_bytes[start + index]
404 do
405 inc index
406 end while
407 if index >= cut then
408 found = start
409 return
410 end if
411 start += period
412 if periodic then
413 memory = sought_length - period
414 end if
415 end if
416 end while
417 found = lenof source_bytes
418end first_match
419
420-- Positions over `utf8` step a whole scalar at a time. The byte cursors
421-- above, `first`, `at_end` and `next`, take bytes and step one byte; these
422-- take the text, and read the scalar at a position as `source[at]` does,
423-- so they trap where it traps, at the end and on a continuation byte
424-- (D182, D249). Every position they and the searches return is a
425-- scalar's start or the end, which is what `source[at]` and D183's
426-- `source[a..<b]` need of an offset.
427
428--- The position of the first scalar of `source`, or of its end when it is
429--- empty: byte offset zero. Step through the text with `step` until
430--- `utf8_at_end`, reading each scalar as `source[at]`.
431public start: (source: utf8) -> (at: position) =
432 _ = source
433 at = (offset: 0)
434end start
435
436--- Whether no scalar begins at `at`: it is at the end of `source`, or past
437--- it.
438public utf8_at_end: (source: utf8, at: position) -> (yes: bool) =
439 yes = at.offset >= lenof source
440end utf8_at_end
441
442--- How many bytes, one to four, encode the scalar at `at`. Traps at the
443--- end and on a continuation byte, as `source[at]` does.
444public scalar_length: (source: utf8, at: position) -> (count: usize) =
445 count = encoded_width(source[at])
446end scalar_length
447
448--- The position just past the scalar at `at`: the next scalar's, or the
449--- end. Traps where `scalar_length` does, so it never steps into a
450--- scalar.
451public step: (source: utf8, at: position) -> (after: position) =
452 after = (offset: at.offset + scalar_length(source, at))
453end step
454
455--- The position where `sought` first occurs in `source`, or `mem.not_found`.
456--- Empty text is found at the start, as `contains` finds it. The match
457--- begins and ends on scalar boundaries, so `source[text.offset(found)..<
458--- text.offset(found) + lenof sought]` is the match and the parts either
459--- side of it are text too, each a view of `source` with nothing copied.
460public find: (source: utf8, sought: utf8)
461 -> (found: position) ! mem.not_found =
462 found = try find_from(source, sought, start(source))
463end find
464
465--- The position where `sought` first occurs in `source` at or after `at`,
466--- or `mem.not_found`: the match after one `find` returned is found from the
467--- position past it. Empty text is found at `at`. A position inside a
468--- scalar or past the end traps, as a range of `source` from it does.
469--- `contains`'s Two-Way search, in time linear in the two lengths and
470--- with no table.
471public find_from: (source: utf8, sought: utf8, at: position)
472 -> (found: position) ! mem.not_found =
473 found = try found_from(source, bytes(sought), at)
474end find_from
475
476--- The position of the first scalar of `source` equal to `scalar`, or
477--- `mem.not_found`, which a surrogate or a value above U+10FFFF always is,
478--- since no text holds one.
479public find_scalar: (source: utf8, scalar: u32) -> (found: position)
480 ! mem.not_found =
481 found = try find_scalar_from(source, scalar, start(source))
482end find_scalar
483
484--- The position of the first scalar of `source` equal to `scalar` at or
485--- after `at`, or `mem.not_found`. A position inside a scalar or past the end
486--- traps, as `find_from`'s does.
487public find_scalar_from: (source: utf8, scalar: u32, at: position)
488 -> (found: position) ! mem.not_found =
489 count: usize = encoded_width(scalar)
490 fail mem.not_found when count == 0
491 mut encoded: [4]u8 = zeroed
492 stored(scalar, count, encoded[0..<count])
493 found = try found_from(source, encoded[0..<count], at)
494end find_scalar_from
495
496-- Where `sought_bytes`, the encoding of whole scalars, first occurs in
497-- `source` at or after `at`. A leading byte is never a continuation
498-- byte, so a match begins and ends on scalars of the text.
499found_from: (source: utf8, sought_bytes: []u8, at: position)
500 -> (found: position) ! mem.not_found =
501 rest: []u8 = bytes(source[at.offset..<lenof source])
502 fail mem.not_found when lenof sought_bytes > lenof rest
503 found = (offset: at.offset)
504 return when lenof sought_bytes == 0
505 index: usize = first_match(rest, sought_bytes)
506 fail mem.not_found when index == lenof rest
507 found = (offset: at.offset + index)
508end found_from
509
510-- The bytes UTF-8 takes for `scalar`, one to four, or zero when it is a
511-- surrogate or above U+10FFFF and so no scalar.
512encoded_width: (scalar: u32) -> (count: usize) =
513 count = if scalar < 0x80 then
514 1
515 elsif scalar < 0x800 then
516 2
517 elsif scalar >= 0xd800 and scalar <= 0xdfff then
518 0
519 elsif scalar < 0x10000 then
520 3
521 elsif scalar <= 0x10ffff then
522 4
523 else
524 0
525 end if
526end encoded_width
527
528-- Write the `count` bytes encoding `scalar` into `into`, which is exactly
529-- that long: the continuation bytes from the last, six bits each, then
530-- the leading byte with what is left.
531stored: (scalar: u32, count: usize, into: []mut u8) -> none =
532 mut remaining: u32 = scalar
533 mut at: usize = count
534 while at > 1 do
535 dec at
536 into[at] = u8(remaining & 63) | 128
537 remaining = remaining >> 6
538 end while
539 lead: u32 = if count == 1 then
540 0
541 elsif count == 2 then
542 192
543 elsif count == 3 then
544 224
545 else
546 240
547 end if
548 into[0] = u8(remaining | lead)
549end stored
550
551--- Encode `scalar` as UTF-8 at the front of `into` and say how many bytes,
552--- one to four, it took; encode at an offset by passing what follows it,
553--- `buffer[at..<lenof buffer]`. A surrogate, U+D800 to U+DFFF, or a value
554--- above U+10FFFF reports `invalid_scalar`, before a scalar whose bytes do
555--- not fit reports `mem.out_of_memory`; either refusal writes nothing, so
556--- `into` is as it was. The builders' `append_scalar` and
557--- `utf8_append_scalar` write the same bytes.
558public encode: (scalar: u32, into: []mut u8)
559 -> (count: usize) ! invalid_scalar | mem.out_of_memory =
560 count = encoded_width(scalar)
561 fail invalid_scalar when count == 0
562 fail mem.out_of_memory when count > lenof into
563 stored(scalar, count, into[0..<count])
564end encode
565
566--- Hash UTF-8 encoded bytes keyed by `seed`, consistently with `equal`
567--- and the byte-slice hash. No Unicode normalization or cryptographic
568--- guarantee is provided.
569---
570--- utf8 is a map key and sortable as it stands: equality, hash and order
571--- are over the encoded bytes, which valid UTF-8 makes unique per scalar
572--- sequence. The hash is `cmp.hash_bytes` of those bytes, SipHash-1-3.
573public hash: (value: utf8, seed: cmp.hash_seed) -> (result: u64) =
574 result = cmp.hash_bytes(bytes(value), seed)
575end hash
576
577--- Order UTF-8 values by their encoded bytes, lexicographically, with a
578--- shorter equal prefix sorting first.
579---
580--- For valid UTF-8 this is scalar order. It is not locale-aware collation.
581public less: (left: utf8, right: utf8) -> (yes: bool) =
582 left_bytes: []u8 = bytes(left)
583 right_bytes: []u8 = bytes(right)
584 mut index: usize = 0
585 while index < lenof left_bytes and index < lenof right_bytes do
586 if left_bytes[index] <> right_bytes[index] then
587 yes = left_bytes[index] < right_bytes[index]
588 return
589 end if
590 inc index
591 end while
592 yes = lenof left_bytes < lenof right_bytes
593end less
594
595utf8 is cmp.equatable (equal: equal)
596utf8 is cmp.hashable (hash: hash)
597utf8 is cmp.ordered (less: less)