r/ProgrammingLanguages • u/MarcoServetto • Apr 12 '26
Requesting criticism Why Unicode strings are difficult to work with and API design
Why Unicode strings are difficult to work with
A simple goal
This text is part of my attempts to design the standard library API for unicode strings in my new language.
Suppose we want to implement:
removePrefixIfPresent(text,prefix):Text
The intended behavior sounds simple:
- if
textstarts withprefix, remove that prefix - otherwise, return
textunchanged
In Unicode, the deeper difficulty is that the logical behavior itself is not uniquely determined.
What exactly does it mean for one string to be a prefix of another?
And once we say "yes, it is a prefix", what exact part of the original source text should be removed?
The easy cases
Case 1/2
text = "banana"
prefix = "ban"
result = "ana"
text = "banana"
prefix = "bar"
result = "banana"
These examples encourage a very naive mental model:
- a string is a sequence of characters
- prefix checking is done left to right
- if the first characters match, remove them
Unicode breaks this model in several different ways.
First source of difficulty: the same visible text can have different internal representations
A very common example is:
- precomposed form: one code point for "e with acute"
- decomposed form:
efollowed by a combining acute mark
Let us name them:
E1 = [U+00E9] // precomposed e-acute
E2 = [U+0065, U+0301] // e + combining acute
Those are conceptually "the same text". Now let us consider all four combinations.
Case 3A: neither side expanded
text = [U+00E9, U+0078] // E1 + x
prefix = [U+00E9] // E1
result = [U+0078]
Case 3B: both sides expanded
text = [U+0065, U+0301, U+0078] // E2 + x
prefix = [U+0065, U+0301] // E2
result = [U+0078]
Case 3C: text expanded, prefix not expanded
text = [U+0065, U+0301, U+0078] // E2 + x
prefix = [U+00E9] // E1
result = [U+0078] // do we want this
result = [U+0065, U+0301, U+0078] // or this?
exact-source semantics or canonical-equivalent semantics?
Case 3D: text not expanded, prefix expanded
text = [U+00E9, U+0078] // E1 + x
prefix = [U+0065, U+0301] // E2
result = [U+0078] // do we want this
result = [U+00E9, U+0078] // or this?
Overall, exact-source semantics is easy but bad. Normalization-aware semantics instead is both hard and bad.
Still, the examples above are relatively tame, because the match consumes one visible "thing" on each side.
The next cases are worse.
Extra source of difficulty: plain e as prefix, "e-acute" in the text
This is interesting because now two different issues get mixed together:
- equivalence: does plain
ecount as matching accentede? - cut boundaries: if the text uses the decomposed form, are we allowed to remove only the first code point and leave the combining mark behind?
Let us name the three pieces:
E1 = [U+00E9] // precomposed e-acute
E2 = [U+0065, U+0301] // e + combining acute
E0 = [U+0065] // plain e
Case 3E: text uses the decomposed accented form
text = [U+0065, U+0301, U+0078] // E2 + x
prefix = [U+0065] // E0
result = [U+0301, U+0078] // do we want this (leave pending accent)
result = [U+0065, U+0301, U+0078] // or this? (no removal)
Case 3F: text uses the single-code-point accented form
text = [U+00E9, U+0078] // E1 + x
prefix = [U+0065] // E0
result = [U+0078] // do we want this (just x)
result = [U+00E9, U+0078] // or this? (no removal)
result = [U+0301, U+0078] // or even this? (implicit expansion and removal)
Those cases are particularly important because the result:
[U+0301, U+0078]
starts with a combining mark. Note how all of those cases could be solved if we consider the unit of reasoning being extended grapheme clusters.
Second source of difficulty: a match may consume different numbers of extended grapheme clusters on the two sides
S1 = [U+00DF] // ß
S2 = [U+0073, U+0073] // SS
Crucially, in German, the uppercase version of S1 is S2, but S2 is composed by two extended grapheme clusters. This is not just an isolated case, and other funny things may happen, for example, the character Σ (U+03A3) can lowercase into two different forms depending on its position: σ (U+03C3) in the middle of a word, or ς (U+03C2) at the end. Again, those are conceptually "the same text" under some comparison notions (case insensitivity)
Of course if neither side is expanded or both sides are expanded, there is no problem. But what about the other cases?
Case 4A: text expanded, prefix compact
text = [U+0073, U+0073, U+0061, U+0062, U+0063] // "SSabc"
prefix = [U+00DF] // S1
result = [U+0061, U+0062, U+0063] // do we want this
result = [U+0073, U+0073, U+0061, U+0062, U+0063] // or this?
Case 4B: text compact, prefix expanded
text = [U+00DF, U+0061, U+0062, U+0063] // S1 + "abc"
prefix = [U+0073, U+0073] // "SS"
result = [U+0061, U+0062, U+0063] // do we want this
result = [U+00DF, U+0061, U+0062, U+0063] // or this?
Here the difficulty is worse than before.
In the e-acute case, the source match still felt like one visible unit against one visible unit.
Here, the logical match may consume:
- 2 source units on one side
- 1 source unit on the other side
So a simple left-to-right algorithm that compares "one thing" from text with "one thing" from prefix is no longer enough.
Third source of difficulty: ligatures and similar compact forms
The same problem appears again with ligatures.
Let us name them:
L1 = [U+FB03] // LATIN SMALL LIGATURE FFI
L2 = [U+0066, U+0066, U+0069] // "ffi"
Again, those may count as "the same text" under some comparison notions.
Case 5A: text expanded, prefix compact
text = [U+0066, U+0066, U+0069, U+006C, U+0065] // "ffile"
prefix = [U+FB03] // L1
result = [U+006C, U+0065] // do we want this
result = [U+0066, U+0066, U+0069, U+006C, U+0065] // or this?
Case 5B: text compact, prefix expanded
text = [U+FB03, U+006C, U+0065] // L1 + "le"
prefix = [U+0066, U+0066, U+0069] // "ffi"
result = [U+006C, U+0065] // do we want this
result = [U+FB03, U+006C, U+0065] // or this?
This case can also be expanded in the same way as the e-acute/e case before:
text = [U+FB03, U+006C, U+0065] // L1 + "le"
prefix = [U+0066] // "f"
result = [U+FB03, U+006C, U+0065] // no change
result = [U+0066, U+0069, U+006C, U+0065] // remove one logical f
result = [U+FB01, U+006C, U+0065] //remove one logical f and use "fi" ligature
result = [U+006C, U+0065] // remove the whole ligature
Boolean matching is easier than removal
A major trap is to think:
"If I can define startsWith, then removePrefixIfPresent is easy."
That is false, as the case of e-acute/e.
A tempting idea: "just normalize first"
A common reaction is:
- normalize both strings
- compare there
- problem solved
This helps, but only partially.
What normalization helps with
It can make many pairs easier to compare:
- precomposed vs decomposed forms
- compact vs expanded forms
- some compatibility-style cases
So for plain Boolean startsWith, normalization may be enough.
What normalization does not automatically solve
If the function must return a substring of the original text, we still need to know:
- where in the original source did the normalized match end?
That is easy only if normalization keeps a clear source mapping.
Otherwise, normalization helps answer:
- "is there a match?"
but does not fully answer:
- "what exact source region should be removed?"
Moreover, this normalization is performance intensive and thus could be undesirable in many cases.
Several coherent semantics are possible
At this point, it is clear that any API offering a single behavior would be hiding complexity under the hood and deceive the user. This is of course an example for a large set of behaviours: startsWith, endsWith, contains, findFirst, replaceFirst, replaceAll, replaceLast etc.
So, my question for you is: What is a good API for those methods that allows the user to specific all reasonable range of behaviours while making it very clear what the intrinsic difficulties are?
13
u/latkde Apr 12 '26
In my opinion, string operations are often anchored in a bytes-only or ASCII-only worldview. Things like substring operations simply don't make a lot of sense in a Unicode world. A programming language would be well advised to provide functions for manipulating (structured) data, but text operations other than concatenation are typically both so rare and so context-dependent that it's difficult to provide an implementation that works well in all cases.
A possible escape hatch is to provide multiple views onto the same text data. A piece of text can be viewed as a sequence of bytes, codepoints, normalized codepoints, grapheme clusters, or other tokens.
There are a couple of languages that provide prior art for this:
stris a codepoint view over an UTF-8 encoded bytes array. Interestingly, offsets in the string view identify the underlying byte position, and string length is the underlying bytes slice length. This is a deliberately leaky abstraction..unicodeScalarsor.utf8view if needed. This strikes a great balance of intuitive operations and complete flexibility. However, a removePrefix() operation is suspiciously absent.30
u/hrvbrs Apr 12 '26
I might have a naïve take but i'd say just treat internally identical Unicode sequences as equal and that’s it. If people complain that you’re not treating [U+00E9] like [U+0065, U+0301] and vice versa, tell them to take it up with Unicode who got us into this mess in the first place ;)
4
u/initial-algebra Apr 12 '26 edited Apr 12 '26
To be honest, this is pretty off-topic for programming language design.
From a language perspective, I think the only important thing is that character/string literals aren't tied to a specific encoding. In fact, the idea of a character literal should probably be thrown out, since most of the time when you say "character" you actually want "glyph", or "grapheme cluster", and you need strings to represent them. If you have more specific needs, then I think it's better to use a string literal and explicitly specify the encoding with a (compile-time) function that returns a value of the appropriate integer type (or a special type backed by an integer type), if such an encoding exists.
4
u/dcpugalaxy Apr 13 '26
Why did you use AI to generate this post? Can you not write yourself? There are lots of really obvious AI writing style tells.
It worries me that someone would think himself qualified to design a programming language who cannot set out a problem like this succinctly in his own words.
For example this post could simply have been:
One paragraph instead of this massive bloated post, copy pasted from ChatGPT, explaining the very well known problem which is better described elsewhere.
35
u/elprophet Apr 12 '26
For the programming language? Default answer is "don't guess don't do anything fancy, let the calling code handle it". The correct answer for "what Unicode APIs should I expose" is ICU, probably ICU4C normalized to or wrapped by the conventions of your language. https://unicode-org.github.io/icu/userguide/icu4c/
16
u/curtisf Apr 12 '26
The only incontrovertible interpretation of a Unicode string is as a sequence of code-points (or scalar values, depending on how you validate...)
How the text represented by a a Unicode strings appears visually, or, ultimately, will be interpreted by a human, is not a well defined question. It depends on what languages are understood by the consumer, what fonts are available, what rendering methods are supported by those fonts, how careful the reader is being, ...
Unicode provides reference algorithms for doing certain text-transformations. Some of these are mostly technical, such as normalization, some of them are linguistic (and thus context dependent) such as transforming case.
In addition to the complexity of interpreting text in the first place, the interpretation changes with every release of Unicode. (Although a lot of properties are not allowed to be changed, the interpretation of a larger block of text could dramatically change if you are unaware of a recently added character or property)
Because the interpretation of a sequence-of-codepoints is so dependent on context, any transformation to that sequence is going to damage interpretability by some context, unless that transformation is accomplishing an explicit technical transformation which was expected by the consumer.
Any API that you expose should be clear about what exactly it accomplishes.
Something to keep in mind is that string/text-handling is sometimes security sensitive, and trying to do something "smarter" or "better" may weaken security if you deviate from what your users expect is happening.
The only thing you can promise with any sense of reliability are technical transformations. Ideally these cite a specific, unambiguous definition of the transformation algorithm, such as a particular version of a Unicode annex, like https://www.unicode.org/reports/tr29/#Sentence_Boundaries
7
u/AdvanceAdvance Apr 12 '26
This is the common first level of Unicode, taught as encodings and compositions. It is wrong.
1
u/[deleted] Apr 12 '26
If you want to give the user is much freedom as possible, you need to allow the user to choose 1) which characters can be replaced by which other characters for normalisation, and 2) whether the operation can split a cluster. Note that normal Unicode normalisation has no effect on the ß character.
1
u/b2gills Apr 13 '26
Raku has dealt with this by coming up with synthetic characters for new combinations of combined characters. It uses NFG Normalization Form Grapheme. Unfortunately usernames, passwords, and filenames are not really Unicode. So it has to add a way to selectively prevent that normalization from happening.
If you want a language that is full on transparently Unicode, I would suggest looking into it.
2
u/lngns Apr 13 '26
We have locales and cultures for those.
C# string operations for instance are culture-sensitive and either require the user to specify the desired behaviour or default to a thread-specific context which defaults to an application domain's context which defaults to the ambient system locale used by Win32 and POSIX.
C# also defers to the ICU (which is distributed with newer versions of MS Windows, if you target those).
This is true only if you normalise on demand.
If you allow operations only on operands using the same normalisation, then everything matches. This moves the problem of keeping anchors between different objects elsewhere.
Your comparison routines do not read UTF-8 strings only to tell you how to index into UTF-EBCDIC strings, do they?
Generic routines accepting types handling multiple encodings (iterators, really) is doable and keeps the concerns separate.
.sizedoes not tell us what it is doing. And whenever we need that information, we typically want something specific.In fact,
a + bdoes not tell us if we're concatenating memory objects, - implying combining of characters, - or if we're concatenating atomic texts, - implying insertion of ZWNJs.Other fun things you did not mention: