Theory of Computation & Computer Graphics β Introduction to Context Free Language, NEC licence examination syllabus (Nepal Engineering Council).
Backus-Naur Form (BNF)
The notation in which programming languages are actually specified.
π Where this lives: Open the specification of any programming language and you will find BNF. John Backus invented it for the ALGOL 60 report, and that report is widely regarded as the moment language specification became a rigorous discipline rather than a description in prose β ALGOL 60 was, in the famous phrase, "an improvement on nearly all of its successors". Every language standard since, from C to Rust, defines its syntax in a variant of this notation. Search "ALGOL 60 report Backus Naur Form language specification".
BNF and its extensions
BACKUS-NAUR FORM IS A NOTATION FOR WRITING CONTEXT-FREE
GRAMMARS. It contains no mathematical content beyond the CFG of
the earlier topic β IT IS A SYNTAX FOR GRAMMARS, adopted because
it is readable by engineers rather than only by theorists.
ββ THE NOTATION ββββββββββββββββββββββββββββββββββββββββββββ
<name> a NON-TERMINAL, written in angle brackets
::= "is defined as" β the production arrow
| alternation, exactly as in a CFG
literal text TERMINALS, often quoted
THE CORRESPONDENCE WITH THE FORMAL DEFINITION:
<expr> ::= <expr> "+" <term> | <term>
is precisely
E β E + T | T
A SMALL COMPLETE EXAMPLE β arithmetic expressions:
<expr> ::= <expr> "+" <term> | <expr> "-" <term>
| <term>
<term> ::= <term> "*" <factor> | <term> "/" <factor>
| <factor>
<factor> ::= "(" <expr> ")" | <number> | <ident>
<number> ::= <digit> | <number> <digit>
<digit> ::= "0" | "1" | "2" | "3" | "4"
| "5" | "6" | "7" | "8" | "9"
NOTE THAT THE SAME LAYERING FOR PRECEDENCE APPEARS, and for
the same reason: BNF inherits every property of the
underlying grammar, including ambiguity if the grammar is
ambiguous.
ββ THE WEAKNESS OF PLAIN BNF βββββββββββββββββββββββββββββββ
Repetition and optionality must be expressed by RECURSION,
which is verbose and obscures intent:
"a list of one or more items separated by commas"
<list> ::= <item> | <list> "," <item>
"an optional else clause"
<if> ::= "if" <cond> "then" <stmt>
| "if" <cond> "then" <stmt> "else" <stmt>
β the entire production must be duplicated.
ββ EXTENDED BNF (EBNF) βββββββββββββββββββββββββββββββββββββ
Adds three constructs, standardised as ISO 14977:
[ x ] OPTIONAL β zero or one occurrence
{ x } REPETITION β zero or more occurrences
( x | y ) GROUPING
THE SAME EXAMPLES BECOME:
<list> ::= <item> { "," <item> }
<if> ::= "if" <cond> "then" <stmt>
[ "else" <stmt> ]
DRAMATICALLY CLEARER, and note something important: THE
REPETITION FORM { x } IS NEITHER LEFT- NOR RIGHT-RECURSIVE,
SO IT EXPRESSES NO ASSOCIATIVITY. That is an advantage for
readability and a problem for meaning β the specification
must state associativity separately in prose, or the
implementer must decide.
SOME EBNF DIALECTS ADD:
x+ one or more
x? optional (same as [ x ])
x* zero or more (same as { x })
which is the regular-expression-influenced style used by
most modern parser generators.
IMPORTANT: EBNF ADDS NO EXPRESSIVE POWER. Every EBNF grammar
can be mechanically rewritten in plain BNF:
{ x } becomes <new> ::= Ξ΅ | <new> x
[ x ] becomes <new> ::= Ξ΅ | x
IT IS SYNTACTIC SUGAR β a genuine improvement in readability
with no change to the class of languages describable, which
remains exactly the context-free languages.
ββ AUGMENTED BNF (ABNF) ββββββββββββββββββββββββββββββββββββ
RFC 5234, used throughout the internet standards. Its
distinctive features:
rule = definition (no angle brackets)
n*m element repetition with explicit bounds
%x41 a character by hex code
"abc" case-INSENSITIVE literal by
default
EVERY IETF PROTOCOL β HTTP, SMTP, URIs, JSON β DEFINES ITS
SYNTAX IN ABNF, which makes it arguably the most widely
deployed grammar notation in existence.
ββ SYNTAX DIAGRAMS (RAILROAD DIAGRAMS) βββββββββββββββββββββ
A graphical equivalent of EBNF, in which a valid string is any
path traced from left to right:
Β· a straight line is a sequence
Β· a branch is an alternation
Β· a backward loop is a repetition
Used in the Pascal report and still common in database
documentation. THEY CONTAIN EXACTLY THE INFORMATION OF THE
EBNF THEY WERE DRAWN FROM β the choice is presentational.
BNF in practice
ββ WHAT BNF IS USED FOR ββββββββββββββββββββββββββββββββββββ
1. LANGUAGE SPECIFICATION. The syntax section of every
language standard.
2. INPUT TO PARSER GENERATORS. yacc, bison, ANTLR and their
relatives all consume a BNF-like grammar and emit a parser.
THE GRAMMAR IN THE SPECIFICATION AND THE GRAMMAR IN THE
COMPILER ARE OFTEN THE SAME FILE, which is how a standard
and its implementation are kept in step.
3. DOCUMENTATION β command-line syntax, configuration file
formats, protocol messages.
4. PROTOCOL DEFINITION, via ABNF as above.
5. TEST GENERATION β a grammar can be run BACKWARDS to
generate random valid inputs, which is the basis of
GRAMMAR-BASED FUZZING for finding parser bugs.
ββ A WORKED SPECIFICATION FRAGMENT βββββββββββββββββββββββββ
A small language's statement syntax in EBNF:
program = { declaration } , { statement } ;
declaration = type , identifier , [ "=" , expression ] ,
";" ;
type = "int" | "float" | "char" | "bool" ;
statement = assignment | if_stmt | while_stmt | block ;
block = "{" , { statement } , "}" ;
assignment = identifier , "=" , expression , ";" ;
if_stmt = "if" , "(" , expression , ")" , statement ,
[ "else" , statement ] ;
while_stmt = "while" , "(" , expression , ")" ,
statement ;
identifier = letter , { letter | digit | "_" } ;
READ THE if_stmt RULE CAREFULLY: the optional else is
written [ "else" , statement ] β WHICH IS EXACTLY THE
DANGLING ELSE AMBIGUITY OF THE PREVIOUS TOPIC, expressed
compactly. EBNF's brevity does not remove the ambiguity; it
hides it, which is a genuine hazard of the notation. The
specification must add a prose rule stating that else binds
to the nearest if.
ββ THE LIMITS OF BNF βββββββββββββββββββββββββββββββββββββββ
BNF DESCRIBES SYNTAX ONLY, and only context-free syntax. It
cannot express:
Β· "a variable must be declared before use"
Β· "the types on both sides of an assignment must match"
Β· "the number of arguments must match the declaration"
Β· "a break statement must be inside a loop"
Β· SEMANTICS OF ANY KIND β what a construct MEANS
THESE ARE STATED IN PROSE ALONGSIDE THE GRAMMAR IN EVERY
LANGUAGE STANDARD, and enforced by the compiler's semantic
analysis phase using a symbol table. THE DIVISION IS EXACTLY
THE ONE PREDICTED BY THE CHOMSKY HIERARCHY: the CFG handles
nesting, and everything requiring long-range matching is
pushed to a later phase.
FORMAL METHODS FOR THE REST:
ATTRIBUTE GRAMMARS attach ATTRIBUTES to grammar symbols and
SEMANTIC RULES to productions, so that type information
and symbol tables can be computed while parsing.
SYNTHESISED attributes flow UP the tree (a node's type
computed from its children); INHERITED attributes flow
DOWN (a declaration's scope passed to its uses).
DENOTATIONAL, OPERATIONAL and AXIOMATIC SEMANTICS are the
formal frameworks for specifying what programs MEAN, and
belong to the programming languages subject rather than
this one.
ββ THE SUMMARY βββββββββββββββββββββββββββββββββββββββββββββ
BNF IS A CFG IN ENGINEERS' NOTATION. Nothing about the
theory changes; what changes is that a language committee, a
compiler writer and a textbook author can all read the same
document. THAT IS NOT A SMALL ACHIEVEMENT β the ALGOL 60
report is remembered precisely because it was the first time
a language's syntax was stated without ambiguity of
description, and every subsequent language has followed it.
EBNF adds readability, not power β every { x } and [ x ] rewrites mechanically into plain BNF, so the class of describable languages is unchanged. But the convenience has a cost worth noticing: { x } is neither left- nor right-recursive, so it expresses no associativity at all, and the specification must state that separately.
π Go further: Grammars can be run backwards to generate rather than recognise, and this is the basis of grammar-based fuzzing. Feed a language's BNF to a generator, produce millions of syntactically valid but semantically bizarre programs, and throw them at a compiler to find crashes. This technique has found thousands of genuine bugs in production compilers β the Csmith tool alone reported over 400 previously unknown bugs in GCC and LLVM, several of which caused silently wrong code generation rather than crashes. The same document that specifies what a compiler must accept becomes the tool for testing whether it does. Search "grammar based fuzzing Csmith compiler bugs random program generation".
π‘ Exam angle: state that BNF is a notation for context-free grammars and give the correspondence between <A> ::= β¦ and A β β¦. Be able to write a small language fragment in BNF and to convert between BNF and the formal production notation. Know the three EBNF additions β [ optional ], { repetition }, ( grouping ) β and state clearly that EBNF adds no expressive power, showing how { x } rewrites recursively. Mention ABNF for internet standards and syntax/railroad diagrams. List what BNF cannot express and note that those constraints move to semantic analysis, formalised by attribute grammars with synthesised and inherited attributes.
Syllabus points
BNF notation and use
Create a free account to tick topics off, take notes as you read, watch the video lessons and get a day-by-day study plan built around your exam date.
Related topics in Introduction to Context Free Language