Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Introduction

import Lait
#lait

Course Overview: Why Study Programming Languages?

You have all programmed in a programming language, but so far, you’ve most likely only interacted with the language as an oracle: you have written programs, and you have learned the meaning of various programs by running them and seeing what happens. This is like how a baby learns to speak: you have learned about programming languages observationally, sometimes also called by immersion.

This course is all about the active study of programming languages. It’s a bit like an English class: we will break programming languages into their tiny gruesome pieces to learn about how they work. It’s also a bit like a math class: we will give precise definitions for what programs do, and study the consequences of those choices. And of course, it’s a programming class: you will write a lot of code and implement a host of different programming languages throughout the course.

In this course, we will actively engage in the study of programming languages. Programming languages have many facets:

  • Social: A programming language is a means of communication between programmers, and exists in a social environment with its own customs.
  • Mathematical: Programs written in a programming language have an abstract notion of “meaning”, given as a definition.
  • Implementation: A programming language can be realized as a program (a compiler, interpreter, etc.) that can be run by a computer and programmed in.

We will study these aspects in turn and implement many programming languages ourselves. Along the way, we will understand more about today’s programming languages, and understand where programming languages may be going in the future.

Consequences of Programming Language Design

Programming languages should not make you laugh at something that they do, but many are unfortunately hilarious. What do you think this C program does?

#include <iostream>

int main() {
   while(true) {}
}
void go_home_c_plus_plus_you_are_drunk() {
    std::cout << "lol" << std::endl;
}

If you answered “loop forever”, you would be wrong for the latest version of C running on Clang, see for yourself by running it here. In fact, this program prints “lol” to the console. The reason why it does this isn’t so important. The fact that it does this at all is what matters. It turns out that this behavior is mathematically legal; the C specification permits this “optimization”.

Note: This video is recommended viewing.

What do you think this JavaScript program that adds two empty arrays evaluates to?

[] + []

If you answered “empty string”, you know a lot of JavaScript and you are right! Why does this evaluate to the empty string? Well, + becomes string append, so it coerces its arguments into strings, and the empty array is coerced into the empty string. Of course!

What’s the point? Aren’t programming languages just funny complicated things that sometimes have weird behavior, just like how English sometimes has strange oddities that we simply accept?

Yes, and no. Languages are synthetic creatures: we made them! Every oddity in a language was someone’s idea that they thought was a really cool idea that would help them, or someone else, program. Sometimes, it is only in hindsight – after programming in a language for many years and writing lots of code – that we realize a cool-seeming idea wasn’t so cool after all.

An important example is Tony Hoare’s billion dollar mistake: null pointers. Consider the following Java program:

public class Example {
    public static void main(String[] args) {
         Object obj = null;
         obj.hashCode();
   }
}

This program causes a runtime error. The design question is: should Java’s typechecker permit this program? Today, it does: you can compile this program, and running it will yield a runtime error. The problem with null values is that they can happen anywhere; programs can surprisingly fail due to a mystery null appearing and not being handled properly, leading to very expensive debugging to track down where the null value originated. Over time, due to this cost, programming languages have slowly moved away from this model: languages like Rust or Kotlin do not permit arbitrary null values, and by and large this is accepted and no one complains about missing their null values.

The moral of the story is: language design is important and can impact generations of programmers. Many of today’s programming languages were developed in a very ad-hoc way; they have small mistakes and big mistakes, and programmers just learn to live with them. As a society, we are beginning to grapple with the enormous technical debt of programming in languages with poor design decisions: for instance, the federal government has, in the past, advocated for programming in memory-safe languages. The main aim of this class is to study the systematic design of programming languages: what are the choices one can make in making a programming language, and how are those choices implemented. It might even make you a better programmer.

Tips for Success in the Course

  • Read the syllabus carefully and ask questions if anything is unclear.
  • Attend lectures and take your own notes. It might be useful for you to follow along with the code yourself.
  • Read the course notes and give feedback on them if you see any typos.
  • Make use of your resources. Go to office hours if you need help, ask questions on Piazza.
  • Communicate with the instructor if you are struggling or need accomodations.
  • Start assignments early; they can be quite tricky and you might need help. Test your code!

Lait

One lesson we will see in this class is that the smaller a programming language is, the harder it is to mess up. Lait is a programming lanugage designed for teaching programming languages courses. It is small, so it has less opportunities for mistakes. It has a simple syntax and type system inspired by ML. See here for more information about Lait. We won’t cover every feature you need from Lait in this lecture; you are expected to learn some on your own.

A Lait program is a collection of definitions. The following is a Lait program:

def myNumber := 2 + 2

If you hover over the myNumber definition, you will see that it has type Int. You can also hover over commands, such as def and #eval below, to see documentation for them. You can then evaluate the definition by using the #eval command:

#eval myNumber>> 4

Note: In these notes, definitions of important terms are written in bold. Important ideas are written with emphasis.

Lait has a number of built-in types, such as Int, Bool, and String, and supports ordinary the arithmetic and boolean operations:

#eval true>> true
#eval false>> false
#eval true && false>> false
#eval if true then 1 else 2>> 1
#eval 1 * (2 - 3) + 4>> 3
#eval "hello">> "hello"
#eval "hello" ++ " " ++ "world" -- String concatenation is written using ++>> "hello world"
#eval 1 == 2>> false
#eval 1 != 2>> true
#eval 1 >= 2>> false
#eval 1 <= 2>> true
#eval 1 < 2>> true
#eval 1 > 2>> false

Lait Functions

Lait is a higher-order language, meaning that functions are values. Let’s take a look at one:

def myFun := fun x => x + 1

If we hover over it, we can see that it has type Int -> Int. We can then apply it to an argument by using the #eval command:

#eval myFun 1>> 2

Instead of writing functions using fun, we can also make them using definitions that take arguments:

def myFun' x := x + 1

This style of function can also take multiple arguments:

def myAdd x y := x + y

Type Annotations

Definitions in Lait can be annotated with types, which ensures that the type Lait assigns to the definition is what you intended. It’s good style to do so.

You can annotate the type of a definition like so:

def myNumber' : Int := 2 + 2
def myBool : Bool := true && false
def myAdd' x y : Int := x + y

Note that for functions, the type annotation is for the output of the function; not the function as a whole. Let’s see what happens if we get the type annotation wrong:

def badNumber : String := 2 + 2

As you can see, this will cause a type error.

For functions, you can annotate the type of the arguments like so:

def myAdd_annotated_args (x : Int) (y : Int) : Int := x + y

Note that you don’t need to annotate every argument:

def myAdd'' x (y : Int) := x + y

Local Variables

When writing the body of a definition, you can introduce local variables by using the let keyword:

def myNum := 
    let x := 2 in 
    let y := 3 in 
    x + y

Lists

Lists are an important datatype. A list is one of two things: an empty list Nil, or a cons node Cons hd tl where hd is the head of the list and tl is the tail of the list.

Let’s see some lists:

#eval Nil>> Nil
#eval Cons 1 Nil>> Cons 1 Nil
#eval Cons 1 (Cons 2 Nil)>> Cons 1 (Cons 2 Nil)

It’s tedious to declare lists this way, so we have several short-hand notations. First, Nil and Cons can be abbreviated to [] and :: respectively:

#eval []>> Nil
#eval 1 :: []>> Cons 1 Nil
#eval 1 :: (2 :: [])>> Cons 1 (Cons 2 Nil)

Next, we can use the following notation to build lists more easily:

#eval [1, 2, 3]>> Cons 1 (Cons 2 (Cons 3 Nil))

We will use all of these notations throughout the course.

Now that we’ve seen how to build lists, let’s see how to use them. We must analyze them using pattern matching.

def myList := [1, 2, 3]
def addList xs := 
  match xs with 
  | Nil => 0
  | Cons hd tl => hd + addList tl
  end

#eval addList myList>> 6

Pattern matching in Lait must begin with match ... with, have a number of cases — for lists, two for head and cons — and must end with end. We often use xs to denote a list (think of it as the plural of x).

For lists in particular, the [] and :: notations work for pattern matching as well:

def addList' xs := 
  match xs with 
  | [] => 0
  | hd :: tl => hd + addList' tl
  end

#eval addList' [1, 2, 3]>> 6

Testing and Errors

Lait has some built-in commands for testing and error handling. The most important one is #test, which ensures that a given expression evaluates to an expected value:

#test (addList' [1, 2, 3]) === 6

Note that #test requires three equal signs === to separate the given expression from the expected value. One equal sign, =, is used for definitions; two equal signs, ==, is used for checking equality; and three equal signs, ===, is used for testing.

A successful test will report nothing, while a failed test will show an error:

#test (addList' [1, 2, 3]) === 7

Syntax: Programs Are Data

Our study of programming languages begins with understanding how programs are represented to the computer. Surface syntax is the textual representation of a program: it’s what you type into your editor.

Consider the following surface syntax for a calculator expression:

1 + 2

This represents the program “add 1 and 2”. The first important lesson is that this choice of syntax is not a given. The following other choices could also work:

Syntax StyleExampleDescription
S-Expressions(+ 1 2)As seen in Lisp-style languages, such as Racket
Postfix1 2 +Used in some programming languages and calculators

Syntax is merely a matter of convention. To understand a programming language more deeply, we need to abstract away the details of the surface syntax and work with a more uniform representation. This is called abstract syntax, which can be represented as the following data structure in Lait:

type CalcLang := | NumE (val : Int) | AddE (left : CalcLang) (right : CalcLang)

Then, the program “add 1 and 2” can be represented as:

def add1to2 :=  AddE (NumE 1) (NumE 2)

This same abstract syntax can represent a variety of different surface syntax. The process of translating surface syntax into abstract syntax is called parsing; we will discuss this a bit more next lecture.

Semantics: Giving a Programming Language Meaning

Semantics associates a meaning with abstract syntax. What does the program add1to2 do? Intuitively, this program should “evaluate to 3” by performing the addition 1+2.

We define the semantics of programs compositionally by giving a meaning to each part. Let’s start by giving a specification for the semantics of calculator programs using English:

  • NumE v should evaluate to v
  • AddE l r should evaluate by evaluating l and r individually, and then adding the results.

We are using one language, English, to describe the behavior of another language, CalcLang. It’s helpful to give these two languages names to denote their roles. We call CalcLang the object language: it’s the language we are trying to describe. We call English the meta-language: it’s the language we’re using to describe another one.

While one can use English to describe the semantics of a programming language — and very important langauges are specified in this way — we will opt for a different approach, and specify programming languages by using another programming language (namely, Lait).
Doing this has a number of advantages. First, our Lait specifications will be executable, meaning that we can actually run CalcLang programs via Lait. Second, by using Lait, we are forced to be formal and precise. Indeed, our specification for the semantics of AddE is not quite precise enough. For example: what if l or r do not evaluate to numbers? what order should we evaluate l and r in? are we using “real” numbers, integers, or something else? By using Lait as our meta-language, we are forced to have an answer to all of these questions.

Lait as a Meta-Language

We can use Lait as a meta-language for describing the meaning of CalcLang programs. To do this, we can write an interpreter: a Lait program that runs CalcLang programs. Here is an example of such a program:

def interpCalc (e : CalcLang) : Int := 
 match e with
 | NumE v => v
 | AddE l r => interpCalc l + interpCalc r
 end

#test (interpCalc (AddE (NumE 1) (NumE 2))) === 3
#test (interpCalc (AddE (AddE (NumE 1) (NumE 2)) (NumE 3))) === 6

Here, we delegate the problem of defining the meaning of the values 3 and 6 to Lait: these are Lait integers. We also delegate the meaning of + to Lait: this is Lait addition.

This is our first programming language. We will see many more.