Semantic Analysis/Exercise 01: Difference between revisions

From Wiki**3

< Semantic Analysis
(Redirected page to ist:Semantic Analysis/Exercise 01)
 
(3 intermediate revisions by the same user not shown)
Line 1: Line 1:
{{TOCright}}
#REDIRECT [[ist:Semantic Analysis/Exercise 01]]
== The Problem (in Portuguese) ==
Considere o analisador sintáctico da linguagem Simple (abaixo). Considere que as variáveis só podem ser utilizadas em expressões (tID ou tASSIGN) depois de declaradas (tLET); que variáveis com o mesmo nome não podem ser declaradas no mesmo bloco; e que os tokens tINT e tSTRING correspondem a  literais, respectivamente, dos tipos inteiro e cadeia de caracteres.
 
Traduza para C (visitor em C++: '''c_writer''') e valide semanticamente (visitor em C++: '''type_checker''') a árvore sintáctica abstracta, emitindo mensagens se forem detectados erros de validação semântica. Utilize as classes da CDK ('''cdk::symbol_table''', nós, etc.) na resolução do problema. Pode ser útil definir outras classes auxiliares de validação de tipos ('''symbol''', etc.). Nos visitors, implemente apenas os métodos process. O acesso às sub-árvores de nós binários faz-se através dos métodos left() e right() e às sub-árvores de nós unários através do método argument().
 
<text>
%token tSTART tBLOCK tEND tLET tPRINT tASSIGN
%token <str>    tID tSTRING
%token <i>      tINT
%type <node>    program block decl instr
%type <sequence> decls instrs
%right tASSIGN
%left '-'
%nonassoc tUMINUS
 
%%
program : tSTART block  { _compiler->ast(new ProgramNode(LINE, $2)); }
        ;
block  : tBLOCK decls instrs tEND { $$ = new BlockNode(LINE, $2, $3); }
        ;
decls  : decl                    { $$ = new Sequence(LINE, $1); }
        | decls decl              { $$ = new Sequence(LINE, $2, $1); }
        ;
decl    : tLET tID             { $$ = new DeclNode(LINE, $2); }
        ;
instrs  : instr                  { $$ = new Sequence(LINE, $1); }
        | instrs instr            { $$ = new Sequence(LINE, $2, $1); }
        ;
instr  :                ';'      { $$ = new Nil(LINE); }
        | block          ';'      { $$ = $1; }
        | tPRINT expr    ';'      { $$ = new PrintExpNode(LINE, $2); }
        | tPRINT tSTRING ';'      { $$ = new PrintStrNode(LINE, $2); }
        ;
expr    : tID                    { $$ = new Identifier(LINE, $1); }
        | tINT                    { $$ = new Integer(LINE, $1); }
        | tID tASSIGN expr        { $$ = new AssignmentNode(LINE, $1, $3); }
        | expr '-' expr          { $$ = new SUB(LINE, $1, $3); }
        | '-' expr %prec tUMINUS  { $$ = new NEG(LINE, $2); }
        ;
%%
</text>
 
== Solution ==
 
The solution is straightforward and very similar to that obtained for the [[Semantic Analysis/The Tiny language: semantic analysis example and C generation|the Tiny language]].
 
[[category:Compilers]]
[[category:Teaching]]

Latest revision as of 18:08, 6 December 2018