A computer
programming language
A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language.
The description of a programming ...
is said to adhere to the off-side rule of
syntax
In linguistics, syntax () is the study of how words and morphemes combine to form larger units such as phrases and sentences. Central concerns of syntax include word order, grammatical relations, hierarchical sentence structure ( constituency) ...
if
blocks in that language are expressed by their
indentation. The term was coined by
Peter Landin
Peter John Landin (5 June 1930 – 3 June 2009) was a British computer scientist. He was one of the first to realise that the lambda calculus could be used to model a programming language, an insight that is essential to the development of both ...
, possibly as a pun on the
offside rule in
association football
Association football, more commonly known as football or soccer, is a team sport played between two teams of 11 players who primarily use their feet to propel the ball around a rectangular field called a pitch. The objective of the game is ...
. This is contrasted with
free-form languages, notably
curly-bracket programming languages, where indentation has no computational meaning and
indent style is only a matter of
coding conventions and formatting.
Definition
Peter Landin
Peter John Landin (5 June 1930 – 3 June 2009) was a British computer scientist. He was one of the first to realise that the lambda calculus could be used to model a programming language, an insight that is essential to the development of both ...
, in his 1966 article "
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
Python may refer to:
Snakes
* Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia
** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia
* Python (mythology), a mythical serpent
Computing
* Python (pro ...
. The colons are part of the Python language syntax for readability; they are not needed to implement the off-side rule.
In Python, the rule is taken to define the boundaries of statements rather than declarations.
def is_even(a):
"""Determine whether number 'a' is even."""
if a % 2 0:
print('Even!')
return True
print('Odd!')
return False
Python also suspends the off-side rule within brackets. A statement within brackets continues until its brackets match (or mismatch):
In this
dictionary
A dictionary is a listing of lexemes from the lexicon of one or more specific languages, often arranged alphabetically (or by radical and stroke for ideographic languages), which may include information on definitions, usage, etymologies ...
, the keys are indented, and a list is split between four lines.
Implementation
The off-side rule can be implemented in the
lexical analysis phase, as in
Python
Python may refer to:
Snakes
* Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia
** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia
* Python (mythology), a mythical serpent
Computing
* Python (pro ...
, where increasing the indenting results in the lexer outputting an
INDENT
token, and decreasing the indenting results in the lexer outputting a
DEDENT
token. These tokens correspond to the opening 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 indent level, and thus can detect changes in indentation when this changes, and thus the lexical
grammar
In linguistics, the grammar of a natural language is its set of structure, structural constraints on speakers' or writers' composition of clause (linguistics), clauses, phrases, and words. The term can also refer to the study of such constraint ...
is not
context-free:
INDENT
and
DEDENT
depend on the contextual information of the prior indent level.
Alternatives
The primary alternative to delimiting blocks by indenting, popularized by broad use and influence of the language
C, is to ignore
whitespace characters and mark blocks explicitly with
curly bracket
A bracket is either of two tall fore- or back-facing punctuation marks commonly used to isolate a segment of text or data from its surroundings. Typically deployed in symmetric pairs, an individual bracket may be identified as a 'left' or 'r ...
s (i.e.,
) or some other delimiter. While this allows for more formatting freedom – a developer might choose not to indent small pieces of code like the
break and continue statements – sloppily indented code might lead the reader astray, such as the
goto fail bug.
Lisp
A lisp is a speech impairment in which a person misarticulates sibilants (, , , , , , , ). These misarticulations often result in unclear speech.
Types
* A frontal lisp occurs when the tongue is placed anterior to the target. Interdental lisping ...
and other
S-expression-based languages do not differentiate statements from expressions, and parentheses are enough to control the scoping of all statements within the language. As in curly bracket languages, whitespace is mostly ignored by the reader (i.e., the read function). Whitespace is used to separate tokens. The explicit structure of Lisp code allows automatic indenting, to form a visual cue for human readers.
Another alternative is for each block to begin and end with explicit keywords. For example, in
ALGOL 60
ALGOL 60 (short for ''Algorithmic Language 1960'') is a member of the ALGOL family of computer programming languages. It followed on from ALGOL 58 which had introduced code blocks and the begin and end pairs for delimiting them, representing a k ...
and its descendant
Pascal
Pascal, Pascal's or PASCAL may refer to:
People and fictional characters
* Pascal (given name), including a list of people with the name
* Pascal (surname), including a list of people and fictional characters with the name
** Blaise Pascal, Fren ...
, blocks start with
keyword
Keyword may refer to:
Computing
* Keyword (Internet search), a word or phrase typically used by bloggers or online content creator to rank a web page on a particular topic
* Index term, a term used as a keyword to documents in an information syste ...
begin
and end with keyword
end
. In some languages (but not Pascal), this means that newlines ''are'' important (unlike in curly brace languages), but the indentation is not. In
BASIC
BASIC (Beginners' All-purpose Symbolic Instruction Code) is a family of general-purpose, high-level programming languages designed for ease of use. The original version was created by John G. Kemeny and Thomas E. Kurtz at Dartmouth College ...
and
Fortran, blocks begin with the block name (such as
IF
) and end with the block name prepended with
END
(e.g.,
END IF
). In
Fortran, each and every block can also have its own unique block name, which adds another level of explicitness to lengthy code.
ALGOL 68 and the
Bourne shell
The Bourne shell (sh) is a Shell (computing), shell Command-line interface#Command-line interpreter, command-line interpreter for computer operating systems.
The Bourne shell was the default Unix shell, shell for Version 7 Unix. Unix-like syste ...
(sh, and
bash
Bash or BASH may refer to:
Arts and entertainment
* ''Bash!'' (Rockapella album), 1992
* ''Bash!'' (Dave Bailey album), 1961
* '' Bash: Latter-Day Plays'', a dramatic triptych
* ''BASH!'' (role-playing game), a 2005 superhero game
* "Bash" ('' ...
) are similar, but the end of the block is usually given by the name of the block written backward (e.g.,
case
starts a
switch statement
In computer programming languages, a switch statement is a type of selection control mechanism used to allow the value of a variable or expression to change the control flow of program execution via search and map.
Switch statements function some ...
and it spans until the matching
esac
; similarly
conditionals
Conditional (if then) may refer to:
*Causal conditional, if X then Y, where X is a cause of Y
*Conditional probability, the probability of an event A given that another event B has occurred
*Conditional proof, in logic: a proof that asserts a co ...
if
...
then
...
elif... else...">code>elif...[else
...fi
or for loop">''for'' loops
for
...
do
...
od
in ALGOL68 or
for
...
do
...
done
in bash).
An interesting variant of this occurs in Modula-2, a Pascal-like language which does away with the difference between one and multiline blocks. This allows the block opener (
or
END
). It also fixes dangling else. Custom is for the
end
token to be placed on the same indent level as the rest of the block, giving a blockstructure that is very readable.
One advantage to the
Fortran approach is that it improves readability of long, nested, or otherwise complex code. A group of outdents or closing brackets alone provides no contextual cues as to which blocks are being closed, necessitating backtracking, and closer scrutiny while
debugging
In computer programming and software development, debugging is the process of finding and resolving '' bugs'' (defects or problems that prevent correct operation) within computer programs, software, or systems.
Debugging tactics can involve in ...
. Further, languages that allow a suffix for END-like keywords further improve such cues, such as
continue
versus
continue for x
. However, modern
source code editors often provide visual indicators, such as
syntax highlighting, and features such as
code folding to assist with these drawbacks.
Productivity
In the language
Scala, early versions allowed curly braces only. Scala 3 added an option to use indenting to structure blocks. Designer Martin Odersky said that this improves productivity overall by 10%, turns out to be the most productive change introduced in Scala 3, and advises its use.
Off-side rule languages
Programming languages
*
ABC
ABC are the first three letters of the Latin script known as the alphabet.
ABC or abc may also refer to:
Arts, entertainment, and media Broadcasting
* American Broadcasting Company, a commercial U.S. TV broadcaster
** Disney–ABC Television ...
*
Boo
* BuddyScript
*
Cobra
*
CoffeeScript
* Converge
*
Curry
A curry is a dish with a sauce seasoned with spices, mainly associated with South Asian cuisine. In southern India, leaves from the curry tree may be included.
There are many varieties of curry. The choice of spices for each dish in tradit ...
*
Elm
Elms are deciduous and semi-deciduous trees comprising the flowering plant genus ''Ulmus'' in the plant family Ulmaceae. They are distributed over most of the Northern Hemisphere, inhabiting the temperate and tropical-montane regions of North ...
*
F# (in early versions, when
#light
is specified; in later versions when
#light "off"
is not)
*
Genie
*
GDScript (Godot Engine)
*
Haskell (only for
where
,
let
,
do
, or
case ... of
clauses when braces are omitted)
*
Inform 7
Inform is a programming language and design system for interactive fiction originally created in 1993 by Graham Nelson. Inform can generate programs designed for the Z-code or Glulx virtual machines. Versions 1 through 5 were released between ...
*
ISWIM, the abstract language that introduced the rule
*
LiveScript
*
Miranda
* MoonScript
*
Nemerle
Nemerle is a general-purpose, high-level, statically typed programming language designed for platforms using the Common Language Infrastructure ( .NET/Mono). It offers functional, object-oriented, aspect-oriented, reflective and imperative featu ...
, optional mode
*
Nim
Nim is a mathematical two player game.
Nim or NIM may also refer to:
* Nim (programming language)
* Nim Chimpsky, a signing chimpanzee Acronyms
* Network Installation Manager, an IBM framework
* Nuclear Instrumentation Module
* Negative index met ...
*
occam
*
PROMAL
PROMAL (PROgrammer's Microapplication Language) is a structured programming language from Systems Management Associates for MS-DOS, Commodore 64, and Apple II. PROMAL features simple syntax, no line numbers, long variable names, functions and proce ...
*
Python
Python may refer to:
Snakes
* Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia
** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia
* Python (mythology), a mythical serpent
Computing
* Python (pro ...
*
Scala, optional mode
*
Scheme A scheme is a systematic plan for the implementation of a certain idea.
Scheme or schemer may refer to:
Arts and entertainment
* ''The Scheme'' (TV series), a BBC Scotland documentary series
* The Scheme (band), an English pop band
* ''The Schem ...
, when using one of several
Scheme Requests for Implementations, the latest of which i
SRFI 119*
Spin
Spin or spinning most often refers to:
* Spinning (textiles), the creation of yarn or thread by twisting fibers together, traditionally by hand spinning
* Spin, the rotation of an object around a central axis
* Spin (propaganda), an intentionally b ...
* Woma
*
XL
Other languages
*
Haml
*
Make
Make or MAKE may refer to:
*Make (magazine), a tech DIY periodical
*Make (software), a software build tool
*Make, Botswana, in the Kalahari Desert
*Make Architects
Make Architects is an international architecture practice headquartered in London ...
(build tool: tabs introduce commands in Make rules)
*
reStructuredTextreStructuredText Markup Specification – Indentation
/ref>
* Sass
Sass, Saß or SASS may refer to:
SASS
* M110 Semi-Automatic Sniper System (or M110 SASS)
* Safe Amplification Site Society, a non-profit organization that promotes music and the arts within Vancouver, British Columbia, Canada
* Shanghai Academ ...
* Stylus
A stylus (plural styli or styluses) is a writing utensil or a small tool for some other form of marking or shaping, for example, in pottery. It can also be a computer accessory that is used to assist in navigating or providing more precision w ...
* YAML
YAML ( and ) (''see '') is a human-readable data-serialization language. It is commonly used for configuration files and in applications where data is being stored or transmitted. YAML targets many of the same communications applications as Exte ...
* Pug (formerly Jade), see Comparison of web template engines
The following table lists the various web template engines used in Web template systems and a brief rundown of their features.
See also
* Template processor
* Web template system
A web template system in web publishing lets web designers ...
See also
*
* Prettyprint
References
{{Types of programming languages
Programming language topics
Articles with example Python (programming language) code