Programming Search⌘K

Conceptcore

Syntax

Also called syntax, concrete syntax, abstract syntax, abstract syntax tree, AST, parse tree, syntax error, syntactic sugar, desugaring, grammar, surface syntax, automatic semicolon insertion, most vexing parse.

Syntax is the set of rules for the form of a program: which characters make tokens and which sequences of tokens make valid programs. What a valid program does is a question of semantics.

Applies to
core-languages

Idea

A program is text, and a language must say which texts are programs. Syntax is the set of rules for this. It says how characters make words such as names, numbers and symbols, and how the words make expressions, statements and declarations. A text that breaks these rules has a syntax error, and the compiler or the interpreter rejects it before the program runs. A text that obeys them can still be wrong, but that is a question of meaning, which is semantics.

import ast

# Syntax is the form of a program. The parser turns the text into a tree.
tree = ast.parse("total = price * (1 + rate)")
print(ast.dump(tree.body[0].value))

# Two texts with the same tree have the same syntax in the abstract.
a = ast.dump(ast.parse("x=1+2*3"))
b = ast.dump(ast.parse("x = 1 + (2 * 3)"))
print("same tree:", a == b)

# A syntax error is found before the program runs.
try:
    compile("total = price * (1 + rate", "<text>", "exec")
except SyntaxError as e:
    print("SyntaxError:", e.msg, "at line", e.lineno)

# Correct syntax can still fail when it runs: that is a matter of semantics.
code = compile("1 / 0", "<text>", "eval")
try:
    eval(code)
except ZeroDivisionError as e:
    print("ZeroDivisionError:", e)
Output
BinOp(left=Name(id='price', ctx=Load()), op=Mult(), right=BinOp(left=Constant(value=1), op=Add(), right=Name(id='rate', ctx=Load())))
same tree: True
SyntaxError: '(' was never closed at line 1
ZeroDivisionError: division by zero

The parser turns price * (1 + rate) into a tree: a multiplication whose right operand is an addition. The parentheses are not in the tree, because the shape of the tree already gives the grouping. x=1+2*3 and x = 1 + (2 * 3) give the same tree, so the spaces and the extra parentheses do not change the program. The text with a missing ) is not a program, and compile rejects it before anything runs. 1 / 0 has valid syntax, and it fails only when it runs.

How it works

Syntax and semantics. "The syntax of a language describes the form of a valid program, but does not provide any information about the meaning of the program or the results of executing that program"1. Semantics gives the meaning. "Not all syntactically correct programs are semantically correct"1: a program can have valid syntax and still use a name that does not exist, mix types or divide by zero. See program semantics.

Three levels. Computer language syntax "is generally distinguished into three levels"1:

  • Words, "the lexical level, determining how characters form tokens". See tokens and lexing.
  • Phrases, "the grammar level, narrowly speaking, determining how tokens form phrases".
  • Context, "determining what objects or variables names' refer to, if types are valid, etc."

Java describes the first two levels with two grammars. Its syntactic grammar "has as its terminal symbols the tokens defined by the lexical grammar", and it describes "how sequences of tokens can form syntactically correct programs"2. The third level is often called static semantics, and the compiler checks it after the parse. In the Java example, int x = 1 } is a syntax error, and int x = "one"; is a type error that the compiler finds after a successful parse.

Grammars and notation. A language reference gives its syntax as a grammar: a set of rules that each say how a phrase is made from smaller parts. Go writes: "The syntax is specified using a variant of Extended Backus-Naur Form (EBNF)"3. Python uses "a grammar notation that is a mixture of EBNF and PEG"4. See context-free grammars.

Concrete and abstract syntax. The parser gives "the parse tree, or "concrete syntax tree", which is determined by the grammar, but is generally far too detailed for practical use, and the abstract syntax tree (AST), which simplifies this into a usable form"1. The AST drops the parentheses, the semicolons and the layout, and keeps the structure. Tools read and change programs through the AST. Python's ast module "helps Python applications to process trees of the Python abstract syntax grammar"5, and Go's go/parser "produces an ast.File representing the complete abstract syntax tree of the file"6.

Rules that are not obvious. Some rules of syntax surprise programmers:

  • JavaScript inserts a semicolon at a line break in some places. "return a + b" on two lines "is transformed by ASI into return; a + b;"7, so the function returns undefined.
  • Go also inserts semicolons. A semicolon goes "immediately after a line's final token" if that token is a name, a literal, one of some keywords, or one of ++, --, ), ] and }3. So the { of a function must be on the same line as the func.
  • In C++, "In case of ambiguity between a variable declaration using the direct-initialization syntax (1) (with round parentheses) and a function declaration, the compiler always chooses function declaration"8. So Timer t1(); declares a function. This rule "has been called the most vexing parse"8.
  • In C, the parse of T * x; depends on whether T names a type. If it does, the line declares a pointer, and if not, it multiplies two values.

Syntactic sugar. "Syntactic sugar is syntax within a programming language that is designed to make things easier to read or to express"9. The compiler translates the sugar into a longer form, and the two forms have the same meaning:

  • In C, "The subscript operator E1[E2] is exactly identical to *((E1)+(E2))"10, so 1[a] is valid.
  • In Java, "The meaning of the enhanced for statement is given by translation into a basic for statement"11 that uses an Iterator.
  • In C#, "The C# compiler translates query syntax into method calls", and "Query syntax and method syntax are semantically identical"12.
  • A Python decorator is a short form of a call and an assignment, and a[i] calls __getitem__.

Syntax that the program extends. Some languages let a program add syntax. In Rust, "macro_rules allows users to define syntax extension in a declarative way"13. Lisp macros, Scheme syntax-rules and C preprocessor macros do similar things at different levels. See syntactic macros.

In languages

LanguageVerdictNote
PythonNative
C++Native
JavaNative
CNative
C#Native
JavaScriptNative
TypeScriptNativeTypeScript has the syntax of JavaScript and adds type annotations, interfaces and generics, and the compiler API gives the syntax tree of a file. No example file exists.
GoNative
RustNative
KotlinNativeKotlin has optional semicolons, trailing lambdas and string templates, and its specification gives the grammar. No example file exists because kotlinc is not installed.
SQLNativeThe SQL standard gives a grammar, and each database adds its own syntax. Keywords are not case sensitive. No example file exists.
BashNativeThe syntax of Bash is made of words, quoting, redirections and expansions, and bash -n checks the syntax of a script without running it. No example file exists.
PowerShellNativeThe PowerShell parser API, such as the Parser class in System.Management.Automation.Language, gives the syntax tree and the errors of a script. No example file exists because pwsh is not installed.
HTMLNativeHTML has a syntax of elements, attributes and text, and the HTML parser has rules to recover from almost every error.
CSSNativeCSS has a syntax of rules, selectors and declarations, and a parser skips a declaration that it cannot read and keeps the others.
Regular expressionsNativeA regular expression has a small syntax of its own with atoms, quantifiers, groups, classes and alternation, and the syntax differs between engines.
Language Verdict Mechanism
Python native indentation is syntax; PEG grammar; ast module in the standard library
JavaScript native C-like syntax; automatic semicolon insertion; new Function parses at run time
TypeScript native the syntax of JavaScript with type annotations; the compiler API gives the AST
Java native lexical and syntactic grammars in the JLS; javax.tools and the compiler tree API
Kotlin native optional semicolons; trailing lambdas; the grammar is in the specification
C# native C-like syntax; query syntax; the Roslyn syntax API as a library
Go native EBNF in the spec; semicolons inserted at line ends; go/parser and go/ast
Rust native expression-oriented syntax; macro_rules; syn as a library for parsing
C native declarator syntax; the parse depends on typedef names; a[i] is *(a + i)
C++ native the most vexing parse; templates; >> closes two argument lists
Bash native words, quoting and expansions; bash -n checks syntax without a run
PowerShell native the parser API gives the AST of a script
SQL native the syntax of the standard and of each database; keywords are not case sensitive
Regex native a small syntax of its own: atoms, quantifiers, groups and alternation
HTML native elements, attributes and text; the parser recovers from most errors
CSS native rules, selectors and declarations; a parser skips a declaration that it cannot read

Every language has a syntax, so the verdict is native for all 16 languages. They differ in the style of the syntax, in how strict the parser is, and in whether the standard library gives the program access to its own syntax tree.

The example files show these differences. Python prints an AST, prints the standard form of a text with ast.unparse, shows a decorator and a[i] as sugar, and reports the position of a syntax error. JavaScript shows a syntax error from new Function, a return that automatic semicolon insertion ends early, a { that starts a block, a tagged template and class syntax. Java compiles strings with the compiler API to separate a syntax error from a type error, and shows the enhanced for as sugar. C# compares query syntax with method syntax and shows properties, interpolation and patterns. Go parses an expression with go/parser, walks the tree and shows the error when a { is on its own line. Rust defines a macro, calls a method as a function and writes a for loop without the sugar. C shows 1[a], the declarator syntax, a typedef that changes a parse and the longest token rule in i+++j. C++ shows the most vexing parse, and the compiler warns about it on purpose, and >>, a range for and a raw string literal.

PythonGitHub
import ast

# The abstract syntax tree drops the layout and the parentheses.
print(ast.dump(ast.parse("f(a, b=2)", mode="eval").body))

# ast.unparse prints the tree as text in a standard form.
print(ast.unparse(ast.parse("x=(1+2)*  3")))

# Syntactic sugar: a decorator is a short form of a call and an assignment.
def shout(f):
    return lambda: f().upper()


@shout
def hi():
    return "hi"


def hey():
    return "hey"


hey = shout(hey)  # the same thing without the sugar
print(hi(), hey())

# a[i] is sugar for a call of __getitem__.
xs = [10, 20, 30]
print(xs[1], type(xs).__getitem__(xs, 1))

# A syntax error has a position.
try:
    ast.parse("if x\n    pass")
except SyntaxError as e:
    print("SyntaxError:", e.msg, "line", e.lineno, "offset", e.offset)
Output
Call(func=Name(id='f', ctx=Load()), args=[Name(id='a', ctx=Load())], keywords=[keyword(arg='b', value=Constant(value=2))])
x = (1 + 2) * 3
HI HEY
20 20
SyntaxError: expected ':' line 1 offset 5
  • Verdict: native. The ast module gives the abstract syntax tree, where a keyword argument is a keyword node. ast.unparse prints the tree in a standard form, so the extra parentheses and spaces go away. A decorator is sugar for a call and an assignment, and xs[1] is sugar for __getitem__. A syntax error has a line and an offset.
#include <iostream>
#include <string>
#include <type_traits>
#include <vector>

struct Timer {
    Timer() { std::cout << "Timer made\n"; }
};

int main() {
    // The most vexing parse: this declares a function, not an object.
    Timer t1();
    std::cout << std::is_function_v<decltype(t1)> << "\n";
    Timer t2{};  // braces make an object

    // >> closes two template argument lists.
    std::vector<std::vector<int>> grid{{1, 2}, {3}};
    std::cout << grid.size() << " " << grid[0].size() << "\n";

    // A range for is sugar for a loop with begin and end.
    int sum = 0;
    for (int v : grid[0]) sum += v;
    int sum2 = 0;
    for (auto it = grid[0].begin(), end = grid[0].end(); it != end; ++it) sum2 += *it;
    std::cout << sum << " " << sum2 << "\n";

    // Raw string literals change the syntax of a string: no escapes inside.
    std::string path = R"(C:\temp\new)";
    std::cout << path << "\n";
}
Output
1
Timer made
2 2
3 3
C:\temp\new
  • Verdict: native. Timer t1(); declares a function, which is the most vexing parse, so no object is made and the compiler warns about it on purpose. Timer t2{}; makes an object. >> closes two template argument lists. A range for is sugar for a loop with begin and end. A raw string literal has no escapes.
JavaGitHub
import com.sun.source.util.JavacTask;
import java.net.URI;
import java.util.List;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.ToolProvider;

public class Main {
    static String check(String code) {
        var compiler = ToolProvider.getSystemJavaCompiler();
        var diags = new DiagnosticCollector<JavaFileObject>();
        var src = new SimpleJavaFileObject(URI.create("string:///T.java"), JavaFileObject.Kind.SOURCE) {
            @Override public CharSequence getCharContent(boolean ignore) { return code; }
        };
        var task = (JavacTask) compiler.getTask(null, null, diags, List.of("-proc:none"), null, List.of(src));
        try {
            task.analyze();  // parse and check types, but write no class file
        } catch (java.io.IOException e) {
            return e.toString();
        }
        if (diags.getDiagnostics().isEmpty()) return "ok";
        Diagnostic<?> d = diags.getDiagnostics().get(0);
        return "line " + d.getLineNumber() + ": " + d.getMessage(null);
    }

    public static void main(String[] args) {
        // A syntax error: the parser expects a semicolon.
        System.out.println(check("class T { int x = 1 }"));
        // Correct syntax, but a type error: the compiler finds it after the parse.
        System.out.println(check("class T { int x = \"one\"; }"));
        System.out.println(check("class T { int x = 1; }"));

        // The enhanced for statement is sugar for a loop with an Iterator.
        int sum = 0;
        for (int v : List.of(1, 2, 3)) sum += v;
        var it = List.of(1, 2, 3).iterator();
        int sum2 = 0;
        while (it.hasNext()) sum2 += it.next();
        System.out.println(sum + " " + sum2);
    }
}
Output
line 1: ';' expected
line 1: incompatible types: java.lang.String cannot be converted to int
ok
6 6
  • Verdict: native. The compiler API compiles a string and reports diagnostics. A missing ; is a syntax error. int x = "one"; has valid syntax, and the compiler rejects it after the parse because the types do not match. The enhanced for statement is sugar for a loop with an Iterator, so the two sums are equal.
#include <stdio.h>

typedef int T;

int main(void) {
    /* a[i] is defined as *(a + i), so i[a] is also valid. */
    int a[3] = {10, 20, 30};
    printf("%d %d %d\n", a[1], *(a + 1), 1[a]);

    /* The declarator syntax reads from the name outward. */
    int *p[3];      /* an array of 3 pointers to int */
    int (*q)[3];    /* a pointer to an array of 3 ints */
    q = &a;
    p[0] = &a[2];
    printf("%zu %zu %d %d\n", sizeof p / sizeof p[0], sizeof *q / sizeof (*q)[0], *p[0], (*q)[0]);

    /* The parse of T * x depends on whether T names a type. */
    T * x = &a[0];  /* a declaration, because T is a typedef */
    printf("%d\n", *x);

    /* x+++y is read as x++ + y: the lexer takes the longest token. */
    int i = 1, j = 2;
    int k = i+++j;
    printf("k = %d, i = %d\n", k, i);
    return 0;
}
Output
20 20 20
3 3 30 10
10
k = 3, i = 2
  • Verdict: native. a[1] is defined as *(a + 1), so 1[a] is also valid. int *p[3] is an array of pointers, and int (*q)[3] is a pointer to an array. T * x is a declaration because T is a typedef. The lexer takes the longest token, so i+++j is i++ + j.
int[] nums = [5, 3, 8, 1];

// Query syntax is sugar: the compiler turns it into method calls.
var q1 = from n in nums where n > 2 orderby n select n * 10;
var q2 = nums.Where(n => n > 2).OrderBy(n => n).Select(n => n * 10);
Console.WriteLine($"{string.Join(",", q1)} | {string.Join(",", q2)}");

// String interpolation is sugar for a call that builds the string.
int a = 2, b = 3;
Console.WriteLine($"{a} + {b} = {a + b}");

// A property looks like a field in the syntax, but it calls a method.
var t = new Temp { Celsius = 100 };
Console.WriteLine(t.Fahrenheit);

// A pattern in a switch expression is a short form of tests and casts.
object o = 3.5;
Console.WriteLine(o switch { int i => $"int {i}", double d when d > 3 => $"big {d}", _ => "other" });

class Temp
{
    public double Celsius { get; set; }
    public double Fahrenheit => Celsius * 9 / 5 + 32;
}
Output
30,50,80 | 30,50,80
2 + 3 = 5
212
big 3.5
  • Verdict: native. The compiler translates query syntax into the method calls Where, OrderBy and Select, so the two queries give the same result. Interpolation builds a string. A property looks like a field, but reading it calls a method. A switch expression with patterns is a short form of tests and casts.
JavaScriptGitHub
// A syntax error stops the parse; new Function parses text at run time.
try { new Function("let x = ;"); } catch (e) { console.log(e.name + ":", e.message); }

// Automatic semicolon insertion: a line break after return ends the statement.
function f() {
  return
    42;
}
console.log("f() =", f());

// A { at the start of a statement starts a block, not an object.
console.log(eval("{ a: 1 }"), eval("({ a: 1 })"));

// Template literals are sugar for a call when a tag is used.
const tag = (strings, ...values) => strings.raw.join("|") + " / " + values.join(",");
console.log(tag`a${1}b${2}c`);

// Class syntax is mostly sugar over constructor functions and prototypes.
class Point { constructor(x) { this.x = x; } get double() { return 2 * this.x; } }
console.log(typeof Point, new Point(4).double);
Output
SyntaxError: Unexpected token ';'
f() = undefined
1 { a: 1 }
a|b|c / 1,2
function 8
  • Verdict: native. new Function parses text at run time and throws SyntaxError. A line break after return ends the statement, so f() returns undefined. { a: 1 } at the start of a statement is a block with a label, and in parentheses it is an object. A tagged template is sugar for a call. A class is a function.
package main

import (
	"fmt"
	"go/ast"
	"go/parser"
	"go/token"
)

func main() {
	// go/parser builds the syntax tree of Go code.
	expr, err := parser.ParseExpr("price * (1 + rate)")
	if err != nil {
		panic(err)
	}
	bin := expr.(*ast.BinaryExpr)
	fmt.Printf("%T %s %T\n", bin.X, bin.Op, bin.Y)

	// ast.Inspect walks the tree.
	n := 0
	ast.Inspect(expr, func(node ast.Node) bool {
		if _, ok := node.(*ast.Ident); ok {
			n++
		}
		return true
	})
	fmt.Println("identifiers:", n)

	// A syntax error has a position.
	fset := token.NewFileSet()
	_, err = parser.ParseFile(fset, "t.go", "package p\nfunc f() { x := }", 0)
	fmt.Println(err)

	// Go inserts semicolons at the end of lines, so a { must be on the same line.
	_, err = parser.ParseFile(fset, "u.go", "package p\nfunc g()\n{\n}", 0)
	fmt.Println(err)
}
Output
*ast.Ident * *ast.ParenExpr
identifiers: 2
t.go:2:17: expected operand, found '}'
u.go:3:1: unexpected semicolon or newline before {
  • Verdict: native. go/parser gives the syntax tree of an expression, and ast.Inspect walks it. A syntax error has a file, a line and a column. Go inserts a semicolon after func g() at the end of the line, so a { on the next line is a syntax error.
RustGitHub
// A macro by example matches a pattern of syntax and writes new syntax.
macro_rules! square_all {
    ($($x:expr),*) => { vec![$($x * $x),*] };
}

struct Counter { n: u32 }

impl Counter {
    fn bump(&mut self) -> u32 { self.n += 1; self.n }
}

fn main() {
    println!("{:?}", square_all!(1, 2 + 1, 4));

    // Method call syntax is sugar for a call of the associated function.
    let mut c = Counter { n: 0 };
    let a = c.bump();
    let b = Counter::bump(&mut c);
    println!("{a} {b}");

    // A for loop is sugar for a loop over IntoIterator::into_iter and next.
    let mut total = 0;
    for v in [1, 2, 3] { total += v; }
    let mut it = IntoIterator::into_iter([1, 2, 3]);
    let mut total2 = 0;
    while let Some(v) = it.next() { total2 += v; }
    println!("{total} {total2}");

    // stringify! gives the text of the tokens that it gets.
    println!("{}", stringify!(a + b * 2));
}
Output
[1, 9, 16]
1 2
6 6
a + b * 2
  • Verdict: native. macro_rules! matches a pattern of syntax and writes new code. Method call syntax is sugar for a call of the associated function with &mut c. A for loop is sugar for IntoIterator::into_iter and next. stringify! gives the text of its tokens.
  • Free form and layout. Most languages ignore line breaks and spaces between tokens. Python and Haskell use indentation as a part of the syntax, and Go and JavaScript use line breaks to insert semicolons.
  • Prefix syntax. Lisp writes every form as a list, such as (+ 1 2). The syntax is small and uniform, so macros can treat code as data.
  • Error recovery. A compiler can stop at the first syntax error or try to continue and report more errors. An HTML parser recovers from almost every error, because browsers must show pages that have them.
  • Syntax for tools. Editors highlight syntax, formatters such as gofmt and black print a standard form from the tree, and linters read the AST.
  • Language workbenches and parser generators. Tools such as yacc, ANTLR and tree-sitter make a parser from a grammar. GCC, Clang, the Go compiler and the Rust compiler use parsers that are written by hand.

Pitfalls

  • A line break that ends a statement. In JavaScript, a return followed by a line break returns undefined. Put the value on the same line as return.
  • The most vexing parse. T x(); in C++ declares a function. Use T x; or T x{};.
  • Sugar that hides a cost. A short syntax can hide a call, an allocation or a copy: a property in C#, an overloaded operator, or a for loop over an iterator.
  • Valid syntax with a different meaning. if (x = 0) in C, i+++j and a missing comma between two string literals in Python, which joins them, are all valid syntax that does not do what the programmer wanted.
  • An error far from its cause. A missing ) or } is often reported at the end of the file or at the next declaration. Read the lines before the reported position.

Cost

Parsing is fast. A compiler reads source text in time that grows about linearly with its size, and the type checking, optimization and code generation after it take most of the time of a build. An interpreter that reads the source each time it starts pays for the parse at each start, so Python stores compiled bytecode in __pycache__ and JavaScript engines cache compiled code.

History

The ALGOL 60 report gave its syntax with "metalinguistic formulae", and it named the source of the notation: "J. W. Backus, The syntax and semantics of the proposed international algebraic language of the Zuerich ACM-GRAMM conference. ICIP Paris, June 1959"14. This notation is now called Backus-Naur form, and most language references still use a form of it34. "The term syntactic sugar was coined by Peter J. Landin in 1964 to describe the surface syntax of a simple ALGOL-like programming language which was defined semantically in terms of the applicative expressions of lambda calculus"9.

Later languages added tools to read their own syntax. Python, Go and Java give a parser or a syntax tree in their standard distributions56, and Rust macros work on the syntax of the program at compile time13.

References

  1. Syntax (programming languages), Wikipedia, Introduction; Levels of syntax; Syntax versus semantics
  2. The Java Language Specification, Java SE 25 Edition, Chapter 2, 2.3 The Syntactic Grammar
  3. The Go Programming Language Specification, Notation; Semicolons
  4. Introduction, The Python Language Reference, 1.2 Notation
  5. ast, Abstract syntax trees, Python documentation, Introduction
  6. Package parser, Go standard library, Overview
  7. Lexical grammar, MDN Web Docs, Automatic semicolon insertion
  8. Direct-initialization, C++ reference, cppreference.com, Notes
  9. Syntactic sugar, Wikipedia, Introduction; Origins
  10. Member access operators, C reference, cppreference.com, Subscript
  11. The Java Language Specification, Java SE 25 Edition, Chapter 14, 14.14.2 The enhanced for statement
  12. Write C# LINQ queries to query data, Microsoft Learn, Introduction
  13. Macros By Example, The Rust Reference, macro.decl.intro
  14. Revised Report on the Algorithmic Language Algol 60, J. W. Backus and others, edited by Peter Naur, 1. Structure of the language; footnote on metalinguistic formulae

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/JV3AKW/text.yaml