You are on page 1of 2

Context Free Grammar (CFG)

Saturday, May 22, 2021 9:26 PM

A context-free grammar consisting of a finite set of grammar rules is a quadruple (N, T, P, S). CFG is
a set of recursive rules used to generate patterns of strings. A CFG can describe all regular
languages and more, but they cannot describe all possible languages.

Problem:
Write a CFG for the language whose specifications are given bellow:
• Consider the name of the language is ASL (A Sample Language).
• An ASL programme starts with the word Begin and finishes with the word End.
• The programme consists of declaration and statements.
• The declaration starts with variable_list followed by a colon and a type.
• Type should be integer or real or character or string.
• Statements should be assaignemt stmt, print stmt, input stmt, and if stmt.

A sample programme of language is given as follows:


Begin
a, b : integer
c : string
input c
input a, b
if (a < > b)
{
a=a+b
print c
print “Answer =” a
}
end

Programme → Begin declaration_list statement_list End


declaration_list → declaration | declaration_list
declaration → variable_list : type
variable_list → variable | variable_list , variable
variable → letter | variable alphanum
alphanum → letter | digit
letter → a | b | c …….. | z | A | B | C ………. | Z
digit → 0 | 1 | 2 | 3 ……….. | 9
type → integer | real | character | string
statement_list → statement | statement_list
statement → assign_stmt | print_stmt | input_stmt
assign_stmt → variable = expression

Compiler 2021 Page 1


statement → assign_stmt | print_stmt | input_stmt
assign_stmt → variable = expression
expression → expression | bin_op expr | unary_expr | (expr) | num | variable
bin_op → +|-|*|/
unary_op → -
num → digit | num
print_stmt → print print_list
print_list → print_item | print_list
print_item → expression | “text”
text → text_ch | text
text_ch → Any printable ASCII character
input_stmt → input variable_list
if_stmt → if (condition) statement | if (condition) statement else statement
condition → term relop term
term → variable | num
relop → < | > | <= | >= | < > | = =

Compiler 2021 Page 2

You might also like