A-normal form
In computer science, A-normal form is an intermediate representation of programs in functional programming language compilers.
In ANF, all arguments to a function must be trivial. That is, evaluation of each argument must halt immediately.
ANF was introduced by Sabry and Felleisen in 1992 as a simpler alternative to continuation-passing style. Some of the advantages of using CPS as an intermediate representation are that optimizations are easier to perform on programs in CPS than in the source language, and that it is also easier for compilers to generate machine code for programs in CPS. Flanagan et al. showed how compilers could use ANF to achieve those same benefits with one source-level transformation; in contrast, for realistic compilers the CPS transformation typically involves additional phases, for example, to simplify CPS terms.
Grammar
Consider the pure λ-calculus with constants and let-expressions. The ANF restriction is enforced by- allowing only values, to serve as operands of function applications, and
- requiring that the result of a non-trivial expression be immediately captured in a let-bound variable.
| Original | ANF |
EXP ::= λ VAR. EXP | EXP EXP | VAR | CONST | let VAR = EXP in EXP CONST ::= f | g | h | EXP ::= VAL | let VAR = VAL in EXP | let VAR = VAL VAL in EXP VAL ::= VAR | CONST | λ VAR. EXP CONST ::= f | g | h |
Variants of ANF used in compilers or in research often allow records, tuples, multiargument functions, primitive operations and conditional expressions as well.
Examples
The expression:f,h)
is written in ANF as:
let v0 = g in
let v1 = h in
f
By imagining the sort of assembly this function call would produce:
;; let v0 = g
move x into args
call g
move result into temp
;; let v1 = h
move y into args
call h
move result into temp
;; f
move temp into args
move temp into args
call f
One can see the immediate similarities between ANF and the compiled form of a function; this property is a part of what makes ANF a good intermediate representation for optimisations in compilers.