Off-side rule
A computer programming language is said to adhere to the off-side rule if blocks in that language are expressed by their indentation. The term was coined by Peter J. Landin, after the offside law of football (soccer). This is contrasted with free-form languages, notably curly bracket programming languages, where indentation is not meaningful and indent style is only a matter of convention and code formatting.
Definition
Peter J. Landin, in an article called "The Next 700 Programming Languages", defined the off-side rule thus: "Any non-whitespace token to the left of the first such token on the previous line is taken to be the start of a new declaration."
Code examples
The following is an example of indentation blocks in Python.
Note that the colons are part of the Python language syntax for readability reasons, and are not necessary to implement the off-side rule.
Implementation
The off-side rule can be implemented in the lexical analysis phase, as in Python, where increasing the indentation results in the lexer outputting an INDENT token, and decreasing the indentation results in the lexer outputting a DEDENT token. These tokens correspond to the opening brace {
and closing brace }
in languages that use braces for blocks, and means that the phrase grammar does not depend on whether braces or indentation are used. This requires that the lexer hold state, namely the current indentation level, and thus can detect changes in indentation when this changes, and thus the lexical grammar is not context-free – INDENT/DEDENT depend on the contextual information of previous indentation level.