Programming Search⌘K

Conceptcore

Source code

Also called source code, source, source text, source file, code, program text, translation unit, compilation unit, open source.

Source code is the text of a program in the form that people write, read and change. Tools turn it into tokens, a tree and then code that a machine can run.

Applies to
core-languages

Idea

Source code is the text of a program: the files that a programmer writes, reads, reviews and changes. A machine cannot run this text directly. A compiler or an interpreter reads it in steps: it cuts the characters into tokens, it builds a tree that shows the structure, and it turns the tree into machine code, bytecode or actions. Each step drops something that matters only to people, such as comments, spaces and the choice of names, so the text is the only form that keeps everything that the authors meant to say.

import ast
import io
import tokenize

source = "total = price * 3  # three items\nprint(total)\n"
print("characters:", len(source), "lines:", source.count("\n"))

# 1. The scanner cuts the text into tokens.
for tok in tokenize.generate_tokens(io.StringIO(source).readline):
    if tok.start[0] == 1 and tok.type != tokenize.NEWLINE:
        print(f"  {tokenize.tok_name[tok.type]:7} {tok.string!r}")

# 2. The parser builds a tree. The comment and the spaces are gone.
tree = ast.parse(source)
print(ast.dump(tree.body[0]))
print("back to text:", ast.unparse(tree.body[0]))

# 3. The compiler makes code that the machine can run.
code = compile(tree, "<example>", "exec")
exec(code, {"price": 4})
Output
characters: 46 lines: 2
  NAME    'total'
  OP      '='
  NAME    'price'
  OP      '*'
  NUMBER  '3'
  COMMENT '# three items'
Assign(targets=[Name(id='total', ctx=Store())], value=BinOp(left=Name(id='price', ctx=Load()), op=Mult(), right=Constant(value=3)))
back to text: total = price * 3
12

The source is one string of 46 characters on two lines. The scanner in tokenize cuts the first line into names, operators, a number and a comment. The parser in ast builds a tree with an assignment, a multiplication and a constant, and the comment and the extra spaces are not in the tree, so the text that ast.unparse makes from the tree has lost them. compile turns the tree into a code object, and exec runs it with a value for price.

How it works

Text in files. Source code is plain text, stored in files with a name and an extension, such as main.go or area.py. The language defines how the bytes of a file become characters. Most modern languages read UTF-8: in Python, "If no encoding declaration is found, the default encoding is UTF-8."2 The language also defines which file is the unit of compilation: a C translation unit is one source file after the preprocessor has inserted its headers, a Java compilation unit is one .java file, and a Go package is all the files of one directory.

From text to tokens. The first step of a compiler is lexical analysis. It reads the characters and groups them into tokens: names, keywords, numbers, strings, operators and punctuation. Spaces and comments separate tokens, and most languages then drop them. Python's tokenize module is "a lexical scanner for Python source code" that also "returns comments as tokens", which tools such as formatters and colorizers need.3 See tokens and lexing.

From tokens to a tree. The parser checks the tokens against the grammar of the language and builds an abstract syntax tree. Different texts can give the same tree: x=(a)+1 and x = a + 1 parse to the same assignment. Go's go/parser "implements a parser for Go source files" and keeps the position of each node, so tools can report an error at a file, a line and a column.8 Formatters such as gofmt, rustfmt and Black parse the source and print the tree again in one standard layout, which ends arguments about style.

From the tree to running code. A compiler turns the tree into machine code or bytecode, and an interpreter runs it. See compilers and interpreters. The compiler keeps a map from the output back to the source, as debug information, line tables or source maps, so that a debugger and a stack trace can show the source line of the running code. Java's StackTraceElement.getLineNumber "Returns the line number of the source line containing the execution point represented by this stack trace element."6

Source text inside the program. Some languages keep the source, or parts of it, for the running program. In CPython, inspect.getsource returns "the text of the source code for an object" by reading the file again.4 In JavaScript, a function's toString "returns a string containing the source text segment which was used to define the function".5 Compiled languages can put pieces of the source into the program when it compiles: C has __LINE__, which "expands to the source file line number", and the # operator, which turns a macro argument into a string literal.10 C++ has std::source_location, which "represents certain information about the source code, such as file names, line numbers, and function names".11 C# fills parameters with the caller's line and argument text,7 and Rust's stringify! "Stringifies its arguments".9 Assertion and logging libraries use these to print the failed expression and its line.

Source code as the preferred form. Source code is more than the input to a compiler. It is the form in which people understand and change a program, so licences define it that way. The Open Source Definition says: "The source code must be the preferred form in which a programmer would modify the program."1 It also excludes "Deliberately obfuscated source code" and "Intermediate forms such as the output of a preprocessor or translator". Programs from a generator, a minifier or a transpiler are text, but they are not the source in this sense.

In languages

LanguageVerdictNote
PythonNative
C++Native
JavaNative
CNative
C#Native
JavaScriptNative
TypeScriptNativeTypeScript source is text in .ts files, which the compiler checks and turns into JavaScript, with source maps that point back to the TypeScript lines, but no example file exists.
GoNative
RustNative
KotlinNativeKotlin source is text in .kt files, which the compiler turns into JVM class files with line number tables, but no example file exists because kotlinc is not installed.
SQLNativeAn SQL statement is source text that the database parses, checks and turns into a query plan.
BashNativeA Bash script is source text that the shell reads and runs one command at a time, and LINENO and BASH_SOURCE give the position, but no example file exists.
PowerShellNativeA PowerShell script is source text, and the parser API in System.Management.Automation.Language gives its tokens and syntax tree, but no example file exists because pwsh is not installed.
HTMLNativeAn HTML document is source text that the browser parses into a tree of elements.
CSSNativeA style sheet is source text that the browser parses into rules and declarations.
Regular expressionsNativeA pattern is source text in a small language that the engine compiles into a matcher.
Language Verdict Mechanism
Python native .py files in UTF-8; tokenize, ast, inspect.getsource
JavaScript native scripts and modules; Function.prototype.toString; new Function
TypeScript native .ts files that the compiler turns into JavaScript
Java native compilation units in .java files; javax.tools; stack traces
Kotlin native .kt files; the compiler writes JVM class files
C# native .cs files; caller information attributes; Roslyn
Go native packages of .go files in UTF-8; go/parser, go/format
Rust native crates of .rs files; stringify!, line!, column!
C native translation units; the preprocessor, __LINE__, #
C++ native translation units and modules; std::source_location
Bash native script files that the shell reads line by line
PowerShell native .ps1 files; the parser API in System.Management.Automation.Language
SQL native statements as text that the database parses and plans
Regex native a pattern is source text that the engine compiles
HTML native documents as text that the browser parses into a tree
CSS native style sheets as text that the browser parses into rules

Every language in the table has source code, because every one is written as text. The difference is what the running program keeps. Python and JavaScript keep enough to give the text of a function back. Java and C# keep line tables for stack traces, and their compilers are libraries that a program can call. C, C++ and Rust keep nothing by default, but macros and built-ins copy pieces of the source into the program when it compiles.

The example files show the stages and the tools. Python prints a function's own source, its first line and the tree that loses the comment. JavaScript gets the text of a function and compiles new text with new Function. Java writes a source file, compiles it with the compiler API and reads the class file. C# prints the text and line of each argument at the call. Go formats messy source with go/format and lists each name with its position. Rust, C and C++ make assertion macros that print the expression and the line.

PythonGitHub
import ast
import inspect


def area(w, h):
    # The comment is part of the source text.
    return w * h


print(inspect.getsource(area), end="")
print("first line in the file:", area.__code__.co_firstlineno)
print("tree to text:", ast.unparse(ast.parse(inspect.getsource(area))).splitlines())

# Two different texts, one tree: the parser ignores spaces and brackets around a name.
print(ast.dump(ast.parse("x=(a)+1")) == ast.dump(ast.parse("x = a + 1")))
Output
def area(w, h):
    # The comment is part of the source text.
    return w * h
first line in the file: 5
tree to text: ['def area(w, h):', '    return w * h']
True
  • Verdict: native. CPython keeps the file name and the first line of each function in its code object, and inspect.getsource reads the lines from the file again, so the comment is still there. The tree from ast has no comments, so ast.unparse gives the code without it. Two texts with different spacing and brackets parse to the same tree.
#include <iostream>
#include <source_location>
#include <string_view>

// A default argument of source_location::current() takes the location of the call.
void check(bool ok, std::string_view what,
           std::source_location loc = std::source_location::current()) {
    std::cout << "line " << loc.line() << ": " << what << " is " << std::boolalpha << ok << '\n';
}

int main() {
    int x = -2;
    check(x > 0, "x > 0");
    check(x * x == 4, "x * x == 4");

    // A raw string literal holds source text with quotes and backslashes as they are.
    std::string_view code = R"(printf("a\tb\n");)";
    std::cout << code << " has " << code.size() << " characters\n";
}
Output
line 13: x > 0 is false
line 14: x * x == 4 is true
printf("a\tb\n"); has 17 characters
  • Verdict: native. std::source_location::current() as a default argument takes the location of the call, not of the function, so the function needs no macro. Unlike a C macro, it cannot get the text of the argument, so the call passes the text too. A raw string literal keeps quotes and backslashes as they are written, which helps when a program holds source code of another language.
JavaGitHub
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HexFormat;
import javax.tools.ToolProvider;

public class Main {
    public static void main(String[] args) throws Exception {
        // The program writes source text to a file and calls the compiler on it.
        Path dir = Files.createTempDirectory("src");
        Path src = dir.resolve("Hello.java");
        Files.writeString(src, "public class Hello { static int answer() { return 6 * 7; } }\n");
        int rc = ToolProvider.getSystemJavaCompiler().run(null, null, null, src.toString());
        System.out.println("compiler exit code: " + rc);

        // The compiler writes a class file of bytecode, which starts with the bytes CAFEBABE.
        byte[] cls = Files.readAllBytes(dir.resolve("Hello.class"));
        System.out.println("class file starts with: " + HexFormat.of().formatHex(cls, 0, 4));

        // A stack trace maps running code back to a file and a line of source.
        StackTraceElement here = new Throwable().getStackTrace()[0];
        System.out.println("this line: " + here.getFileName() + ":" + here.getLineNumber());
        for (Path p : new Path[] {dir.resolve("Hello.class"), src, dir}) Files.delete(p);
    }
}
Output
compiler exit code: 0
class file starts with: cafebabe
this line: Main.java:20
  • Verdict: native. The program writes a compilation unit to a file and calls the system Java compiler through javax.tools, which returns 0 when the compile succeeds. The output is a class file of bytecode that starts with the magic number CAFEBABE. The compiler also writes a line number table, so a stack trace names the source file and the line of the running code.
#include <stdio.h>

/* #e turns the macro argument into a string literal, and __LINE__ is the line of the use. */
#define CHECK(e) printf("line %d in %s: %s is %s\n", __LINE__, __func__, #e, (e) ? "true" : "false")

/* Text that the preprocessor joins: a backslash at the end of a line continues the line. */
#define AREA(w, h) \
    ((w) * (h))

int main(void) {
    int x = -2;
    CHECK(x > 0);
    CHECK(x * x == 4);
    printf("AREA(2 + 1, 4) = %d\n", AREA(2 + 1, 4));
    printf("adjacent " "string " "literals join: %s\n", "yes");
    return 0;
}
Output
line 12 in main: x > 0 is false
line 13 in main: x * x == 4 is true
AREA(2 + 1, 4) = 12
adjacent string literals join: yes
  • Verdict: native. The preprocessor works on the source text before the compiler sees it. #e turns the macro argument into a string literal, __LINE__ gives the line of the use and __func__ gives the name of the function, as the standard assert does. A backslash at the end of a line joins it to the next line, and adjacent string literals join into one.
using System.Runtime.CompilerServices;

int x = -2;
Check(x > 0);
Check(x * x == 4);
Check(x   <   0);

// The compiler puts the text of the argument and the line of the call into each call.
static void Check(bool ok,
    [CallerArgumentExpression(nameof(ok))] string text = "",
    [CallerLineNumber] int line = 0)
{
    Console.WriteLine($"line {line}: {text} is {(ok ? "true" : "false")}");
}
Output
line 4: x > 0 is false
line 5: x * x == 4 is true
line 6: x   <   0 is true
  • Verdict: native. The compiler fills the optional parameters at each call: CallerArgumentExpression gets the source text of the argument and CallerLineNumber gets the line. The text is exactly what the programmer wrote, spaces included, as the third call shows. Assertion libraries use this to print the failed condition without a macro.
JavaScriptGitHub
function area(w, h) {
  // The engine keeps the exact source text.
  return w * h;
}
console.log(area.toString());

// new Function compiles source text when the program runs.
const double = new Function("x", "return x * 2;");
console.log(double(21));
console.log(double.toString().split("\n").join(" | "));

console.log(Math.max.toString());
Output
function area(w, h) {
  // The engine keeps the exact source text.
  return w * h;
}
42
function anonymous(x | ) { | return x * 2; | }
function max() { [native code] }
  • Verdict: native. A function's toString gives the exact text that defined it, with its comment and its layout. new Function compiles source text while the program runs, and the engine wraps the body in a function named anonymous. A built-in function such as Math.max has no JavaScript source, so its text says [native code].
package main

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

func main() {
	src := "package p\nfunc area( w,h int )int{return w*h // product\n}\n"

	// gofmt rewrites the text into the one standard layout.
	out, err := format.Source([]byte(src))
	if err != nil {
		panic(err)
	}
	fmt.Print(string(out))

	// The parser gives a tree, and each node knows its position in the text.
	fset := token.NewFileSet()
	f, err := parser.ParseFile(fset, "area.go", src, parser.ParseComments)
	if err != nil {
		panic(err)
	}
	ast.Inspect(f, func(n ast.Node) bool {
		if id, ok := n.(*ast.Ident); ok {
			fmt.Printf("%s at %s\n", id.Name, fset.Position(id.Pos()))
		}
		return true
	})
	fmt.Println("comments:", len(f.Comments))
}
Output
package p

func area(w, h int) int {
	return w * h // product
}
p at area.go:1:9
area at area.go:2:6
w at area.go:2:12
h at area.go:2:14
int at area.go:2:16
int at area.go:2:21
w at area.go:2:32
h at area.go:2:34
comments: 1
  • Verdict: native. The Go standard library contains the parser and the formatter of the language. format.Source prints messy source in the layout of gofmt and keeps the comment. parser.ParseFile builds the tree, and fset.Position turns the position of each identifier into a file, a line and a column, which is how Go tools report errors.
RustGitHub
macro_rules! check {
    ($e:expr) => {
        // stringify! turns the argument back into text.
        println!("line {}: {} is {}", line!(), stringify!($e), $e)
    };
}

fn main() {
    let x = -2;
    check!(x > 0);
    check!(x*x==4);
    println!("column of this call: {}", column!());
}
Output
line 10: x > 0 is false
line 11: x*x==4 is true
column of this call: 41
  • Verdict: native. The macro gets the expression as tokens, and stringify! turns them back into a string when the program compiles. line! and column! give the position of the macro call, so the program prints the source text and the line of each check with no cost at run time. The documentation of stringify! warns that the exact text of the result may change in future compilers.
  • Generated source code. Parser generators, protocol buffer compilers and code generators write source files from a description. The description is the real source, and the generated files are usually marked so that people do not edit them.
  • Transpilers and minifiers. TypeScript, Babel and minifiers turn one source text into another. A source map relates positions in the output to positions in the input.
  • Literate programming. Donald Knuth's literate programming, which he described in 1984, kept a program and its explanation in one document, and tools extracted the code and the typeset text from it.
  • Visual and structured languages. Scratch, spreadsheets and some industrial languages store a program as blocks or a tree, not as free text, and the editor prevents syntax errors.
  • Notebooks. A Jupyter notebook stores code cells with their output in one JSON file, so the source and the results of a run travel together.
  • Syntactic macros. Syntactic macros take source as tokens or trees and give new source that the compiler then reads.

Pitfalls

  • Encoding problems. A file saved in one encoding and read in another changes its strings and can break the compile. Save source as UTF-8 without a byte order mark unless the language needs something else. See UTF-8.
  • Invisible characters. Tabs mixed with spaces break the indentation of Python and Makefiles, and bidirectional control characters and look-alike letters can make code look different from what the compiler reads, as in the Trojan Source attacks of 2021.
  • Running text as code. eval, new Function and string building for SQL or shell commands turn data into source code, which lets an attacker inject code. See code injection.
  • Line numbers that do not match. Generated code, macros and minified bundles report lines in the output, not in the source that a person wrote, unless a source map or #line directive maps them back.
  • Editing generated files. A change to a generated file is lost the next time the generator runs. Change the input of the generator instead.
  • Relying on the text of a function. Function.prototype.toString and inspect.getsource fail for built-in functions and for code without a file, and minifiers change the text.

Cost

The size of source code drives the time to compile it, the time to read it and the number of defects in it. Compile time grows with the amount of text after macro expansion and header inclusion, which is why large C++ projects spend much of their build time parsing the same headers again, and why C++ modules and precompiled headers exist. Tokenizing and parsing are fast, often linear in the length of the text; type checking, optimization and code generation take most of the time of a compile. For people, the cost is reading: code is read many more times than it is written, so clear names, a standard layout and short functions reduce the cost of each change.

History

The first stored-program computers ran numbers in memory that programmers wrote by hand. Kathleen Booth wrote an assembly notation for the ARC computer in 1947, and David Wheeler's initial orders for the EDSAC, in 1949, read instructions written as letters and decimal numbers from paper tape and turned them into binary. From then on, the text that people wrote was different from the code that the machine ran. John Backus's team delivered the FORTRAN compiler in 1957, and the source of a program became formulas and statements on punched cards, one line per card.

Source moved from cards to files in time-sharing systems in the 1960s and 1970s. Marc Rochkind wrote SCCS at Bell Labs in 1972 to keep the history of each source file, the first in a line of version control systems that leads to Git. Richard Stallman started the GNU project in 1983 because vendors had stopped giving source code to users, and the Open Source Definition of 1998 made access to the preferred form of the source a term of open source licences.

References

  1. The Open Source Definition, Open Source Initiative, 2. Source Code
  2. Lexical analysis, The Python Language Reference, Encoding declarations
  3. tokenize, Tokenizer for Python source, Python documentation, Introduction
  4. inspect, Inspect live objects, Python documentation, getsource
  5. Function.prototype.toString(), MDN Web Docs, Description
  6. Class StackTraceElement, Java SE 25 API documentation, getLineNumber()
  7. Determine caller information using attributes interpreted by the C# compiler, Microsoft Learn, Argument expressions
  8. Package parser, Go standard library documentation, Overview
  9. Macro stringify, Rust standard library documentation, Description
  10. Replacing text macros, C reference, cppreference.com, Predefined macros
  11. std::source_location, C++ reference, cppreference.com, Description

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/3CE4MV/text.yaml