Akuli / jou

Yet another programming language
MIT License
11 stars 4 forks source link

Initializing byte array with a string literal #359

Closed Akuli closed 1 year ago

Akuli commented 1 year ago

https://github.com/Akuli/jou/blob/6f1c37dc2dc1fba055b08c29f8373618e9bf0613/self_hosted/parser.jou#L104-L108

This is a bit weird. Ideally you could just do name = "self".

As a minimal example, this doesn't work:

foo: byte[100] = "hello"

Solution 1: bidirectional type inference

Bidirectional type inference, aka type context, means that the type of a thing depends on how it is used. If the string "hello" is being assigned into an array of type byte[100], its type would become byte[100] rather than byte*.

In general, I don't want to have bidirectional type inference in Jou, because it makes the language and the compilers more complicated. But just special-casing strings could be super simple.

I think I will go with this approach.

Solution 2: "hello" has type byte[6]

If we add an implicit conversion that lets you assign byte[6] to byte[100] (presumably filling the end with zeros), and we change "hello" to be byte[6] rather than byte*, then foo: byte[100] = "hello" would work.

An advantage is that sizeof "hello" would produce 6 as expected, rather than 8 (size of a pointer on 64-bit computer).

A disadvantage is:

if something:
    foo = "asd"  # Type of variable blah becomes byte[4]
else:
    foo = "asd asd"  # Error, because this string doesn't fit in byte[4]

Another disadvantage is that you might want an error for assigning arrays of different sizes. For example, if you pass int[3] to a function expecting int[5], you probably want an error rather than padding the int[3] array with two zeros.