Type Systems For The Uninitiated

· 14 min

Since the recent ChatGPT 3.5 was released only almost four years ago. boom of AI assisted programming, there’s been a growing interest around programming languages, particularly their type systems. If you are even remotely present in Twitter/X, YouTube or Hacker-News you’ve seen many projects being rewritten to more “type safe” languages like Rust, efforts to strengthen guarantees in languages like TypeScript and even new languages with emphasis on types.

One recurring argument is that expressive type systems make programming with agents easier. But what does type safety even mean? What does a type system have to offer?

Introduction

I, like many of you, have not had a formal education on programming languages. I’ve essentially done what most out there do, just messed around until all the concepts you being thrown around online start making sense, the best thing I did was exposing myself to languages that force you to think because it helped me develop a good surface understanding of the layers involved. That’s why this is an informal exploration of type systems and their use, intended for to someone who already programs.

Type Systems

To start talking about type systems we have to first talk about what is a type. Already that is kind of a land-mine, the answer could depend heavily on whom you ask, it could be really technical and rich or bit reductive and tell you its only how memory is interpreted. That difference stems from different point of views on the importance on the role of a type system. For this I’d liked to adopt Luca Cardelli’s use of it in “Type Systems”, where he calls a type:

“A program variable can assume a range of values during the execution of a program. An upper bound of such a range is called a type of the variable.”

For example, in a language with a 16-bit signed integer type, a variable explicitly or implicitlyBy implicitly think of languages with type inference or Hindley-Milner type-checking algorithms where you don’t usually need to annotate. declared with it can hold values ranging from −215-2^{15} to 215−12^{15}-1. The type system ensures that operations on these values follow the language’s rules, including error cases.

This is achieved by two pieces working in together, first is the type system: a set of rules that together defines what is a well-typed expression in a language. These type rules are computed in the abstract (think of how a formal grammar is detached of the actual parsing algorithm that gets executed) and they are built from the ground-up using judgments, particular claims done under a set of assumptions I avoided giving examples in fear of making the part too big. If you want to go deeper on that defer to the “Type Systems” paper above. . It’s important to understand that the quality of a type system is not measured by the number of rules it has, but by how it shapes the semantics of the language. A program being well-typed should serve to ensure good program behavior.

Then, there is the type-checker: an algorithm that implements the type systems rules (completely or partially) and works to check if a program is well-typed by exercising the rules and failing if it’s unable to guard against possible errors .

These rules can be enforced in different ways depending on the language and algorithm. In statically typed languages (Rust, C or OCaml) they are checked at compile-time before the program is executed. Other languages, often dynamic languages, rely on runtime checks to know if an operation is valid on a given value. Type-checking can be done independently of program execution, for example, in TypeScript every type gets erased when compiled to JavaScript. In practice, languages often combine both kinds of checks.

It’s important to remember that a particular type-checker for a language can, for many reasons, diverge from the formal specification of the type system. In many cases there is no complete formal description of the type system to begin with, instead, the closest resource is the actual type-checker implementation or a collection of prose describing the rules in an intuitive form. Take WebAssembly’s, OCaml’s and Kotlin’s as examples of varying degrees of formality.

Safe languages

Earlier, I mentioned a trend of moving projects to “safer” languages. To understand that, we have to understand that type safetyWhich is not the same as memory safety. can be defined as the property of a program. Borrowing from Cardelli’s framework, a type safe program has ruled out errors that don’t immediately stop computation (named untrapped errors) and defines a safe language as one where all programs are safe.

He expands this idea by declaring a subset of the possible execution errors as forbidden errors, formed by all the unexpected and a subset of the trapped errors (errors which stop the program immediately) and, similarly, states that a program without forbidden errors can be considered well-behaved, and a language where all programs are well-behaved is strongly checked. There’s also the notion of type soundness which, in this framework, is too a property of a program stated to not cause forbidden errors. In a more pragmatic sense, it means that the program doesn’t break the type system’s rules.

This may sound good and all, it surely makes sense but it starts to become less useful when you realize that every language chooses what to consider as an unexpected or a trapped error. Even more so, each language implementation can add more checks and guard against more errors than what are defined in the rules of the language, this post makes a better case about it than what I could write. Because language safety is a binary property, you are either completely safe or you are not, so maybe the actual useful part of the discussion is how many errors can be prevented. You have to account for the actual implementation of the language and what guarantees it upholds when push comes to shove.

Preservation and Progress

Proving type soundness for a type system is not trivial, it is a discipline by itself, language design is a combinatorial problem and you’ll have to make sure all the programs written with it never get stuck, meaning that it can never reach a point in execution where an expression is not a value and no evaluation rule applies to move that expression forwards, that should have been rejected! For this, its good to know at least two of the theorems used: Preservation and Progress.

First, let’s introduce some notation to express these theorems somewhat precisely:

Symbol Meaning Example
Γ\Gamma Typing context. It maps variables to their types and carries all assumptions currently in scope. Γ={x:Int, f:Int→Bool}\Gamma = \{x : \mathrm{Int},\ f : \mathrm{Int} \to \mathrm{Bool}\}
⊢\vdash Turnstile operator. Read as “under the assumption of”. Separates the context from the typing conclusion. Γ⊢e:τ\Gamma \vdash e : \tau — in context Γ\Gamma, ee has type τ\tau
τ\tau Stands for any concrete type in a judgment. ⊢42:τ\vdash 42 : \tau where τ=Int\tau = \mathrm{Int}
:: Typing relation. It relates an expression to its type. true:Bool\mathrm{true} : \mathrm{Bool} — true has type Bool
→\rightarrow Single-step evaluation. It is one reduction step in the semantics of the language. 1+1→21 + 1 \rightarrow 2
val\mathrm{val} Value predicate. Denotes that an expression is a value and cannot reduce further. e vale\ \mathrm{val} means ee is a value
∧\land Logical “and”. Both propositions on either side must hold simultaneously. e val∧e:τe\ \mathrm{val} \land e : \tau
∨\lor Logical “or”. At least one of the propositions must hold. τ=Int∨τ=Bool\tau = \mathrm{Int} \lor \tau = \mathrm{Bool}
∅\varnothing Empty typing context. No variable assumptions are in scope. ∅⊢5:Int\varnothing \vdash 5 : \mathrm{Int} is a closed term
∃\exists Existential quantifier. Witnesses some value or type satisfying a given property. ∃τ. Γ⊢e:τ\exists \tau.\ \Gamma \vdash e : \tau
.. Binder operator. Read as “such that”. ∃x. P(x)\exists x.\ P(x) — there exists xx such that P(x)P(x)

Where ΓΓ represents all the variables that are in the scope alongside their types. It’s used in the relation Γ⊢e:τΓ ⊢ e : τ that can be read as “the typing context shows that ee has type ττ”.

Preservation can be expressed as:

Γ⊢e:τ∧e→e′⟹Γ⊢e′:τ\Gamma \vdash e : \tau \land e \rightarrow e' \Longrightarrow \Gamma \vdash e' : \tau

Preservation can be read as a judgment stating that “if under the typing context ΓΓ, ee has type ττ, and ee steps to e′e' in one step, then e′e' also has type ττ under ΓΓ”. It ensures that each step of evaluation preserves the type of the expression, remember what we talked about ranges before.

and Progress as:

∅⊢e:τ⟹(e val)∨(∃ e′. e→e′)\varnothing \vdash e : \tau \Longrightarrow (e\ \mathrm{val}) \lor (\exists\ e'.\ e \rightarrow e')

Progress and can be read as “if under the empty typing context ∅∅, ee has type ττ then ee is either a value or there exists an expression e′e' reachable by a single step from ee”. It ensures that well-typed closed expressions (essentially a whole type sound program) are either values or can be further evaluated and will not get stuck.

What about untyped languages?

Also referred to as “Dynamic Languages”, borrowing from Robert Harper’s Practical Foundations for Programming Languages, they are languages that embrace a model of computation where they do not have any types whatsoever or multiple classes of values exist for a single recursive type. A quote from the book states:

“Every dynamic language is inherently a static language in which we confine ourselves to a (needlessly) restricted type discipline to ensure safety.”

Here every value is tagged to indicate which class of value they belong through a process called Classification. The only static check done is that the expression is well-formed, and that there are no free variables in the expressionThis is, of course, in theory. Python is a dynamic language that has no issues parsing a program with free variables, remember that this is a general description not a unbreakable rule. ; Checks for errors that would have never show up in a statically-typed language are done at runtime by a process called Class Checking using the tags each value was given.

This changes how the theorems are proven. Progress is expressed as:

d ok⟹(d val)∨(d err)∨(∃ d′. d→d′)d\ \mathrm{ok} \Longrightarrow (d\ \mathrm{val}) \lor (d\ \mathrm{err}) \lor (\exists\ d'.\ d \rightarrow d')

Progress now reads as “If dd is a closed expression, then it’s either a value, results in a runtime error or it can be further evaluated”.

And there’s now a Exclusivity lemma:

∀ d:exactly one of (d val), (d err), (∃ d′. d→d′)\forall\ d : \text{exactly one of } (d\ \mathrm{val}),\ (d\ \mathrm{err}),\ (\exists\ d'.\ d \rightarrow d')

Which states that, for any dd in the language, exactly one of these outcomes must be true at any given time.

In the previous model, these errors were guaranteed not to happen! But, since catching those errors before evaluation requires static typing, now they have become part of the behavior (the semantics) of the language! Since there exists only one singular recursive type, Preservation plays lesser of a role here, there is no static type information to preserve between evaluations!

A little example for this can be done by manipulating a list in Python, we can try something thats obviously wrong and we’ll still see the error only at runtime and not before!

> python3
>>> list.append([], 3.14) # This works without issue, because why not, I am passing a list!
>>> list.append("obviously not a list", 3.14)
Traceback (most recent call last):
  File "<python-input-4>", line 1, in <module>
    list.append("obviously not a list", 3.14)
    ~~~~~^^^^^^^^^^^^^^^^^^^^
TypeError: descriptor 'append' for 'list' objects doesn't apply to a 'str' object

Since it wasn’t able to resolve to a value nor be further evaluated, it resulted in a runtime error.

If we look deeper, we can see that this is done implementing a similar idea to that of a single recursive type Harper talks about. In the CPython Language Reference, there is a type PyObject described as “All object types are extensions of this type. This is a type which contains the information Python needs to treat a pointer to an object as an object”. How does that look like? Well, lets check the source code:

> wget https://www.python.org/ftp/python/3.11.18/Python-3.11.18.tgz
> tar -xzf Python-3.11.18.tgz
> z Python-3.11.18/
typedef struct _object PyObject;
typedef struct _typeobject PyTypeObject;
Include/pytypedefs.h
/* Nothing is actually declared to be a PyObject, but every pointer to
 * a Python object can be cast to a PyObject*.  This is inheritance built
 * by hand. ... 
 */
struct _object {
    Py_ssize_t ob_refcnt;
    PyTypeObject *ob_type;
};
Include/object.h

You can see that the definition is small enough, it only has a field to counter the number of references pointing to it and a pointer to a PyTypeObject holding a bunch of metadata about the type. To understand how this “inheritance” is done in CPython you’ll need to know that in C, the fields in a struct are laid out in memory in the order they are declared. CPython leverages this by having every specialized type start its definition with a PyObject, the float type for example:

typedef struct {
    // This is a macro that gets expanded in normal builds to a ob_base field of type PyObject
    PyObject_HEAD
    double ob_fval;
} PyFloatObject;
Include/cpython/floatobject.h

Thanks to this, as the comments say in the _object definition, it allows any pointer to an object to be interpreter as a pointer to a PyObject, creating the relation in which any object is a PyObject. In turn, the _typeobject holds key information like the type name and its size, which is how CPython implements the idea of tagging a value to be able to do Class Checking later. Also you can see the definition has a PyObject field so it is recursive, again, similar to how Harper states.

struct _typeobject {
    PyObject_VAR_HEAD
    const char *tp_name; / For printing, in format "<module>.<name>" */
    Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */
    ...
}
Include/cpython/object.h

To see Class Checking in action, we can see:

static inline int PyObject_TypeCheck(PyObject *ob, PyTypeObject *type) {
    return Py_IS_TYPE(ob, type) || PyType_IsSubtype(Py_TYPE(ob), type);
}
Include/object.h

The function expects an object and a given type to check if the object is of said type or a subtype of it! This function is used in a lot of places to check if a necessary method description applies to an object. For example, if we grab the descr_check function and add a print statement before checking:

static int descr_check(PyDescrObject *descr, PyObject *obj) {
  printf("I am checking!\n"); 
  if (!PyObject_TypeCheck(obj, descr->d_type)) {
    PyErr_Format(PyExc_TypeError,
     "descriptor '%V' for '%.100s' objects "
     "doesn't apply to a '%.100s' object",
     descr_name((PyDescrObject *)descr), "?",
     descr->d_type->tp_name,
     Py_TYPE(obj)->tp_name);
    return -1;
  }
  return 0;
}
Objects/descrobject.c

Then we compile it again and run our first example against it:

> ./configure
> make -j"$(nproc)"
> ./python
>>> list.append("obviously not a list", 3.14)
I am checking!
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: descriptor 'append' for 'list' objects doesn't apply to a 'str' object

You’ll see that this function was the one who created the message printed before!I cleaned up a lot of the terminal output because it seems to be called a lot so, if you do it yourself, you’ll see the message spammed everywhere.

Types As Design Tools

When I was thinking on what to show as an example of static typing, I didn’t want to do a basic example of, I don’t know, passing the wrong value to a function and have the compiler scream at me, it is the most basic example and it would showcase the point but it is boring.

To showcase how static typing can be used to design software, in this case an API, in the most brief way possible, I thought of the typestate patternIf you want to read an explanation of it, read Cliff Biffle’s article and how it is applied in rustls, a crate (a library) that implements the TLS Protocol and it’s features. The crate has a type ConfigBuilder that leverages the pattern to encode the states of a process in the type system and enforces them at compile-time:

/// ...
/// # Types
///
/// ConfigBuilder uses the [typestate] pattern to ensure at compile time that each required
/// configuration item is provided exactly once. This is tracked in the `State` type parameter,
/// which can have these values:
///
/// - [`WantsVersions`]
/// - [`WantsVerifier`]
/// - [`WantsClientCert`]
/// - [`WantsServerCert`]
///
/// The other type parameter is `Side`, which is either `ServerConfig` or `ClientConfig`
/// depending on whether the ConfigBuilder was built with [`ServerConfig::builder()`] or
/// [`ClientConfig::builder()`].
///
/// You won't need to write out either of these type parameters explicitly. If you write a
/// correct chain of configuration calls they will be used automatically. If you write an
/// incorrect chain of configuration calls you will get an error message from the compiler
/// mentioning some of these types.
/// ...
///
#[derive(Clone)]
pub struct ConfigBuilder<Side: ConfigSide, State> {
  state: State,
  provider: Arc<CryptoProvider>,
  time_provider: Arc<dyn TimeProvider>,
  side: PhantomData<Side>,
}

Focus on the highlighted part of the comments which showcase the patternFully understanding each feature in the snippet would take a much longer article, but you can search them yourself: parametric polymorphism, phantom data(which isn’t the same as phantom types!) and dynamic sized types , if we go and try to configure the verifier twice for our config, in other languages you could be overwriting the previous config, but here that would result in an error:

use rustls::server::{ServerConfig};

fn main() {
  let builder = ServerConfig::builder()
    .with_no_client_auth()
    .with_client_cert_verifier(todo!());
}
> cargo c
    Checking example v0.1.0 (/home/lautaro/Documents/Development/example)
error[E0599]: no method named `with_client_cert_verifier` found for
struct `ConfigBuilder<ServerConfig, WantsServerCert>` in the current scope
 --> src/main.rs:4:109
  |
4 |     let builder = ServerConfig::builder()
  |       .with_no_client_auth().with_client_cert_verifier(todo!());
  |                              ^^^^^^^^^^^^^^^^^^^^^^^^^
  |          method not found in `ConfigBuilder<ServerConfig, WantsServerCert>`
  |
  = note: the method was found for `ConfigBuilder<ServerConfig, WantsVerifier>`

This is because once we configure the verifier by using with_no_client_auth() we moved from the WantsVerifier state to the WantsServerCert state, which simply doesn’t have a method for that. With the same mechanism, the builder() method from ServerConfig returns a ConfigBuilder<ServerConfig, WantsVerifier, so we are forced to set that first before anything elseYou can try it yourself . All of those state transitions are encoded in type signatures:

impl ServerConfig {
  pub fn builder() -> ConfigBuilder<Self, WantsVerifier>;
}

impl ConfigBuilder<ServerConfig, WantsVerifier> {
  pub fn with_no_client_auth(self) -> ConfigBuilder<ServerConfig, WantsServerCert>;
  pub fn with_client_cert_verifier(self, client_cert_verifier: Arc<dyn ClientCertVerifier>) -> ConfigBuilder<ServerConfig, WantsServerCert>;
}

Before, I mentioned that types are different things depending on whom you ask. This is a good example of that. Instead of only being used to describe the shape of data, they express the semantic intent of the maintainers of the crate.

This idea extends beyond this particular pattern. Rust’s standard library provides abstractions that express the behavior of computations. Take, for example, Future, Iterator or good old Result, expressing asynchronous computations, pull based iteration and the outcome of a fallible operation, respectively.

Conclusion

This is it! There are still a lot of things I didn’t cover about how type systems are leveraged, the rabbit hole goes so deep I choose to stop here because otherwise it would become too long and it would miss the point.

We explored both statically and dynamically typed languages and saw how they can offer meaningful safety guarantees about the behavior of our programs. The strength of an expressive static type system lies in its ability to offload some of the reasoning about the program’s behavior to the compiler, enabling us to focus more on the design of better abstractions. By encoding properties in types and using them as building blocks we can rule out entire classes of errors by construction.

That has always been the case with statically typed languages, but it may become more widely adopted as AI assisted programming is becoming the norm in the industry and the volume of code grows beyond what can be reviewed. How much this ideas will end up shaping the future of agentic engineering remains to be seen. Early signs suggest they’re playing a role right now.

These are truly exciting times to be living in!

Further reading

Sound type systems, have interesting properties for the coming times, types can combine to create programs that work as proofs for propertiesTypes As Propositions. , really, there are people burning millions of tokens as you read this to create proofs in Lean or Rocq, no matter how useful they turn out to be.

You can also see the shift towards static typing in languages like Elixir that now have a gradual type system or further efforts to leverage the existing type system like in TypeScript with libraries like effect and gdp-ts.

I recommend reading Ted Kaminski’s “The One Ring Problem” article around abstraction design, if your jam is testing, I too like Alperen Keles articles around automated testing and verification methods.

References

  • Harper, Robert. (2016) Practical Foundations for Programming Languages. 2nd ed. Cambridge University Press.
  • Cardelli, Luca. (1996) “Type Systems.” In The Computer Science and Engineering Handbook, edited by Allen B. Tucker, chapter 140.