RE: monic part 5: writing C programs on the calculator
(02-01-2021 06:36 AM)F-73P Wrote: [snip]
EDIT: Thank you to Jonathan Busby for translating the "C-" BNF grammar above into an ISO/IEC 14977 "standard" (see the Wikipedia article) EBNF grammar, which I will use to write the "C-" parser:
Code:
program = declaration-list ;
declaration-list = { declaration } , declaration ;
declaration = var-declaration , fun-declaration ;
var-declaration = type-specifier , ID , [ "[" NUM "]" ] , ";" ;
type-specifier = "int" | "void" ;
fun-declaration = type-specifier , ID , "(" , params , ")" , compound-stmt ;
params = ( { param , "," } , param ) | "void" ;
param = type-specifier , ID [ "[" , "]" ] ;
compound-stmt = "{" , local-declarations , statement-list , "}" ;
local-declarations = { var-declaration } ;
statement-list = { statement } ;
statement = expression-stmt | compound-stmt | selection-stmt | iteration-stmt | return-stmt ;
expression-stmt = [ expression ] , ";" ;
selection-stmt = if , "(" , expression , ")" , statement , [ "else" , statement ] ;
iteration-stmt = while , "(" , expression , ")" , statement ;
return-stmt = "return" , [ expression ] , ";" ;
expression = { var , "=" } , simple-expression ;
simple-expression = { additive-expression , relop } , additive-expression ;
relop = "<=" | "<" | ">" | ">=" | "==" | "!=" ;
additive-expression = { term , addop } , term ;
addop = "+" | "-" ;
term = { factor , mulop } , factor ;
mulop = "*" | "/" ;
factor = "(" , expression , ")" | var | call | NUM ;
call = ID , "(" , args , ")" ;
args = [ { expression , "," } , expression ] ;
Note that the above EBNF grammar has a slight glitch, which is my fault. I accidentally incorrectly translated the "C-" BNF grammar arithmetic expressions into an EBNF grammar which made all the arithmetic expressions change from left-associative to right-associative. Here is the fix :
Code:
additive-expression = term , { addop , term } ;
term = factor , { mulop , factor } ;
Hope this doesn't cause any inconvenience or confusion.
N.B. Also, note that I assumed when writing the EBNF grammar that the Monic author would be implementing an LL(1) recursive descent parser, which reads its input from left to right and recurses in a depth-first manner. If this is not the case, then the EBNF grammar will need to be modified.
Regards,
Jonathan
Aeternitas modo est. Longa non est, paene nil.
|