r/ProgrammingLanguages • 🧿 Pipefish • Apr 28 '26

Hindsight languages

A thought experiment. What languages should they have been writing in the 60s, 70s, 80s, 90s? We can see their faults, in hindsight, and also we've had some really cool ideas since then --- but we can't answer this just by pointing to our shiny new modern languages and saying "they should have done it like that", because of compile times.

(E.g. Pipefish is meant to be for rapid iteration and livecoding, and also does a topological sort on everything at compile-time so you can do top-down declaration. Those wouldn't be compatible goals in the 1980s, I can get away with it now.)

So for example if we think of "a better C", are there any cool modern ideas they could and should have used back in 1972, had they known about them --- or should they just have tweaked the precedence slightly, found a less arcane way of describing types, and left it at that?

39 Upvotes

72 comments sorted by

View all comments

56

u/alphaglosined Apr 28 '26

Some obvious things that wouldn't have cost much:

  1. Make null something you opt-into for parameters/variables
  2. Tuples
  3. Sum types
  4. Slices (pointer + length)
  5. Compile time constants and CTFE, so that you can ditch macro preprocessors i.e. C's

26

u/Great-Powerful-Talia Apr 28 '26

I like to say that the null pointer exception is a dynamic typing error to really drive home why it shouldn't be an expected problem.

If I'm coding in Python or JS, I should expect the possibility of a variable being NULL instead of Int, just as I should expect the possibility of it being String instead of Int.

If it's a statically typed language, why do I not statically know what operations are valid on my variables? That's the whole point of static typing. If it's an int, you know it's an int. If it's a float, you know it's a float. If it's a pointer, then maybe it contains a pointer (which supports dereferencing), or maybe it contains something that doesn't support the dereferencing operation, and therefore isn't the same type.

24

u/Norphesius Apr 28 '26

Well from a C perspective, nullability is a consequence of the memory model. A pointer is just an address, there's no other associated info. You don't even know if it's an address inside your allocated memory space. NULL (0x0) isn't even necessarily special, its just another address. In plenty of embed systems its a valid, writable/readable address. You can make new addresses with pointer math or casting, whats the static type in that case?

So many of C's flaws come from design compromises to reduce memory, so the bookkeeping of tagging a type with a reference wouldn'tve been permissible. The constraints apply to compile time too (hence header files), so attempting to track everything statically wouldn't work either. C's nullability is an unfortunate product of its time.

14

u/Great-Powerful-Talia Apr 29 '26 edited Apr 29 '26

I wouldn't argue that C should actually take steps to totally prevent a null pointer from being packaged as a normal pointer. It's C, you can do anything in C, this is known.

But it should afford it the same level of restriction as is given to ints/floats- that is, you can package a float as an int32_t, but you shouldn't, and that etiquette is still inherent to the language. No reasonable person is going to conclude, based on the syntax of C, that they actually should return *(int*)&myFloat instead of making the function signature say float myFunc(...)

Consider int *foo as a non-nullable pointer, int *?bar or something as a nullable pointer. In that case, it's not that you wouldn't be able to make foo point to 0x0, it's just that you would be rightfully annoyed if someone made a function that returned a potentially-invalid int* when they could more easily just specify that it can be null by saying the function returns an int*? instead.

Imagine if all ints were the same type and you had to choose whether to use signed or unsigned operations yourself. And you had to constantly track "okay, does this function's documentation specify signed or unsigned meanings?" That would be stupid.

Even though it's not actually enforced in any meaningful way, C still does fix this problem just by allowing you to call something a signed or unsigned value, thus allowing you to tag signedness in the type system itself instead of putting it in the documentation.

And yet we have many functions that return a valid pointer, and many functions that return a potentially-null pointer, and many variables that can hold null pointers, and many variables that should never hold null pointers, and their type signatures don't clarify matters for no good reason at all.

6

u/Norphesius Apr 29 '26

As for the signed/unsigned distinction, that's something that CPUs understand and have different sets of operations for, so I can understand how when C was designed that was accounted for.

I can't justify the lack of dedicated syntax for distinguishing nullability, but if its not statically enforced, it just becomes a conventions thing anyway. Arguably you could achieve the same thing using typedef specifying a (non)nullable type e.g. typedef int* int_ptr_no_null; typedef int* int_ptr_maybe_null; (or something more terse). You would still get bugs & mistakes assigning a null where it shouldn't be, though.

I suspect the fact that all the C codebases I've seen don't do this speaks to how it either wasn't envisioned as meaningful distinction for C devs when the language was being made, or that it isn't a very effective pattern (or both).

5

u/alphaglosined Apr 29 '26

There are extensions in gcc/clang for nullability and C has _Optional now.

C is going kicking and screaming to gain static analysis capabilities as part of the spec, but there is an effort to make it happen.

For nullability the clang folks are suggesting going in the direction of type qualifiers due to problems with C (they have it implemented in a restricted form). And of course clang-analyser understands it. https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3876.pdf

So yeah things are improving.

2

u/WittyStick Apr 29 '26 edited Apr 29 '26

Cake has optional types and uses the correct approach to retrofitting them - using a pragma #nullable enable/#nullable disable (though missing #nullable restore) - similar to other proposals it uses qualifiers. It also has owned pointers using the same approach.

I still think these proposals are missing something though - a more general model of modal types that is more flexible. They could take some inspiration from granule. In particular I would also like to see uniqueness types and linear types.

9

u/glasket_ Apr 29 '26

NULL (0x0)

Just FYI, the null pointer isn't guaranteed to be address 0, that's just convention. All the standard states is that the ICE 0 is guaranteed to be the null pointer when suitably converted. So int *p = 0; is always null, but uintptr_t x = 0; int *p = (int *)x; doesn't have to be.

2

u/yuri-kilochek Apr 30 '26

Well from a C perspective, nullability is a consequence of the memory model. A pointer is just an address, there's no other associated info. You don't even know if it's an address inside your allocated memory space. NULL (0x0) isn't even necessarily special, its just another address. In plenty of embed systems its a valid, writable/readable address. You can make new addresses with pointer math or casting, whats the static type in that case?

You aren't actually allowed to do what you describe in standard C. It's not legal to do arithmetic on NULL, or increment an object pointer out of bounds of the complete object (one that isn't a subobject of another object) it points to. So it's not just an address, but tracking this metadata is the responsibility of the programmer, the compiler and runtime don't help you.

1

u/Norphesius Apr 30 '26

I was imprecise and not quite accurate with what I said (as other people have pointed out). NULL is special, and usually 0x0 is NULL, but it doesn't have to be.

That being said, even if the particular concept of NULL didn't exist in the C standard spec, you would still probably have common convention of 0x0 or some other address acting as "this address is invalid" informally (although more error prone, since you could write to it). Whether explicit or implicit, NULL & C are bound together.

2

u/dcbst Apr 30 '26

This is an area where Ada really excels! You have System.Address type, which is just a raw address like in C which can of course be zero. There is no real concept of a 'Null' System.Address and values of System.Address cannot simply be used as pointers and dereferenced. They can only be used to map/locate a value/variable to an address in memory. Accesses to that variable will then be made to the specified address. System.Address is simply a low level systems programming mechanism, typically used for accessing hardware registers.

Then you have pointers, or Access Types in Ada. They are nothing really to do with addresses, but more an object which points to another object of a given type. They can be null, if desired, in which case you need to explicitly check before dereferencing (otherwise you get a runtime exception), or you can explicitly state that a pointer is "not null", in which case, you can guarantee that the pointer always points to a valid object of the given type.

1

u/renozyx Apr 29 '26

Slices aren't inexpensive (think of the x86 and other CPUs with a paltry few registers), plus they create compatibility issue if one has a 16bit length and another a 32bit length.. Fat pointers (two pointers) are better if again a little more expensive.

0

u/PrimozDelux Apr 29 '26

For tuples and sum types, how would the language support that without becoming opinionated? Maybe they could have exposed it as part of the language plus a reference implementation? I.e if you wanted the tuple datastructure to behave differently, you could supply a header (or something better ideally, but that's another story) with your desired implementation if the standard one wasn't to your liking. It would be a headache for sure, but not having sum types and tuples would've been well worth it. Question is, with hindsight, would it have been feasible in the 70s?

2

u/alphaglosined Apr 29 '26

C is an opinionated language.

It has field layouting and its own calling convention.

There is nothing wrong with being opinionated about how sumtypes are lowered. If it's not the right tool for the job, either the compiler would change, or somebody would do something else.

Today, we'd throw attributes/pragma's at it if you wanted to alter the layout. Which wasn't really a thing in the 70's.

Lowering both tuples and sumtypes to structs wouldn't have been much of a problem; it would be quite simple to do with a 70's compiler that doesn't support forward references or complex symbol lookup.

-3

u/dcpugalaxy Apr 29 '26

Disagree with all of these except 4.

5

u/alphaglosined Apr 29 '26

Okay, but why?

4

u/WittyStick Apr 29 '26 edited Apr 29 '26

I somewhat agree, but not entirely. The issue is that implementations of things like tuples and sum types are opinionated, and not a great fit for C, where we essentially have full control of memory layout.

Sum types for example, have a "hidden" tag field ("hidden" being the red flag) - does this field go before or after the value in memory? How wide is the tag? Is the value stored directly or indirectly via a reference? There are multiple ways we can implement tagged unions and for this reason alone they don't belong in C (at least how they're typically implemented in other languages). The C programmer should chose precisely how they're laid out in memory - which implies they have access to the tag field and it is not hidden.

We can already do a sum type in C with a struct containing a tag field and a union. We can implement slices and tuples similarly. The issue is C provides limited means of encapsulation. We can properly encapsulate with GCC specific extensions, but this requires a bit of preprocessor boilerplate and isn't portable C.

What I would like is a more general feature for encapsulation - given this, we could implement tuples, sum types, slices ourself, without having to resort to compiler extensions and preprocessor foo.

And we also require such feature to be zero cost, as performance is a primary goal of C.

4

u/tsanderdev Apr 29 '26

We can already do a sum type in C with a struct containing a tag field and a union. We can implement slices and tuples similarly. The issue is C provides limited means of encapsulation. We can properly encapsulate with GCC specific extensions, but this requires a bit of preprocessor boilerplate and isn't portable C.

Exactly what builtin sum types would solve. Only being sble to access tge right data in it when you should be able to. And as for "where is the tag", either the standard specifies it or you are sble to manually say start or end for each sum type.

1

u/Ok-Scheme-913 Apr 29 '26

Not having is specialized also let's the compiler to simply omit it when not necessary. E.g. you have a function where you only use one of the options, here the compiler can "unwrap" the sum type and use it as is.

1

u/WittyStick Apr 29 '26 edited Apr 29 '26

What if the tag is neither at the end nor the start? What if the tag isn't a plain integer? There are simply too many options - and a "standard" version would be too opinionated.

That's why we don't want a specific feature for tagged unions, but a general feature for enabling fields to be encapsulated.

Here's an example of how we can provide encapsulation using non-standard GCC features:

// NB: The designated_init attribute forces us to name the fields for initialization
//       preventing us from using positional initializers 
//       as in: (struct string){ len, chars }

struct string __attribute__((__designated_init__)) {
    size_t _internal_string_length;
    char *_internal_string_chars;
};

#define STRING_CREATE(len, chars) \
    (struct string) \
        { ._internal_string_length = (len) \
        , ._internal_string_chars = (chars) \
        }
        
#define STRING_LENGTH(string) \
    ((string)._internal_string_length)

#define STRING_CHARS(string) \
    ((string)._internal_string_chars)

// The poison pragma then prevents the field names being used in any code afterwards.
#pragma GCC poison _internal_string_length _internal_string_chars

// Any code below here cannot access the field names,
// Except via the 3 macros provided.
//Eg:

inline struct string string_from_chars(const char *str) {
    size_t len = strnlen(str, STRLEN_MAX);
    char *storage = malloc(len + 1);
    strncpy(storage, str, len);
    storage[len] = '\0';
    return STRING_CREATE(len, storage);
}
inline void string_free(struct string string) {
    free(STRING_CHARS(string));
}
inline size_t string_length(struct string string) {
    return STRING_LENGTH(string);
}
inline void string_set_char(struct string string, size_t index, char chr) {
    if (index >= STRING_LENGTH(string)) error("Out of bounds");
    STRING_CHARS(string)[index] = chr;
}
inline char string_get_char(struct string string, size_t index) {
    if (index >= STRING_LENGTH(string)) error("Out of bounds");
    return STRING_CHARS(string)[index];
}

// We undefine the 3 macros to prevent any further access to the fields
#undef STRING_CREATE
#undef STRING_LENGTH
#undef STRING_CHARS

// Any code below here cannot access the fields, except via the functions above.
// (Or via manipulating pointers)
// We cannot redefine the macros because we poisoned the field names.

I've previously described how to implement tagged unions with these tricks.

But there's an undesirable amount of boilerplate. What would be nice if there were some kind of feature for encapsulating fields of structs in a way that can avoid the boilerplate and GCC specific features.

I'm not entirely sure how such feature would look - but perhaps it could be done via C23 attributes:

struct string [[opaque]] {
    size_t length [[private]];
    char  *chars  [[private]];
};

inline struct string string_from_chars(const char *str) 
    [[access(struct string)]]
{
    size_t len = strnlen(str, STRLEN_MAX);
    char *storage = malloc(len + 1);
    strncpy(storage, str, len);
    storage[len] = '\0';
    return (struct string){ len, storage };
}

inline void string_free(struct string string) 
    [[access(struct string)]]
{
    free(string.chars);
}

inline size_t string_length(struct string string) 
    [[access(struct string)]]
{
    return string.length;
}

inline void string_set_char(struct string string, size_t index, char chr) 
    [[access(struct string)]]
{
    if (index >= string.length) error("Out of bounds");
    string.chars[index] = chr;
}

inline char string_get_char(struct string string, size_t index) 
    [[access(struct string)]]
{
    if (index >= string.length) error("Out of bounds");
    return string.chars[index];
}

// permanently seal the fields so no other functions may access.
[[seal(struct string)]];

And rather than a specific implementation of tagged unions, I'd rather see a more general facility for pattern matching - something like a _Match which behaves somewhat like a switch (with no implicit fallthrough) and somewhat like an inverse _Generic - eg, something of the form:

_Match(src, dst, CASE1 : value1, CASE2 : value2, ...) 
{
    case CASE1:
        // dst = value1 and has type typeof(value1)
    case CASE2:
        // dst = value2 and has type typeof(value2)
}

So a tagged union using the approaches above would look like:

enum my_tag {
    TAG_FOO,
    TAG_BAR
};

union my_union {
    struct foo as_foo;
    struct bar as_bar;
};

struct my_tagged_union [[opaque]] {
    enum my_tag tag [[private]];
    union my_union value [[private]];
}

#define my_tagged_union_create(value) \
    _Generic [[access((struct my_tagged_union)]]  \
        ( (value) \
        , struct foo : (struct my_tagged_union){ TAG_FOO, foo } \
        , struct bar : (struct my_tagged_union){ TAG_BAR, bar } \
        )

#define my_tagged_union_match(tu, value) \
    _Match [[access(struct my_tagged_union)]] \
        ( tu.tag \
        , value \
        , TAG_FOO : tu.value.as_foo \
        , TAG_BAR : tu.value.as_bar \
        )

[[seal(struct my_tagged_union)]]

usage:

auto x = my_tagged_union_create((struct foo)}{ ... });

my_tagged_union_match (x, value) 
{
    case TAG_FOO: 
        // value has type struct foo
    case TAG_BAR:
        // value has type struct bar
}

The _Match form above would not be tied to any specific implementation of tagged unions - it's a general facility for mapping values of different types to a common variable name, scoped only to the respective case.

3

u/Ok-Scheme-913 Apr 29 '26

Having a standard option doesn't prevent you from doing some unsafe special case optimization next to it.

Like rust has sum types, but you are free to have some union with unsafe where you use this and that bit to denote whatever you want. The language is still better for the former, which encompasses 99% of use cases.

1

u/WittyStick Apr 29 '26 edited Apr 29 '26

A "standard" for tagged unions will simply never be added to C. I'd bet close to 100% of the standard committee would reject any such proposal.

The approach I've suggested above has much more chance - the use of attributes for start makes the entire feature optional (the attributes are ignored if not supported), and the _Match proposal adds safety without adding runtime cost - which is more likely to pass. There's probably better approaches to the match that could be used though. Perhaps something like:

_Match(val, CASE1 : value1, CASE2 : value2)
{
    case CASE1(auto foo): //foo = value1
    case CASE2(auto bar): //bar = value2
}

But this requires changes to the syntax of case labels, whereas the previous version only requires the addition of a new _Match form, which resembles generic selection. I'd prefer the latter though.

1

u/alphaglosined Apr 29 '26

Maybe not a dedicated type, but I suspect with the work towards memory safety in C, they may end up adding something to make sum types safe.

However, my general feeling reading the document log, I'd say they are not up to this yet. They have a long way to go to standardise stuff from 20 years ago, that's now considered normal.

And you know, 15 years ago, IBM blocked C from removing digraphs and trigraphs, and one of those is now gone. Things do change when it comes to that committee.

1

u/WittyStick Apr 29 '26

Sum types aren't from 20 years ago though. They're half a century old at this point.

The issue isn't about making sum types safe - the suggestions I've given above can do this. The issue is about "hidden state" - it's very un-C-like. Nothing should be hidden.

If you argue the case for hiding a tag field, then it's only a stones throw away to suggesting hiding a field that is a pointer to a vtable - and then you have to fight to keep "OOP" out of C.

→ More replies
→ More replies (6)

0

u/Ok-Scheme-913 Apr 29 '26

But C was never zero cost. The queen of performance is C++ for a reason - lack of abstraction in C also hinders the possible "user-written" optimizations that are possible, like small string optimizations.

But it's enough to look at ordinary C code, people often opt for a shittier data structure simply because it's more ergonomic to use. Meanwhile a "good" language like C++ or Rust let's you use a better algoritjm/data structure ergonomically with zero cost. (E.g. see C's over reliance on linked lists, and sure the kernel may be an exception as they do have a reason for that, but a random user space C library has no excuse, it just lacks proper vector types).

→ More replies (9)