Devlog: Adding String Indexing to Flower
This one was fairly quick, and was about making one very normal-looking thing actually work:
name: string = "Ivy" as string
first: char = name[0]
That sounds small, but once string became a real Flower type, indexing could no longer piggyback on the old “arrays and pointers only” behavior. The compiler needed to understand that string[index] is its own case.
What changed
I taught the typechecker to treat string subscripts as char.
That means:
-
string[index]now resolves tochar - the index expression must be an integer
- string indexing is readonly for now
So this is valid:
first: char = name[0]
but this is not:
name[0] = 'X'
I wanted reads first, writes later. That keeps the rules simple while the string representation is still compiler-owned. I’m not sure how writes would work with a C backend, due to how ‘strings’ are allocated. Perhaps a feature for post-v2.0?
Lowering it to C
Since Flower strings currently lower to a struct with .data and .length, codegen needed a special path for string subscripts.
Normal arrays and pointers still lower like:
arr[index]
but strings now lower like:
name.data[index]
That keeps the generated C valid without changing how regular subscripts work elsewhere in the language.
So something conceptually like:
This checkpoint also forced one strict-but-correct rule that required me to update a WHOLE SINGLE LINE (hehe):
arg[i] = tolower(arg[i] as char)
to
arg[i] = tolower(arg[i] as char) as char
Because tolower(...) is effectively treated as returning int, assigning it back into a char subscript needs an explicit cast. I kept that strictness on purpose. I do not want Flower silently narrowing values just because C would let it.
Validation
I expanded the string example coverage to check:
- string indexing returns the expected chars
-
string[index]works alongsidestring <-> @charcasts - bootstrap still succeeds
- repeated bootstrap succeeds
- tests still pass
Which, after all the recent bootstrap chaos, was very nice to see.
Where this leaves v1.3
Now we can:
- store strings
- compare strings
- print strings
- inspect
length - index into them as
char
This should make it much easier to replace the builtin C functions with a Flower library in the near-near future.
Comments 0
No comments yet. Be the first!
Sign in to join the conversation.