elp strings and characters
The definition
string is an immutable sequence of Unicode scalar values with a
guaranteed UTF-8 representation.
char is one Unicode scalar value โ a code point excluding
surrogates, so a char is always validly encodable and a [char] can
always be joined back into a string.
== on string and char is scalar-wise. There is no implicit
normalization.
Both are primitives: lowercase, atmospheric, never imported.
string is Copy, and char is Copy. Ratified in aliasing.md,
and forced by the first sentence above: an immutable value has no second
state to be independent of, so a copy is a pointer copy and a retain and
Duplicate would promise something unobservable. Two things follow that
belong here rather than there โ a + b allocates and walks both operands,
which is where the cost of an immutable string actually is; and a string
may be borrowed inside an @abi(.C, realtime) body but not copied into
one or dropped there, because the release can reach zero and call the
allocator.
Why scalars, and why no normalization
The decisive argument is one the design already made for another
feature. collections.md ratified an insertion-ordered Map because a
compile-time pure fn macro must emit identical code every build
across all three targets, and hash order is not stable across
processes once hashing is seeded.
Grapheme segmentation and NFC normalization tables are both Unicode-version-dependent, and iOS, Android and Web ship different Unicode and ICU versions. So:
- if
charwere a grapheme cluster,"๐จโ๐ฉโ๐งโ๐ฆ".chars().length()could differ between iOS and Android for byte-identical source; - if
==used canonical equivalence,"รฉ" == "e\u{301}"could differ the same way.
Either one puts a target-dependent value inside a construct the language promises is deterministic. This is the determinism requirement arriving a second time, not a new preference.
Three supporting reasons:
- A grapheme cluster is unbounded in length, so it is
heap-allocated.
charwould stop beingCopyand stop being a primitive โ butTextSearchputs it in aMap<char, int>key and binds it withconst, both of which want a fixed-width value. - Scalar values are version-stable. An assigned code point never changes meaning. Grapheme boundaries do, between Unicode releases.
- Swift chose canonical equivalence and pays for it by shipping its
own copy of ICU. elp targets Web, where that payload is the
shipping constraint
dispatch.mdalready flagged for binary size.
The cost, stated plainly
"รฉ" != "e\u{301}". A user typing รฉ on one platform and another
typing it on a second can produce strings that compare unequal, and
nothing in the language will warn them.
That is a real footgun and it is worth naming rather than burying.
And it has a second direction the paragraph above does not cover.
examples/Untrusted found it: that cost is a user typing the same name two
ways, and the adversarial version is a hostile handle chosen to normalize
onto a trusted one. normalized(.NFC) answers that case โ and only that
case, because NFC resolves canonical equivalence and says nothing about
visual confusables, which are distinct scalars under every normal form.
So the rule worth stating, which costs no feature: a scalar-wise == is
the right primitive and the wrong identity test. Comparing identities is a
policy โ normalize, then apply a confusable skeleton, then compare โ and it
belongs in stdlib and then in an application, never in an operator. The
mistake to avoid is treating a normal form as the whole answer. Two
things make it the right trade anyway: it is the same footgun Rust, Go,
Python 3, Java, C# and JavaScript all have โ Swift is the outlier, not
elp โ and it is predictable, which is the property this language
has chosen at every previous fork. Normalization is available, as an
explicit stdlib operation that says it is happening.
Literals
String and char literals are grammar, so they are settled here.
| string | "...", with { expr } interpolation |
char | '...', exactly one scalar value |
| escapes | \\ \" \' \n \r \t \0 \{ \u{...} โ a fixed, closed set |
'ab' and '๐จโ๐ฉโ๐งโ๐ฆ' are errors, and the diagnostic states the rule: a
char is one Unicode scalar value. The second case is the useful one
to get right, because it is the error a user will actually hit and the
message is where they learn what char means.
The single quote was free. It is absent from LexerSymbol and
there is no Char token (crates/lexer/src/tokens.rs), so nothing had
claimed it. elp has no lifetimes, so nothing was going to.
\{ is in the set because interpolation claims the brace: a literal
{ in a string has to be spelled somehow, and an escape is consistent
with the rest of the table rather than inventing a {{ doubling rule
that applies to one character.
No octal escapes, no \x โ it reads as a Unicode escape and is not one
in any language that has it โ and no \a/\v/\f. A closed set means
an unknown escape is an error rather than a silently-dropped backslash.
Interpolation is already designed and unimplemented: the lexer emits
one opaque string token today with escapes passed through raw, and
chunked tokens are the outstanding work (grammar-script-notes.md
gap #9).
What the lexer had already decided
Worth recording as decisions rather than leaving as accidents of implementation, because all three are observable:
lib.rs:14 | Peekable<Chars<'a>> โ source is scanned as scalars |
lib.rs:51 | cursor += c.len_utf8() โ spans are byte offsets |
lib.rs:52 | UnicodeWidthChar::width(c) โ columns are display width |
The compiler needs all three units simultaneously: bytes to slice
source, scalars to scan it, display width to put a caret under the
right column. So "bytes versus scalars versus graphemes" was never a
pick-one โ the only open question was which unit string's public
surface exposes, and the answer above is scalars.
One further shipped decision: identifiers are Unicode XID plus emoji
presentation (lib.rs:64), which is a more permissive alphabet than
most languages allow and should be deliberate rather than incidental.
What this pushes to the stdlib
The language defines what a string and a char are; the methods
are stdlib built on top, and are not language design.
The one consequence worth stating, because it looks like a stdlib
choice and is not: UTF-8 means a scalar offset is not O(1), so
string does not conform to Index and there is no s[i].
.chars() -> [char] is the random-access path.
The corpus validates this without having been asked to. TextSearch
is a Boyer-Moore-Horspool implementation โ the program most likely to
demand string indexing โ and it never indexes a string:
export fn Pattern.find(&self, haystack string) -> Optional<int> {
const text = haystack.chars()
const h = text.length()
...
while j >= 0 && text[offset + j] == self.needle[j] {
needle is [char] and skip is Map<char, int>. Every index, every
length() and every comparison in the algorithm is on an array.
There is no s[i] anywhere in the corpus.
The four string length() calls are all incidental: two are emptiness
tests (code.length() == 0, note.trim().length() == 0) and one is a
bound in path.slice(1, path.length()) that means "strip the leading
slash". Nothing in the corpus needs to know how many units a string
has, which is the usual objection to a non-indexable string and does
not apply here.
So length, slice, isEmpty, trim, split, padEnd and
normalized(.NFC) are stdlib surface, designed with the rest of it.
Migration
Char โ char, five sites, all in TextSearch/search.elp. string,
int, int8 and bool were already lowercase; Char was the only
uppercase primitive. UUID stays uppercase correctly โ it is an
imported stdlib type, not a primitive.
Open
- Multi-line and raw strings. Zero corpus evidence either way. The lexer currently ends a string scan at a newline.
- Is
stringIterable<char>? Leaning yes: forward iteration is O(1) amortised in UTF-8 even though indexing is not, sofor c in scosts nothing the ways[i]would. A stdlib conformance, but forced by the definition above. - Byte access for I/O.
LinkShortenerspeaks HTTP, so bytes exist somewhere. Partly answered:memory-model.mdsettles that contiguous storage isBuffer<T>, so this isBuffer<uint8>rather than[uint8]or a distinctBytestype, ands.bytes()copies. The zero-copy form is a view over the string's own UTF-8, and views are reserved (borrow-shaped, spelledSpan<T>) rather than designed. The integer-width question is still undesigned, souint8is a placeholder for whatever the numeric tower calls it. - Is
charComparable? Scalar ordering is well-defined, so this is cheaply yes, but it should be a stated conformance rather than assumed. - Interpolation's chunked tokens, outstanding in the lexer.