You are on page 1of 85

Construo de um compilador de MiniPascal para CLR

usando Objective Caml

Hugo Gustavo Valin Oliveira da Cunha


hugog.valin@gmail.com

Faculdade de Computao
Universidade Federal de Uberlndia

28 de novembro de 2017
Lista de Listagens

1.1 nano1.pas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.2 nano1.cs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.3 nano1.il . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.4 nano2.pas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.5 nano2.cs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.6 nano2.il . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.7 nano3.pas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.8 nano3.cs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.9 nano1.il . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.10 nano4.pas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.11 nano1.cs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.12 nano1.il . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.13 nano5.pas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
1.14 nano5.cs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
1.15 nano1.il . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
1.16 nano6.pas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
1.17 nano6.cs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
1.18 nano6.il . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
1.19 nano7.pas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
1.20 nano7.cs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
1.21 nano7.il . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
1.22 nano8.pas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
1.23 nano8.cs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
1.24 nano8.il . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
1.25 teste1_9.pas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
1.26 teste1_9.cs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
1.27 teste1_9.il . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
1.28 nano10.pas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
1.29 nano10.cs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
1.30 nano10.il . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
1.31 nano11.pas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
1.32 nano11.cs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
1.33 nano11.il . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
1.34 nano12.pas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
1.35 nano12.cs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
1.36 nano12.il . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
1.37 micro01.pas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
1.38 micro01.cs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
1.39 micro01.il . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
1.40 micro02.pas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

2
1.41 micro02.cs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
1.42 micro02.il . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
1.43 micro03.pas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
1.44 micro03.cs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
1.45 micro03.il . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
1.46 micro04.pas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
1.47 micro04.cs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
1.48 micro04.il . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
1.49 micro05.pas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
1.50 micro05.cs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
1.51 micro05.il . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
1.52 micro06.pas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
1.53 micro06.cs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
1.54 micro06.il . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
1.55 micro07.pas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
1.56 micro02.cs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
1.57 micro07.il . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
1.58 micro08.pas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
1.59 micro08.cs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
1.60 micro08.il . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
1.61 micro09.pas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
1.62 micro09.cs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
1.63 micro09.il . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
1.64 micro10.pas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
1.65 micro10.cs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
1.66 micro10.il . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
1.67 micro11.pas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
1.68 micro11.cs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
1.69 micro11.il . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
2.1 lexico.mll . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
3.1 sintatico.mly . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
3.2 ast.ml . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
3.3 tast.ml . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
4.1 sast.ml . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
4.2 semantico.ml . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
5.1 interprete.ml . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
Sumrio

1 Introduo 5
1.1 Linha de comando . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.2 Linguagem Assembly . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.3 Cdigos de programas em Pascal . . . . . . . . . . . . . . . . . . . . . . . . 8

2 Analisador Lxico 60

3 Analisador Sinttico 63

4 Analisador Semntico 69

5 Interprete 78

4
Captulo 1

Introduo

A Common Language Runtime (CLR) o componente de mquina virtual da plata-


forma .NET da Microsoft que gerencia a execuo de programas .NET. Um processo co-
nhecido como compilao just-in-time (JIT) converte o cdigo compilado em linguagem e
mquina que a CPU do computador executa. A CLR fornece servios adicionais, incluindo
gerenciamento de memria, segurana de tipagem, tratamento de exceo, garbage colec-
tor, gerenciamento de thread e segurana. A CLR implementa o Virtual Exection System
(VES), como definido no padro da infraestrutura de linguagem comum (CLI), inicialmente
desenvolvida pela Microsoft. Um padro pblico define a especificao da infraestrutura de
linguagem comum.

A especificao do CLI permite que rodemos aplicaes escritas em uma linguagem de


alto nvel em diferentes sistemas sem a necessidade de se reescrever as aplicaes levando em
conta as especificaes tcnicas de cada um. Alm disso o CLI descreve o cdigo exeutvel e
o ambiente de execuo que forma o ncleo do Framework .NET da Microsoft, do MONO e
Portable.NET sendo os dois ultimo implementaes gratuitas e de cdigo aberto da mesma.
A Common Languagem Runtime a implementao da CLI peloa Microsoft, isto , uma
mquina virtual que segue o padro internacional para a criao e execuo de ambiente de
desenvolvimento.

1.1 Linha de comando

Para essa primeira parte do projeto utilizei os seguintes componentes:

Sistema Operacional Linux Desktop 4.10.0-32-generic 36 16.04.1-Ubuntu i686 i686 i686


GNU/Linux.

Mono JIT compiler version 4.2.1 (Debian 4.2.1.102+dfsg2-7ubuntu4) Copyright (C)


2002-2014 Novell, Inc, Xamarin Inc and Contributors.

Linguagem de programao interpretada, multi-paragdima, C, desenvolvida pela Mi-


crosoft como parta da plataforma .NET.

5
1.2

Para fazer a instalao do sistema utilizei o seguintes comandos no terminal dentro do


sistema Linux:
> sudo apt-get install mono-runtime monodevelop

Para fazer a compilao do cdigo fonte para o arquivo executvel usado o seguinte
comando no terminal Linux:
> mcs /out:nomeExecutavel.exe arquivoCodigoFonte.cs

J para fazer o desassembly utilizei o seguinte comando:


> monodis --output=arquivoCodigoAssembly.il nomeExecutavel.exe

1.2 Linguagem Assembly

O assembly da plataforma CLR um conjuntode instrues baseado em pilha e orientado


a objetos que so listadas a seguir:

add: retira os dois elementos do topo da pilha e coloca o resultado no topo.

add.ovf: retira os dois elementos do topo da pilha e coloca o resultado no topo, verifi-
cando overflow.

and: retira os dois elementos do topo da pilha, faz a operao and bit a bit e coloca o
resultado no topo da pilha.

arglist: retorna o identificador da lista de argumentos para o mtodo atual.

beq pula para o endereo se os elementos topo da pilha so iguais

bge: pula para o endereo se o topo da pilha menor que o seu antecesso.

bge.un. : igual ao bge, mas a comparao feita sem sinal.

bgt: pular para o endereo se o segundo elemento da pilha maior que o topo.

ble: pula para o endereo se o topo menor ou igual ao seu antecessor.

ble.un: igual ao ble, mas a comparao feita sem sinal.

blt : pula pra o endereo se o o topo menor que seu antecessor.

blt.un: igual ao blt, mas a comparao feita sem sinal.

bne: pula para o endereo se o topo no for igual ou no ordenada.

bne.un: igual ao bne, mas a comparao feita sem sinal.

br: salto incondicional

break: instruo de breakpoint


1.2

brfalse: pula para o endereco se falso, nulo, ou zero.

brtrue: pula para o endereo se verdadeiro, diferente de zero, ou no nulo.

call: chamada de mtodo.

calli: chamada de mtodo indireto.

ceq: compara se igual

cgt: compara se maior que.

cgt.un: igual ao cgt, mas a comparao feita sem sinal.

clt: compara se menor que

clt.un igual ao clt, mas a comparao feita sem sinal.

conv : converso de dados.

conv.ovf: igual ao conv, mas com sinalizao de overflow.

conv.ovf.un: igual ao conv.of, mas a comparao feita sem sinal.

cpbllc: copia dados da memria para a memria.

div: diviso.

div.un: igual ao div, mas a comparao feita sem sinal.

dup: duplica o valor da pilha.

jmp: pula para um mtodo.

jmpi: pular para um ponteiro de mtodo.

ldarg: carrega um argumento na pilha.

ldarga: carrega um argumento a partir de um endereo.

ldc: carrega uma constante numrica.

Idelem: carrega um elemento do vetor no index para topo da pilha.

Idelema: carrega o endereco do vetor na posicao index na pilha.

Idstr: poe no topo da pilha a string.

mul: multiplica os dois valores de cima da pilha e empilha o resultado.

mul.ovf: igual ao mul, mas feita sinalizao de overflow.

neg: altera o sinal do elemento do topo da pilha.

newarr: cria um array com o tipo definido onde seu tamanho est no topo da pilha.

not: inverte os bits do elemento do topo da pilha.

r: faz um ou lgico bit a bit dos elementos do topo, empilhando o resultado.


1.3

pop: desempilha a pilha.

rem: computa o resto da diviso do elemento abaixo do topo, pelo topo, e empilha o
resultado.

rem.un: igual ao rem, mas a comparao feita sem sinal.

shl: deslocamento de bits a esquerda.

shr: deslocamento de bits a direita.

starg: retira o elemento do topo da pilha e coloca em um argumento.

sizeof: carrega o tamanho em bits do topo na pilha.

sub: subtrai o segundo valor do primeiro e empilha o resultado.

sub.ovf: igual ao sub, mas com a sinalizao de overflow.

xor: executaa a operao XOR(bit a bit) entre dois elementos da pilha colocando seu
resultado na mesma.

1.3 Cdigos de programas em Pascal

Para introduzir a listagem do cdigo no documento existem pelo menos duas formas
bsicas, ambas usando o pacote listings:

1. Nano1
Listagem 1.1: nano1.pas
1 PROGRAM NANO1;
2 BEGIN
3 END.

Listagem 1.2: nano1.cs


1 class nano1 {
2 public static void Main(){
3 }
4 }

Listagem 1.3: nano1.il


1 .assembly extern mscorlib
2 {
3 .ver 4:0:0:0
4 .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4..
5 }
6 .assembly 'nano1'
7 {
8 .custom instance void class [mscorlib]System.Runtime.
CompilerServices.RuntimeCompatibilityAttribute::'.ctor'() = (
1.3

9 01 00 01 00 54 02 16 57 72 61 70 4E 6F 6E 45 78 // ....T..
WrapNonEx
10 63 65 70 74 69 6F 6E 54 68 72 6F 77 73 01 ) //
ceptionThrows.
11
12 .hash algorithm 0x00008004
13 .ver 0:0:0:0
14 }
15 .module nano1.exe // GUID = {5ED09DB1-FA20-4D85-8F38-87FF39FA9BE5}
16

17
18 .class private auto ansi beforefieldinit nano1
19 extends [mscorlib]System.Object
20 {
21
22 // method line 1
23 .method public hidebysig specialname rtspecialname
24 instance default void '.ctor' () cil managed
25 {
26 // Method begins at RVA 0x2050
27 // Code size 7 (0x7)
28 .maxstack 8
29 IL_0000: ldarg.0
30 IL_0001: call instance void object::'.ctor'()
31 IL_0006: ret
32 } // end of method nano1::.ctor
33
34 // method line 2
35 .method public static hidebysig
36 default void Main () cil managed
37 {
38 // Method begins at RVA 0x2058
39 .entrypoint
40 // Code size 1 (0x1)
41 .maxstack 8
42 IL_0000: ret
43 } // end of method nano1::Main
44
45 } // end of class nano1

2. Nano2
Listagem 1.4: nano2.pas
1 PROGRAM NANO2;
2 VAR
3 n: integer;
4
5 BEGIN
6 END.

Listagem 1.5: nano2.cs


1 class nano2 {
2 public static void Main(){
3 int n;
4 }
5 }
1.3

Listagem 1.6: nano2.il


1 .assembly extern mscorlib
2 {
3 .ver 4:0:0:0
4 .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4..
5 }
6 .assembly 'nano2'
7 {
8 .custom instance void class [mscorlib]System.Runtime.
CompilerServices.RuntimeCompatibilityAttribute::'.ctor'() = (
9 01 00 01 00 54 02 16 57 72 61 70 4E 6F 6E 45 78 // ....T..
WrapNonEx
10 63 65 70 74 69 6F 6E 54 68 72 6F 77 73 01 ) //
ceptionThrows.
11

12 .hash algorithm 0x00008004


13 .ver 0:0:0:0
14 }
15 .module nano2.exe // GUID = {5EE07A5F-D6EC-4659-8DB3-6EA69D6FF499}
16
17

18 .class private auto ansi beforefieldinit nano2


19 extends [mscorlib]System.Object
20 {
21
22 // method line 1
23 .method public hidebysig specialname rtspecialname
24 instance default void '.ctor' () cil managed
25 {
26 // Method begins at RVA 0x2050
27 // Code size 7 (0x7)
28 .maxstack 8
29 IL_0000: ldarg.0
30 IL_0001: call instance void object::'.ctor'()
31 IL_0006: ret
32 } // end of method nano2::.ctor
33
34 // method line 2
35 .method public static hidebysig
36 default void Main () cil managed
37 {
38 // Method begins at RVA 0x2058
39 .entrypoint
40 // Code size 1 (0x1)
41 .maxstack 0
42 .locals init (
43 int32 V_0)
44 IL_0000: ret
45 } // end of method nano2::Main
46
47 } // end of class nano2

3. Nano3
Listagem 1.7: nano3.pas
1 PROGRAM NANO3;
2 VAR
3 n: integer;
1.3

4
5 BEGIN
6 n := 1;
7 END.

Listagem 1.8: nano3.cs


1 class nano3 {
2 public static void Main(){
3 int n;
4 n = 1;
5 }
6 }

Listagem 1.9: nano1.il


1 .assembly extern mscorlib
2 {
3 .ver 4:0:0:0
4 .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4..
5 }
6 .assembly 'nano3'
7 {
8 .custom instance void class [mscorlib]System.Runtime.
CompilerServices.RuntimeCompatibilityAttribute::'.ctor'() = (
9 01 00 01 00 54 02 16 57 72 61 70 4E 6F 6E 45 78 // ....T..
WrapNonEx
10 63 65 70 74 69 6F 6E 54 68 72 6F 77 73 01 ) //
ceptionThrows.
11
12 .hash algorithm 0x00008004
13 .ver 0:0:0:0
14 }
15 .module nano3.exe // GUID = {F99E8C54-DFCD-4C5D-8EED-0AF7A1C379E0}
16
17
18 .class private auto ansi beforefieldinit nano3
19 extends [mscorlib]System.Object
20 {
21
22 // method line 1
23 .method public hidebysig specialname rtspecialname
24 instance default void '.ctor' () cil managed
25 {
26 // Method begins at RVA 0x2050
27 // Code size 7 (0x7)
28 .maxstack 8
29 IL_0000: ldarg.0
30 IL_0001: call instance void object::'.ctor'()
31 IL_0006: ret
32 } // end of method nano3::.ctor
33
34 // method line 2
35 .method public static hidebysig
36 default void Main () cil managed
37 {
38 // Method begins at RVA 0x2058
39 .entrypoint
40 // Code size 3 (0x3)
1.3

41 .maxstack 1
42 .locals init (
43 int32 V_0)
44 IL_0000: ldc.i4.1
45 IL_0001: stloc.0
46 IL_0002: ret
47 } // end of method nano3::Main
48
49 } // end of class nano3

4. Nano4
Listagem 1.10: nano4.pas
1 PROGRAM NANO4;
2 VAR
3 n: integer;
4
5 BEGIN
6 n := 1 + 2;
7 END.

Listagem 1.11: nano1.cs


1 class nano4 {
2 public static void Main(){
3 int n;
4 n = 1 + 2;
5 }
6 }

Listagem 1.12: nano1.il


1 .assembly extern mscorlib
2 {
3 .ver 4:0:0:0
4 .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4..
5 }
6 .assembly 'nano4'
7 {
8 .custom instance void class [mscorlib]System.Runtime.
CompilerServices.RuntimeCompatibilityAttribute::'.ctor'() = (
9 01 00 01 00 54 02 16 57 72 61 70 4E 6F 6E 45 78 // ....T..
WrapNonEx
10 63 65 70 74 69 6F 6E 54 68 72 6F 77 73 01 ) //
ceptionThrows.
11
12 .hash algorithm 0x00008004
13 .ver 0:0:0:0
14 }
15 .module nano4.exe // GUID = {5F14DDC1-9CCB-493A-8830-645816D38F8C}
16
17
18 .class private auto ansi beforefieldinit nano4
19 extends [mscorlib]System.Object
20 {
21
22 // method line 1
1.3

23 .method public hidebysig specialname rtspecialname


24 instance default void '.ctor' () cil managed
25 {
26 // Method begins at RVA 0x2050
27 // Code size 7 (0x7)
28 .maxstack 8
29 IL_0000: ldarg.0
30 IL_0001: call instance void object::'.ctor'()
31 IL_0006: ret
32 } // end of method nano4::.ctor
33
34 // method line 2
35 .method public static hidebysig
36 default void Main () cil managed
37 {
38 // Method begins at RVA 0x2058
39 .entrypoint
40 // Code size 3 (0x3)
41 .maxstack 1
42 .locals init (
43 int32 V_0)
44 IL_0000: ldc.i4.3
45 IL_0001: stloc.0
46 IL_0002: ret
47 } // end of method nano4::Main
48
49 } // end of class nano4

5. Nano5
Listagem 1.13: nano5.pas
1 PROGRAM NANO5;
2 VAR
3 n: integer;
4
5 BEGIN
6 n := 2;
7 write(n);
8 END.

Listagem 1.14: nano5.cs


1 using System;
2
3 class nano5 {
4 public static void Main(){
5 int n;
6 n = 2;
7 Console.Write(n);
8 }
9 }

Listagem 1.15: nano1.il


1 .assembly extern mscorlib
2 {
3 .ver 4:0:0:0
1.3

4 .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4..


5 }
6 .assembly 'nano5'
7 {
8 .custom instance void class [mscorlib]System.Runtime.
CompilerServices.RuntimeCompatibilityAttribute::'.ctor'() = (
9 01 00 01 00 54 02 16 57 72 61 70 4E 6F 6E 45 78 // ....T..
WrapNonEx
10 63 65 70 74 69 6F 6E 54 68 72 6F 77 73 01 ) //
ceptionThrows.
11
12 .hash algorithm 0x00008004
13 .ver 0:0:0:0
14 }
15 .module nano5.exe // GUID = {5C4F22FE-7630-4D87-80C5-32E6619B62E4}
16

17
18 .class private auto ansi beforefieldinit nano5
19 extends [mscorlib]System.Object
20 {
21
22 // method line 1
23 .method public hidebysig specialname rtspecialname
24 instance default void '.ctor' () cil managed
25 {
26 // Method begins at RVA 0x2050
27 // Code size 7 (0x7)
28 .maxstack 8
29 IL_0000: ldarg.0
30 IL_0001: call instance void object::'.ctor'()
31 IL_0006: ret
32 } // end of method nano5::.ctor
33
34 // method line 2
35 .method public static hidebysig
36 default void Main () cil managed
37 {
38 // Method begins at RVA 0x2058
39 .entrypoint
40 // Code size 9 (0x9)
41 .maxstack 1
42 .locals init (
43 int32 V_0)
44 IL_0000: ldc.i4.2
45 IL_0001: stloc.0
46 IL_0002: ldloc.0
47 IL_0003: call void class [mscorlib]System.Console::Write(int32)
48 IL_0008: ret
49 } // end of method nano5::Main
50
51 } // end of class nano5

6. Nano6
Listagem 1.16: nano6.pas
1 PROGRAM NANO6;
2 VAR
3 n: integer;
1.3

4
5 BEGIN
6 n := 1 - 2;
7 write(n);
8 END.

Listagem 1.17: nano6.cs


1 using System;
2

3 class nano5 {
4 public static void Main(){
5 int n;
6 n = 1 - 2;
7 Console.Write(n);
8 }
9 }

Listagem 1.18: nano6.il


1 .assembly extern mscorlib
2 {
3 .ver 4:0:0:0
4 .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4..
5 }
6 .assembly 'nano6'
7 {
8 .custom instance void class [mscorlib]System.Runtime.
CompilerServices.RuntimeCompatibilityAttribute::'.ctor'() = (
9 01 00 01 00 54 02 16 57 72 61 70 4E 6F 6E 45 78 // ....T..
WrapNonEx
10 63 65 70 74 69 6F 6E 54 68 72 6F 77 73 01 ) //
ceptionThrows.
11
12 .hash algorithm 0x00008004
13 .ver 0:0:0:0
14 }
15 .module nano6.exe // GUID = {F9105CC6-2B0A-4822-8D27-285E4054F305}
16

17
18 .class private auto ansi beforefieldinit nano5
19 extends [mscorlib]System.Object
20 {
21
22 // method line 1
23 .method public hidebysig specialname rtspecialname
24 instance default void '.ctor' () cil managed
25 {
26 // Method begins at RVA 0x2050
27 // Code size 7 (0x7)
28 .maxstack 8
29 IL_0000: ldarg.0
30 IL_0001: call instance void object::'.ctor'()
31 IL_0006: ret
32 } // end of method nano5::.ctor
33
34 // method line 2
35 .method public static hidebysig
36 default void Main () cil managed
1.3

37 {
38 // Method begins at RVA 0x2058
39 .entrypoint
40 // Code size 9 (0x9)
41 .maxstack 1
42 .locals init (
43 int32 V_0)
44 IL_0000: ldc.i4.m1
45 IL_0001: stloc.0
46 IL_0002: ldloc.0
47 IL_0003: call void class [mscorlib]System.Console::Write(int32)
48 IL_0008: ret
49 } // end of method nano5::Main
50
51 } // end of class nano5

7. Nano7
Listagem 1.19: nano7.pas
1 PROGRAM NANO7;
2 VAR
3 n: integer;
4
5 BEGIN
6 n := 1;
7 if ( n = 1) then
8 begin
9 write(n);
10 end;
11 END.

Listagem 1.20: nano7.cs


1 using System;
2
3 class nano7 {
4 public static void Main(){
5 int n;
6 n = 1;
7 if ( n == 1)
8 Console.Write(n);
9 }
10 }

Listagem 1.21: nano7.il


1 .assembly extern mscorlib
2 {
3 .ver 4:0:0:0
4 .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4..
5 }
6 .assembly 'nano7'
7 {
8 .custom instance void class [mscorlib]System.Runtime.
CompilerServices.RuntimeCompatibilityAttribute::'.ctor'() = (
9 01 00 01 00 54 02 16 57 72 61 70 4E 6F 6E 45 78 // ....T..
WrapNonEx
1.3

10 63 65 70 74 69 6F 6E 54 68 72 6F 77 73 01 ) //
ceptionThrows.
11
12 .hash algorithm 0x00008004
13 .ver 0:0:0:0
14 }
15 .module nano7.exe // GUID = {F3A7240D-AC0D-4B6E-A4F3-49D6B8F53EB8}
16
17
18 .class private auto ansi beforefieldinit nano7
19 extends [mscorlib]System.Object
20 {
21
22 // method line 1
23 .method public hidebysig specialname rtspecialname
24 instance default void '.ctor' () cil managed
25 {
26 // Method begins at RVA 0x2050
27 // Code size 7 (0x7)
28 .maxstack 8
29 IL_0000: ldarg.0
30 IL_0001: call instance void object::'.ctor'()
31 IL_0006: ret
32 } // end of method nano7::.ctor
33
34 // method line 2
35 .method public static hidebysig
36 default void Main () cil managed
37 {
38 // Method begins at RVA 0x2058
39 .entrypoint
40 // Code size 16 (0x10)
41 .maxstack 2
42 .locals init (
43 int32 V_0)
44 IL_0000: ldc.i4.1
45 IL_0001: stloc.0
46 IL_0002: ldloc.0
47 IL_0003: ldc.i4.1
48 IL_0004: bne.un IL_000f
49
50 IL_0009: ldloc.0
51 IL_000a: call void class [mscorlib]System.Console::Write(int32)
52 IL_000f: ret
53 } // end of method nano7::Main
54

55 } // end of class nano7

8. Nano8
Listagem 1.22: nano8.pas
1 PROGRAM NANO8;
2 VAR
3 n: integer;
4
5 BEGIN
6 n := 1;
7 if ( n = 1) then
1.3

8 begin
9 write(n);
10 end;
11 else
12 begin
13 write(0);
14 end;
15 END.

Listagem 1.23: nano8.cs


1 using System;
2
3 class nano8 {
4 public static void Main(){
5 int n;
6 n = 1;
7 if ( n == 1)
8 Console.Write(n);
9 else
10 Console.Write(0);
11 }
12 }

Listagem 1.24: nano8.il


1 .assembly extern mscorlib
2 {
3 .ver 4:0:0:0
4 .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4..
5 }
6 .assembly 'nano8'
7 {
8 .custom instance void class [mscorlib]System.Runtime.
CompilerServices.RuntimeCompatibilityAttribute::'.ctor'() = (
9 01 00 01 00 54 02 16 57 72 61 70 4E 6F 6E 45 78 // ....T..
WrapNonEx
10 63 65 70 74 69 6F 6E 54 68 72 6F 77 73 01 ) //
ceptionThrows.
11
12 .hash algorithm 0x00008004
13 .ver 0:0:0:0
14 }
15 .module nano8.exe // GUID = {3859264A-95A3-4151-B928-CD463DDDF935}
16

17
18 .class private auto ansi beforefieldinit nano8
19 extends [mscorlib]System.Object
20 {
21
22 // method line 1
23 .method public hidebysig specialname rtspecialname
24 instance default void '.ctor' () cil managed
25 {
26 // Method begins at RVA 0x2050
27 // Code size 7 (0x7)
28 .maxstack 8
29 IL_0000: ldarg.0
30 IL_0001: call instance void object::'.ctor'()
1.3

31 IL_0006: ret
32 } // end of method nano8::.ctor
33
34 // method line 2
35 .method public static hidebysig
36 default void Main () cil managed
37 {
38 // Method begins at RVA 0x2058
39 .entrypoint
40 // Code size 27 (0x1b)
41 .maxstack 2
42 .locals init (
43 int32 V_0)
44 IL_0000: ldc.i4.1
45 IL_0001: stloc.0
46 IL_0002: ldloc.0
47 IL_0003: ldc.i4.1
48 IL_0004: bne.un IL_0014
49
50 IL_0009: ldloc.0
51 IL_000a: call void class [mscorlib]System.Console::Write(int32)
52 IL_000f: br IL_001a
53
54 IL_0014: ldc.i4.0
55 IL_0015: call void class [mscorlib]System.Console::Write(int32)
56 IL_001a: ret
57 } // end of method nano8::Main
58

59 } // end of class nano8

9. Teste1_9
Listagem 1.25: teste1_9.pas
1 PROGRAM TESTE1_9;
2 VAR
3 n: real;
4
5 BEGIN
6 n := 1 + 1 / 2;
7 if ( n = 1) then
8 begin
9 write(n);
10 end;
11 else
12 begin
13 write(0);
14 end;
15 END.

Listagem 1.26: teste1_9.cs


1 using System;
2
3 class teste1_9{
4 public static void Main(){
5 int n;
6 n = 1 + 1 / 2;
7 if ( n == 1)
1.3

8 Console.Write(n);
9 else
10 Console.Write(0);
11 }
12 }

Listagem 1.27: teste1_9.il


1 .assembly extern mscorlib
2 {
3 .ver 4:0:0:0
4 .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4..
5 }
6 .assembly 'teste1_9'
7 {
8 .custom instance void class [mscorlib]System.Runtime.
CompilerServices.RuntimeCompatibilityAttribute::'.ctor'() = (
9 01 00 01 00 54 02 16 57 72 61 70 4E 6F 6E 45 78 // ....T..
WrapNonEx
10 63 65 70 74 69 6F 6E 54 68 72 6F 77 73 01 ) //
ceptionThrows.
11

12 .hash algorithm 0x00008004


13 .ver 0:0:0:0
14 }
15 .module teste1_9.exe // GUID = {A30CCD6F-42E2-4A48-9B76-2F0EC5BCE1CC}
16
17

18 .class private auto ansi beforefieldinit teste1_9


19 extends [mscorlib]System.Object
20 {
21
22 // method line 1
23 .method public hidebysig specialname rtspecialname
24 instance default void '.ctor' () cil managed
25 {
26 // Method begins at RVA 0x2050
27 // Code size 7 (0x7)
28 .maxstack 8
29 IL_0000: ldarg.0
30 IL_0001: call instance void object::'.ctor'()
31 IL_0006: ret
32 } // end of method teste1_9::.ctor
33
34 // method line 2
35 .method public static hidebysig
36 default void Main () cil managed
37 {
38 // Method begins at RVA 0x2058
39 .entrypoint
40 // Code size 27 (0x1b)
41 .maxstack 2
42 .locals init (
43 int32 V_0)
44 IL_0000: ldc.i4.1
45 IL_0001: stloc.0
46 IL_0002: ldloc.0
47 IL_0003: ldc.i4.1
48 IL_0004: bne.un IL_0014
1.3

49
50 IL_0009: ldloc.0
51 IL_000a: call void class [mscorlib]System.Console::Write(int32)
52 IL_000f: br IL_001a
53
54 IL_0014: ldc.i4.0
55 IL_0015: call void class [mscorlib]System.Console::Write(int32)
56 IL_001a: ret
57 } // end of method teste1_9::Main
58

59 } // end of class teste1_9

10. Nano10
Listagem 1.28: nano10.pas
1 PROGRAM NANO10;
2 VAR
3 n,m: integer;
4
5 BEGIN
6 n := 1;
7 m := 2;
8 if ( n = m ) then
9 begin
10 write(n);
11 end;
12 else
13 begin
14 write(0);
15 end;
16 END.

Listagem 1.29: nano10.cs


1 using System;
2
3 class nano10{
4 public static void Main(){
5 int n, m;
6 n = 1;
7 m = 2;
8
9 if ( n == m)
10 Console.Write(n);
11 else
12 Console.Write(0);
13 }
14 }

Listagem 1.30: nano10.il


1 .assembly extern mscorlib
2 {
3 .ver 4:0:0:0
4 .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4..
5 }
6 .assembly 'nano10'
1.3

7 {
8 .custom instance void class [mscorlib]System.Runtime.
CompilerServices.RuntimeCompatibilityAttribute::'.ctor'() = (
9 01 00 01 00 54 02 16 57 72 61 70 4E 6F 6E 45 78 // ....T..
WrapNonEx
10 63 65 70 74 69 6F 6E 54 68 72 6F 77 73 01 ) //
ceptionThrows.
11
12 .hash algorithm 0x00008004
13 .ver 0:0:0:0
14 }
15 .module nano10.exe // GUID = {CEB6B741-839A-4CCC-BBBB-33314E97341A}
16
17
18 .class private auto ansi beforefieldinit nano10
19 extends [mscorlib]System.Object
20 {
21
22 // method line 1
23 .method public hidebysig specialname rtspecialname
24 instance default void '.ctor' () cil managed
25 {
26 // Method begins at RVA 0x2050
27 // Code size 7 (0x7)
28 .maxstack 8
29 IL_0000: ldarg.0
30 IL_0001: call instance void object::'.ctor'()
31 IL_0006: ret
32 } // end of method nano10::.ctor
33
34 // method line 2
35 .method public static hidebysig
36 default void Main () cil managed
37 {
38 // Method begins at RVA 0x2058
39 .entrypoint
40 // Code size 29 (0x1d)
41 .maxstack 2
42 .locals init (
43 int32 V_0,
44 int32 V_1)
45 IL_0000: ldc.i4.1
46 IL_0001: stloc.0
47 IL_0002: ldc.i4.2
48 IL_0003: stloc.1
49 IL_0004: ldloc.0
50 IL_0005: ldloc.1
51 IL_0006: bne.un IL_0016
52
53 IL_000b: ldloc.0
54 IL_000c: call void class [mscorlib]System.Console::Write(int32)
55 IL_0011: br IL_001c
56
57 IL_0016: ldc.i4.0
58 IL_0017: call void class [mscorlib]System.Console::Write(int32)
59 IL_001c: ret
60 } // end of method nano10::Main
61

62 } // end of class nano10


1.3

11. Nano11
Listagem 1.31: nano11.pas
1 PROGRAM NANO11;
2 VAR
3 n,m,x: integer;
4
5 BEGIN
6 n := 1;
7 m := 2;
8 x := 5;
9 while ( x > n ) do
10 begin
11 n := n + m;
12 write(n);
13 end;
14
15 END.

Listagem 1.32: nano11.cs


1 using System;
2
3 class nano11 {
4 public static void Main(){
5 int n, m, x;
6 n = 1;
7 m = 2;
8 x = 5;
9
10 while ( x > n){
11 n = n + m;
12 Console.Write(n);
13 }
14 }
15 }

Listagem 1.33: nano11.il


1 .assembly extern mscorlib
2 {
3 .ver 4:0:0:0
4 .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4..
5 }
6 .assembly 'nano11'
7 {
8 .custom instance void class [mscorlib]System.Runtime.
CompilerServices.RuntimeCompatibilityAttribute::'.ctor'() = (
9 01 00 01 00 54 02 16 57 72 61 70 4E 6F 6E 45 78 // ....T..
WrapNonEx
10 63 65 70 74 69 6F 6E 54 68 72 6F 77 73 01 ) //
ceptionThrows.
11
12 .hash algorithm 0x00008004
13 .ver 0:0:0:0
14 }
15 .module nano11.exe // GUID = {8E5BE46C-821E-4AA1-9EBD-0BEC8D85CCCE}
16
1.3

17
18 .class private auto ansi beforefieldinit nano11
19 extends [mscorlib]System.Object
20 {
21
22 // method line 1
23 .method public hidebysig specialname rtspecialname
24 instance default void '.ctor' () cil managed
25 {
26 // Method begins at RVA 0x2050
27 // Code size 7 (0x7)
28 .maxstack 8
29 IL_0000: ldarg.0
30 IL_0001: call instance void object::'.ctor'()
31 IL_0006: ret
32 } // end of method nano11::.ctor
33
34 // method line 2
35 .method public static hidebysig
36 default void Main () cil managed
37 {
38 // Method begins at RVA 0x2058
39 .entrypoint
40 // Code size 29 (0x1d)
41 .maxstack 2
42 .locals init (
43 int32 V_0,
44 int32 V_1,
45 int32 V_2)
46 IL_0000: ldc.i4.1
47 IL_0001: stloc.0
48 IL_0002: ldc.i4.2
49 IL_0003: stloc.1
50 IL_0004: ldc.i4.5
51 IL_0005: stloc.2
52 IL_0006: br IL_0015
53
54 IL_000b: ldloc.0
55 IL_000c: ldloc.1
56 IL_000d: add
57 IL_000e: stloc.0
58 IL_000f: ldloc.0
59 IL_0010: call void class [mscorlib]System.Console::Write(int32)
60 IL_0015: ldloc.2
61 IL_0016: ldloc.0
62 IL_0017: bgt IL_000b
63
64 IL_001c: ret
65 } // end of method nano11::Main
66
67 } // end of class nano11

12. Nano12
Listagem 1.34: nano12.pas
1 PROGRAM NANO12;
2 VAR
3 n,m,x: integer;
1.3

4
5 BEGIN
6 n := 1;
7 m := 2;
8 x := 5;
9 while ( x > n ) do
10 begin
11 if ( n = m ) then
12 begin
13 write(n);
14 end;
15 else
16 begin
17 write(0);
18 end;
19 x := x - 1;
20 end;
21
22 END.

Listagem 1.35: nano12.cs


1 using System;
2
3 class nano12 {
4 public static void Main(){
5 int n, m, x;
6 n = 1;
7 m = 2;
8 x = 5;
9
10 while ( x > n){
11 if ( n == m)
12 Console.Write(n);
13 else
14 Console.Write(0);
15 x = x - 1;
16 }
17 }
18 }

Listagem 1.36: nano12.il


1 .assembly extern mscorlib
2 {
3 .ver 4:0:0:0
4 .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4..
5 }
6 .assembly 'nano12'
7 {
8 .custom instance void class [mscorlib]System.Runtime.
CompilerServices.RuntimeCompatibilityAttribute::'.ctor'() = (
9 01 00 01 00 54 02 16 57 72 61 70 4E 6F 6E 45 78 // ....T..
WrapNonEx
10 63 65 70 74 69 6F 6E 54 68 72 6F 77 73 01 ) //
ceptionThrows.
11

12 .hash algorithm 0x00008004


13 .ver 0:0:0:0
1.3

14 }
15 .module nano12.exe // GUID = {47B286E8-BC25-4510-B8F3-7840D64B7D28}
16
17

18 .class private auto ansi beforefieldinit nano12


19 extends [mscorlib]System.Object
20 {
21
22 // method line 1
23 .method public hidebysig specialname rtspecialname
24 instance default void '.ctor' () cil managed
25 {
26 // Method begins at RVA 0x2050
27 // Code size 7 (0x7)
28 .maxstack 8
29 IL_0000: ldarg.0
30 IL_0001: call instance void object::'.ctor'()
31 IL_0006: ret
32 } // end of method nano12::.ctor
33
34 // method line 2
35 .method public static hidebysig
36 default void Main () cil managed
37 {
38 // Method begins at RVA 0x2058
39 .entrypoint
40 // Code size 47 (0x2f)
41 .maxstack 2
42 .locals init (
43 int32 V_0,
44 int32 V_1,
45 int32 V_2)
46 IL_0000: ldc.i4.1
47 IL_0001: stloc.0
48 IL_0002: ldc.i4.2
49 IL_0003: stloc.1
50 IL_0004: ldc.i4.5
51 IL_0005: stloc.2
52 IL_0006: br IL_0027
53

54 IL_000b: ldloc.0
55 IL_000c: ldloc.1
56 IL_000d: bne.un IL_001d
57
58 IL_0012: ldloc.0
59 IL_0013: call void class [mscorlib]System.Console::Write(int32)
60 IL_0018: br IL_0023
61
62 IL_001d: ldc.i4.0
63 IL_001e: call void class [mscorlib]System.Console::Write(int32)
64 IL_0023: ldloc.2
65 IL_0024: ldc.i4.1
66 IL_0025: sub
67 IL_0026: stloc.2
68 IL_0027: ldloc.2
69 IL_0028: ldloc.0
70 IL_0029: bgt IL_000b
71

72 IL_002e: ret
1.3

73 } // end of method nano12::Main


74
75 } // end of class nano12

13. Micro01
Listagem 1.37: micro01.pas
1 PROGRAM MICRO01;
2 VAR
3 cel, fahr : real;
4
5 BEGIN
6 writeln('Tabela de converso: Celsius -> Fahrenhiet');
7 write('Digite a temperatura em Celsius: ');
8 readln(cel);
9 fahr := (9*cel+160)/5;
10 writeln('A nova temperatura : ', fahr, ' F');
11
12 END.

Listagem 1.38: micro01.cs


1 using System;
2
3 class micro01 {
4 public static void Main(){
5 double cel, far;
6 Console.WriteLine("Tabela de converso: Celsius -> Fahrenheit");
7 Console.Write("Digite a temperatura em Celsius: ");
8 cel = Convert.ToDouble(Console.ReadLine());
9 far = (9*cel+160)/5;
10 Console.WriteLine("A nova temperatura " + far + " F");
11 }
12 }

Listagem 1.39: micro01.il


1 .assembly extern mscorlib
2 {
3 .ver 4:0:0:0
4 .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4..
5 }
6 .assembly 'micro01'
7 {
8 .custom instance void class [mscorlib]System.Runtime.
CompilerServices.RuntimeCompatibilityAttribute::'.ctor'() = (
9 01 00 01 00 54 02 16 57 72 61 70 4E 6F 6E 45 78 // ....T..
WrapNonEx
10 63 65 70 74 69 6F 6E 54 68 72 6F 77 73 01 ) //
ceptionThrows.
11
12 .hash algorithm 0x00008004
13 .ver 0:0:0:0
14 }
15 .module micro01.exe // GUID = {41846A18-08BE-4F54-813D-8E35D731BA58}
16
17
1.3

18 .class private auto ansi beforefieldinit micro01


19 extends [mscorlib]System.Object
20 {
21

22 // method line 1
23 .method public hidebysig specialname rtspecialname
24 instance default void '.ctor' () cil managed
25 {
26 // Method begins at RVA 0x2050
27 // Code size 7 (0x7)
28 .maxstack 8
29 IL_0000: ldarg.0
30 IL_0001: call instance void object::'.ctor'()
31 IL_0006: ret
32 } // end of method micro01::.ctor
33

34 // method line 2
35 .method public static hidebysig
36 default void Main () cil managed
37 {
38 // Method begins at RVA 0x2058
39 .entrypoint
40 // Code size 90 (0x5a)
41 .maxstack 3
42 .locals init (
43 float64 V_0,
44 float64 V_1)
45 IL_0000: ldstr bytearray (
46 54 00 61 00 62 00 65 00 6c 00 61 00 20 00 64 00 // T.a.b.e.l.a. .d
.
47 65 00 20 00 63 00 6f 00 6e 00 76 00 65 00 72 00 // e. .c.o.n.v.e.r
.
48 73 00 e3 00 6f 00 3a 00 20 00 43 00 65 00 6c 00 // s...o.:. .C.e.l
.
49 73 00 69 00 75 00 73 00 20 00 2d 00 3e 00 20 00 // s.i.u.s. .-.>.
.
50 46 00 61 00 68 00 72 00 65 00 6e 00 68 00 65 00 // F.a.h.r.e.n.h.e
.
51 69 00 74 00 01 ) // i.t..
52

53 IL_0005: call void class [mscorlib]System.Console::WriteLine(


string)
54 IL_000a: ldstr "Digite a temperatura em Celsius: "
55 IL_000f: call void class [mscorlib]System.Console::Write(string)
56 IL_0014: call string class [mscorlib]System.Console::ReadLine()
57 IL_0019: call float64 class [mscorlib]System.Convert::ToDouble(
string)
58 IL_001e: stloc.0
59 IL_001f: ldc.r8 9.
60 IL_0028: ldloc.0
61 IL_0029: mul
62 IL_002a: ldc.r8 160.
63 IL_0033: add
64 IL_0034: ldc.r8 5.
65 IL_003d: div
66 IL_003e: stloc.1
67 IL_003f: ldstr bytearray (
68 41 00 20 00 6e 00 6f 00 76 00 61 00 20 00 74 00 // A. .n.o.v.a. .t
.
1.3

69 65 00 6d 00 70 00 65 00 72 00 61 00 74 00 75 00 // e.m.p.e.r.a.t.u
.
70 72 00 61 00 20 00 e9 00 20 00 01 ) // r.a. ... ..
71

72 IL_0044: ldloc.1
73 IL_0045: box [mscorlib]System.Double
74 IL_004a: ldstr " F"
75 IL_004f: call string string::Concat(object, object, object)
76 IL_0054: call void class [mscorlib]System.Console::WriteLine(
string)
77 IL_0059: ret
78 } // end of method micro01::Main
79
80 } // end of class micro01

14. Micro02
Listagem 1.40: micro02.pas
1 PROGRAM MICRO02;
2 VAR
3 num1, num2 : integer;
4
5 BEGIN
6 write('Digite o primeiro nmero: ');
7 readln(num1);
8 write('Digeite o segundo nmero: ');
9 readln(num2);
10 if ( num1 > num2 ) then
11 begin
12 write('O primeiro nmero ', num1, ' maior que o segundo ',
num2);
13 end;
14 else
15 begin
16 write('O segundo nmero ', num2, ' maior que o primeiro ',
num1);
17 end;
18

19 END.

Listagem 1.41: micro02.cs


1 using System;
2

3 class micro02 {
4 public static void Main(){
5 int num1, num2;
6 Console.Write("Digite o primeiro nmero: ");
7 num1 = Convert.ToInt32(Console.ReadLine());
8 Console.Write("Digite o segundo nmero: ");
9 num2 = Convert.ToInt32(Console.ReadLine());
10 if ( num1 > num2)
11 Console.Write("O primeiro nmero " + num1 + " maior que o
segundo " + num2);
12 else
13 Console.Write("O segundo nmero " + num2 + " maior que o
primeiro" + num2);
14 }
1.3

15 }

Listagem 1.42: micro02.il


1 .assembly extern mscorlib
2 {
3 .ver 4:0:0:0
4 .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4..
5 }
6 .assembly 'micro02'
7 {
8 .custom instance void class [mscorlib]System.Runtime.
CompilerServices.RuntimeCompatibilityAttribute::'.ctor'() = (
9 01 00 01 00 54 02 16 57 72 61 70 4E 6F 6E 45 78 // ....T..
WrapNonEx
10 63 65 70 74 69 6F 6E 54 68 72 6F 77 73 01 ) //
ceptionThrows.
11
12 .hash algorithm 0x00008004
13 .ver 0:0:0:0
14 }
15 .module micro02.exe // GUID = {9BB4814A-ACA4-4BAF-8941-7BBDBD6078CA}
16
17
18 .class private auto ansi beforefieldinit micro02
19 extends [mscorlib]System.Object
20 {
21

22 // method line 1
23 .method public hidebysig specialname rtspecialname
24 instance default void '.ctor' () cil managed
25 {
26 // Method begins at RVA 0x2050
27 // Code size 7 (0x7)
28 .maxstack 8
29 IL_0000: ldarg.0
30 IL_0001: call instance void object::'.ctor'()
31 IL_0006: ret
32 } // end of method micro02::.ctor
33
34 // method line 2
35 .method public static hidebysig
36 default void Main () cil managed
37 {
38 // Method begins at RVA 0x2058
39 .entrypoint
40 // Code size 155 (0x9b)
41 .maxstack 4
42 .locals init (
43 int32 V_0,
44 int32 V_1)
45 IL_0000: ldstr bytearray (
46 44 00 69 00 67 00 69 00 74 00 65 00 20 00 6f 00 // D.i.g.i.t.e. .o
.
47 20 00 70 00 72 00 69 00 6d 00 65 00 69 00 72 00 // .p.r.i.m.e.i.r
.
48 6f 00 20 00 6e 00 fa 00 6d 00 65 00 72 00 6f 00 // o. .n...m.e.r.o
.
49 3a 00 20 00 01 ) // :. ..
1.3

50
51 IL_0005: call void class [mscorlib]System.Console::Write(string)
52 IL_000a: call string class [mscorlib]System.Console::ReadLine()
53 IL_000f: call int32 class [mscorlib]System.Convert::ToInt32(string
)
54 IL_0014: stloc.0
55 IL_0015: ldstr bytearray (
56 44 00 69 00 67 00 69 00 74 00 65 00 20 00 6f 00 // D.i.g.i.t.e. .o
.
57 20 00 73 00 65 00 67 00 75 00 6e 00 64 00 6f 00 // .s.e.g.u.n.d.o
.
58 20 00 6e 00 fa 00 6d 00 65 00 72 00 6f 00 3a 00 // .n...m.e.r.o
.:.
59 20 00 01 ) // ..
60
61 IL_001a: call void class [mscorlib]System.Console::Write(string)
62 IL_001f: call string class [mscorlib]System.Console::ReadLine()
63 IL_0024: call int32 class [mscorlib]System.Convert::ToInt32(string
)
64 IL_0029: stloc.1
65 IL_002a: ldloc.0
66 IL_002b: ldloc.1
67 IL_002c: ble IL_0068
68
69 IL_0031: ldc.i4.4
70 IL_0032: newarr [mscorlib]System.Object
71 IL_0037: dup
72 IL_0038: ldc.i4.0
73 IL_0039: ldstr bytearray (
74 4f 00 20 00 70 00 72 00 69 00 6d 00 65 00 69 00 // O. .p.r.i.m.e.i
.
75 72 00 6f 00 20 00 6e 00 fa 00 6d 00 65 00 72 00 // r.o. .n...m.e.r
.
76 6f 00 20 00 01 ) // o. ..
77
78 IL_003e: stelem.ref
79 IL_003f: dup
80 IL_0040: ldc.i4.1
81 IL_0041: ldloc.0
82 IL_0042: box [mscorlib]System.Int32
83 IL_0047: stelem.ref
84 IL_0048: dup
85 IL_0049: ldc.i4.2
86 IL_004a: ldstr bytearray (
87 20 00 e9 00 20 00 6d 00 61 00 69 00 6f 00 72 00 // ... .m.a.i.o.r
.
88 20 00 71 00 75 00 65 00 20 00 6f 00 20 00 73 00 // .q.u.e. .o. .s
.
89 65 00 67 00 75 00 6e 00 64 00 6f 00 20 00 01 ) // e.g.u.n.d.o. ..
90
91 IL_004f: stelem.ref
92 IL_0050: dup
93 IL_0051: ldc.i4.3
94 IL_0052: ldloc.1
95 IL_0053: box [mscorlib]System.Int32
96 IL_0058: stelem.ref
97 IL_0059: call string string::Concat(object[])
98 IL_005e: call void class [mscorlib]System.Console::Write(string)
99 IL_0063: br IL_009a
1.3

100
101 IL_0068: ldc.i4.4
102 IL_0069: newarr [mscorlib]System.Object
103 IL_006e: dup
104 IL_006f: ldc.i4.0
105 IL_0070: ldstr bytearray (
106 4f 00 20 00 73 00 65 00 67 00 75 00 6e 00 64 00 // O. .s.e.g.u.n.d
.
107 6f 00 20 00 6e 00 fa 00 6d 00 65 00 72 00 6f 00 // o. .n...m.e.r.o
.
108 20 00 01 ) // ..
109
110 IL_0075: stelem.ref
111 IL_0076: dup
112 IL_0077: ldc.i4.1
113 IL_0078: ldloc.1
114 IL_0079: box [mscorlib]System.Int32
115 IL_007e: stelem.ref
116 IL_007f: dup
117 IL_0080: ldc.i4.2
118 IL_0081: ldstr bytearray (
119 20 00 e9 00 20 00 6d 00 61 00 69 00 6f 00 72 00 // ... .m.a.i.o.r
.
120 20 00 71 00 75 00 65 00 20 00 6f 00 20 00 70 00 // .q.u.e. .o. .p
.
121 72 00 69 00 6d 00 65 00 69 00 72 00 6f 00 01 ) // r.i.m.e.i.r.o..
122
123 IL_0086: stelem.ref
124 IL_0087: dup
125 IL_0088: ldc.i4.3
126 IL_0089: ldloc.1
127 IL_008a: box [mscorlib]System.Int32
128 IL_008f: stelem.ref
129 IL_0090: call string string::Concat(object[])
130 IL_0095: call void class [mscorlib]System.Console::Write(string)
131 IL_009a: ret
132 } // end of method micro02::Main
133
134 } // end of class micro02

15. Micro03
Listagem 1.43: micro03.pas
1 PROGRAM MICRO03;
2 VAR
3 numero: integer;
4
5 BEGIN
6 write('Digite um nmero: ');
7 readln(numero);
8 if ( numero >= 100 ) then
9 begin
10 if ( numero <= 200 ) then
11 begin
12 writeln('O nmero est no intervalo entre 100 e 200');
13 end;
14 else
15 begin
1.3

16 writeln('O nmero no est no intervalo entre 100 2 200');


17 end;
18 end;
19 else
20 begin
21 writeln('O nmero no est no intervalo entre 100 e 200');
22 end;
23 END.

Listagem 1.44: micro03.cs


1 using System;
2
3 class micro03 {
4 public static void Main(){
5 int numero;
6 Console.Write("Digite um nmero: ");
7 numero = Convert.ToInt32(Console.ReadLine());
8 if ( numero >= 100){
9 if ( numero <= 200)
10 Console.WriteLine("O nmero no intervalor entre 100 e 200");
11 else Console.WriteLine("O nmero no est no intervalo entre
100 e 200");
12 }
13 else
14 Console.WriteLine("O nmero no est no intervalo entre 100 e
200");
15 }
16 }

Listagem 1.45: micro03.il


1 .assembly extern mscorlib
2 {
3 .ver 4:0:0:0
4 .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4..
5 }
6 .assembly 'micro03'
7 {
8 .custom instance void class [mscorlib]System.Runtime.
CompilerServices.RuntimeCompatibilityAttribute::'.ctor'() = (
9 01 00 01 00 54 02 16 57 72 61 70 4E 6F 6E 45 78 // ....T..
WrapNonEx
10 63 65 70 74 69 6F 6E 54 68 72 6F 77 73 01 ) //
ceptionThrows.
11
12 .hash algorithm 0x00008004
13 .ver 0:0:0:0
14 }
15 .module micro03.exe // GUID = {99769FA4-0AA3-469F-AC61-1FB064653E86}
16

17
18 .class private auto ansi beforefieldinit micro03
19 extends [mscorlib]System.Object
20 {
21
22 // method line 1
23 .method public hidebysig specialname rtspecialname
24 instance default void '.ctor' () cil managed
1.3

25 {
26 // Method begins at RVA 0x2050
27 // Code size 7 (0x7)
28 .maxstack 8
29 IL_0000: ldarg.0
30 IL_0001: call instance void object::'.ctor'()
31 IL_0006: ret
32 } // end of method micro03::.ctor
33
34 // method line 2
35 .method public static hidebysig
36 default void Main () cil managed
37 {
38 // Method begins at RVA 0x2058
39 .entrypoint
40 // Code size 81 (0x51)
41 .maxstack 2
42 .locals init (
43 int32 V_0)
44 IL_0000: ldstr bytearray (
45 44 00 69 00 67 00 69 00 74 00 65 00 20 00 75 00 // D.i.g.i.t.e. .u
.
46 6d 00 20 00 6e 00 fa 00 6d 00 65 00 72 00 6f 00 // m. .n...m.e.r.o
.
47 3a 00 20 00 01 ) // :. ..
48
49 IL_0005: call void class [mscorlib]System.Console::Write(string)
50 IL_000a: call string class [mscorlib]System.Console::ReadLine()
51 IL_000f: call int32 class [mscorlib]System.Convert::ToInt32(string
)
52 IL_0014: stloc.0
53 IL_0015: ldloc.0
54 IL_0016: ldc.i4.s 0x64
55 IL_0018: blt IL_0046
56
57 IL_001d: ldloc.0
58 IL_001e: ldc.i4 200
59 IL_0023: bgt IL_0037
60
61 IL_0028: ldstr bytearray (
62 4f 00 20 00 6e 00 fa 00 6d 00 65 00 72 00 6f 00 // O. .n...m.e.r.o
.
63 20 00 6e 00 6f 00 20 00 69 00 6e 00 74 00 65 00 // .n.o. .i.n.t.e
.
64 72 00 76 00 61 00 6c 00 6f 00 72 00 20 00 65 00 // r.v.a.l.o.r. .e
.
65 6e 00 74 00 72 00 65 00 20 00 31 00 30 00 30 00 // n.t.r.e.
.1.0.0.
66 20 00 65 00 20 00 32 00 30 00 30 00 01 ) // .e. .2.0.0..
67
68 IL_002d: call void class [mscorlib]System.Console::WriteLine(
string)
69 IL_0032: br IL_0041
70
71 IL_0037: ldstr bytearray (
72 4f 00 20 00 6e 00 fa 00 6d 00 65 00 72 00 6f 00 // O. .n...m.e.r.o
.
73 20 00 6e 00 e3 00 6f 00 20 00 65 00 73 00 74 00 // .n...o. .e.s.t
.
1.3

74 e1 00 20 00 6e 00 6f 00 20 00 69 00 6e 00 74 00 // .. .n.o. .i.n.t
.
75 65 00 72 00 76 00 61 00 6c 00 6f 00 20 00 65 00 // e.r.v.a.l.o. .e
.
76 6e 00 74 00 72 00 65 00 20 00 31 00 30 00 30 00 // n.t.r.e.
.1.0.0.
77 20 00 65 00 20 00 32 00 30 00 30 00 01 ) // .e. .2.0.0..
78
79 IL_003c: call void class [mscorlib]System.Console::WriteLine(
string)
80 IL_0041: br IL_0050
81
82 IL_0046: ldstr bytearray (
83 4f 00 20 00 6e 00 fa 00 6d 00 65 00 72 00 6f 00 // O. .n...m.e.r.o
.
84 20 00 6e 00 e3 00 6f 00 20 00 65 00 73 00 74 00 // .n...o. .e.s.t
.
85 e1 00 20 00 6e 00 6f 00 20 00 69 00 6e 00 74 00 // .. .n.o. .i.n.t
.
86 65 00 72 00 76 00 61 00 6c 00 6f 00 20 00 65 00 // e.r.v.a.l.o. .e
.
87 6e 00 74 00 72 00 65 00 20 00 31 00 30 00 30 00 // n.t.r.e.
.1.0.0.
88 20 00 65 00 20 00 32 00 30 00 30 00 01 ) // .e. .2.0.0..
89
90 IL_004b: call void class [mscorlib]System.Console::WriteLine(
string)
91 IL_0050: ret
92 } // end of method micro03::Main
93
94 } // end of class micro03

16. Micro04
Listagem 1.46: micro04.pas
1 PROGRAM MICRO04;
2 VAR
3 x, num, intervalo : integer;
4
5 BEGIN
6 intervalo := 0;
7 for x := 1 to 5 do
8 begin
9 write('Digite um nmero: ');
10 readln(num);
11 if ( num >= 10 ) then
12 begin
13 if ( num <= 150 ) then
14 begin
15 intervalo := intervalo + 1;
16 end;
17 end;
18 end;
19 writeln('Ao total, foram digitados ', intervalo, ' nmeros no
intervalor 10 e 150');
20 END.
1.3

Listagem 1.47: micro04.cs


1 using System;
2

3 class micro04 {
4 public static void Main(){
5 int x, num, intervalo;
6
7 intervalo = 0;
8

9 for ( x = 1; x <= 5; x++){


10 Console.Write("Digite um nmero: ");
11 num = Convert.ToInt32(Console.ReadLine());
12 if ( num >= 10 )
13 if ( num <= 150 )
14 intervalo = intervalo + 1;
15 }
16
17 Console.WriteLine("Ao total, foram digitados " + intervalo + " n
meros no intervalo entre 10 e 150");
18
19 }
20 }

Listagem 1.48: micro04.il


1 .assembly extern mscorlib
2 {
3 .ver 4:0:0:0
4 .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4..
5 }
6 .assembly 'micro04'
7 {
8 .custom instance void class [mscorlib]System.Runtime.
CompilerServices.RuntimeCompatibilityAttribute::'.ctor'() = (
9 01 00 01 00 54 02 16 57 72 61 70 4E 6F 6E 45 78 // ....T..
WrapNonEx
10 63 65 70 74 69 6F 6E 54 68 72 6F 77 73 01 ) //
ceptionThrows.
11

12 .hash algorithm 0x00008004


13 .ver 0:0:0:0
14 }
15 .module micro04.exe // GUID = {D8580E0E-2548-4BD1-ACDC-356151188BA6}
16
17

18 .class private auto ansi beforefieldinit micro04


19 extends [mscorlib]System.Object
20 {
21
22 // method line 1
23 .method public hidebysig specialname rtspecialname
24 instance default void '.ctor' () cil managed
25 {
26 // Method begins at RVA 0x2050
27 // Code size 7 (0x7)
28 .maxstack 8
29 IL_0000: ldarg.0
30 IL_0001: call instance void object::'.ctor'()
31 IL_0006: ret
1.3

32 } // end of method micro04::.ctor


33
34 // method line 2
35 .method public static hidebysig
36 default void Main () cil managed
37 {
38 // Method begins at RVA 0x2058
39 .entrypoint
40 // Code size 91 (0x5b)
41 .maxstack 3
42 .locals init (
43 int32 V_0,
44 int32 V_1,
45 int32 V_2)
46 IL_0000: ldc.i4.0
47 IL_0001: stloc.2
48 IL_0002: ldc.i4.1
49 IL_0003: stloc.0
50 IL_0004: br IL_0039
51
52 IL_0009: ldstr bytearray (
53 44 00 69 00 67 00 69 00 74 00 65 00 20 00 75 00 // D.i.g.i.t.e. .u
.
54 6d 00 20 00 6e 00 fa 00 6d 00 65 00 72 00 6f 00 // m. .n...m.e.r.o
.
55 3a 00 20 00 01 ) // :. ..
56
57 IL_000e: call void class [mscorlib]System.Console::Write(string)
58 IL_0013: call string class [mscorlib]System.Console::ReadLine()
59 IL_0018: call int32 class [mscorlib]System.Convert::ToInt32(string
)
60 IL_001d: stloc.1
61 IL_001e: ldloc.1
62 IL_001f: ldc.i4.s 0x0a
63 IL_0021: blt IL_0035
64
65 IL_0026: ldloc.1
66 IL_0027: ldc.i4 150
67 IL_002c: bgt IL_0035
68

69 IL_0031: ldloc.2
70 IL_0032: ldc.i4.1
71 IL_0033: add
72 IL_0034: stloc.2
73 IL_0035: ldloc.0
74 IL_0036: ldc.i4.1
75 IL_0037: add
76 IL_0038: stloc.0
77 IL_0039: ldloc.0
78 IL_003a: ldc.i4.5
79 IL_003b: ble IL_0009
80

81 IL_0040: ldstr "Ao total, foram digitados "


82 IL_0045: ldloc.2
83 IL_0046: box [mscorlib]System.Int32
84 IL_004b: ldstr bytearray (
85 20 00 6e 00 fa 00 6d 00 65 00 72 00 6f 00 73 00 // .n...m.e.r.o.s
.
86 20 00 6e 00 6f 00 20 00 69 00 6e 00 74 00 65 00 // .n.o. .i.n.t.e
1.3

.
87 72 00 76 00 61 00 6c 00 6f 00 20 00 65 00 6e 00 // r.v.a.l.o. .e.n
.
88 74 00 72 00 65 00 20 00 31 00 30 00 20 00 65 00 // t.r.e. .1.0. .e
.
89 20 00 31 00 35 00 30 00 01 ) // .1.5.0..
90
91 IL_0050: call string string::Concat(object, object, object)
92 IL_0055: call void class [mscorlib]System.Console::WriteLine(
string)
93 IL_005a: ret
94 } // end of method micro04::Main
95
96 } // end of class micro04

17. Micro05
Listagem 1.49: micro05.pas
1 PROGRAM MICRO05;
2 VAR
3

4 nome, sexo : char;


5 x, h, m : integer;
6
7
8 BEGIN
9 h := 0;
10 m := 0;
11
12 for x:=1 to 5 do
13 begin
14 write('Digite o nome: ');
15 readln(nome);
16 write('H - Homem ou M - Mulher: ');
17 readln(sexo);
18 case sexo of
19 'H': h := h + 1;
20 'M': m := m + 1;
21 otherwise writeln('Sexo s pode ser H ou M!');
22 end;
23 end;
24
25 writeln ('Foram inseridos ', h, ' Homens');
26 writeln ('Foram inseridos ', m, ' Mulheres');
27
28 END.

Listagem 1.50: micro05.cs


1 using System;
2
3 class micro05 {
4 public static void Main(){
5 string nome;
6 char sexo;
7 int x, h, m;
8
9 h = 0;
1.3

10 m = 0;
11
12 for ( x = 1; x <= 5; x++){
13 Console.Write("Digite o nome: ");
14 nome = Console.ReadLine();
15 Console.Write("H - Homem ou M - Mulher: ");
16 sexo = Convert.ToChar(Console.Read());
17 switch (sexo){
18 case 'H': h = h + 1; break;
19 case 'M': m = m + 1; break;
20 default: Console.WriteLine("Sexo s pode ser H ou M!"); break
;
21 }
22 }
23
24 Console.WriteLine("Foram inseridos " + h + " Homens");
25 Console.WriteLine("Foram inseridos " + m + " Mulheres");
26 }
27 }

Listagem 1.51: micro05.il


1 .assembly extern mscorlib
2 {
3 .ver 4:0:0:0
4 .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4..
5 }
6 .assembly 'micro05'
7 {
8 .custom instance void class [mscorlib]System.Runtime.
CompilerServices.RuntimeCompatibilityAttribute::'.ctor'() = (
9 01 00 01 00 54 02 16 57 72 61 70 4E 6F 6E 45 78 // ....T..
WrapNonEx
10 63 65 70 74 69 6F 6E 54 68 72 6F 77 73 01 ) //
ceptionThrows.
11
12 .hash algorithm 0x00008004
13 .ver 0:0:0:0
14 }
15 .module micro05.exe // GUID = {A462B327-FFA9-4CD0-9C0A-BF08B62E1F38}
16
17
18 .class private auto ansi beforefieldinit micro05
19 extends [mscorlib]System.Object
20 {
21
22 // method line 1
23 .method public hidebysig specialname rtspecialname
24 instance default void '.ctor' () cil managed
25 {
26 // Method begins at RVA 0x2050
27 // Code size 7 (0x7)
28 .maxstack 8
29 IL_0000: ldarg.0
30 IL_0001: call instance void object::'.ctor'()
31 IL_0006: ret
32 } // end of method micro05::.ctor
33
34 // method line 2
1.3

35 .method public static hidebysig


36 default void Main () cil managed
37 {
38 // Method begins at RVA 0x2058
39 .entrypoint
40 // Code size 170 (0xaa)
41 .maxstack 3
42 .locals init (
43 string V_0,
44 char V_1,
45 int32 V_2,
46 int32 V_3,
47 int32 V_4)
48 IL_0000: ldc.i4.0
49 IL_0001: stloc.3
50 IL_0002: ldc.i4.0
51 IL_0003: stloc.s 4
52 IL_0005: ldc.i4.1
53 IL_0006: stloc.2
54 IL_0007: br IL_006d
55
56 IL_000c: ldstr "Digite o nome: "
57 IL_0011: call void class [mscorlib]System.Console::Write(string)
58 IL_0016: call string class [mscorlib]System.Console::ReadLine()
59 IL_001b: stloc.0
60 IL_001c: ldstr "H - Homem ou M - Mulher: "
61 IL_0021: call void class [mscorlib]System.Console::Write(string)
62 IL_0026: call int32 class [mscorlib]System.Console::Read()
63 IL_002b: call char class [mscorlib]System.Convert::ToChar(int32)
64 IL_0030: stloc.1
65 IL_0031: ldloc.1
66 IL_0032: ldc.i4.s 0x48
67 IL_0034: beq IL_0046
68

69 IL_0039: ldloc.1
70 IL_003a: ldc.i4.s 0x4d
71 IL_003c: beq IL_004f
72
73 IL_0041: br IL_005a
74

75 IL_0046: ldloc.3
76 IL_0047: ldc.i4.1
77 IL_0048: add
78 IL_0049: stloc.3
79 IL_004a: br IL_0069
80

81 IL_004f: ldloc.s 4
82 IL_0051: ldc.i4.1
83 IL_0052: add
84 IL_0053: stloc.s 4
85 IL_0055: br IL_0069
86

87 IL_005a: ldstr bytearray (


88 53 00 65 00 78 00 6f 00 20 00 73 00 f3 00 20 00 // S.e.x.o. .s...
.
89 70 00 6f 00 64 00 65 00 20 00 73 00 65 00 72 00 // p.o.d.e. .s.e.r
.
90 20 00 48 00 20 00 6f 00 75 00 20 00 4d 00 21 00 // .H. .o.u. .M
.!.
1.3

91 01 ) // .
92
93 IL_005f: call void class [mscorlib]System.Console::WriteLine(
string)
94 IL_0064: br IL_0069
95
96 IL_0069: ldloc.2
97 IL_006a: ldc.i4.1
98 IL_006b: add
99 IL_006c: stloc.2
100 IL_006d: ldloc.2
101 IL_006e: ldc.i4.5
102 IL_006f: ble IL_000c
103
104 IL_0074: ldstr "Foram inseridos "
105 IL_0079: ldloc.3
106 IL_007a: box [mscorlib]System.Int32
107 IL_007f: ldstr " Homens"
108 IL_0084: call string string::Concat(object, object, object)
109 IL_0089: call void class [mscorlib]System.Console::WriteLine(
string)
110 IL_008e: ldstr "Foram inseridos "
111 IL_0093: ldloc.s 4
112 IL_0095: box [mscorlib]System.Int32
113 IL_009a: ldstr " Mulheres"
114 IL_009f: call string string::Concat(object, object, object)
115 IL_00a4: call void class [mscorlib]System.Console::WriteLine(
string)
116 IL_00a9: ret
117 } // end of method micro05::Main
118
119 } // end of class micro05

18. Micro06
Listagem 1.52: micro06.pas
1 PROGRAM MICRO06;
2 VAR
3 numero : integer;
4
5 BEGIN
6 write('Digite um nmero de 1 a 5: ');
7 readln(numero);
8 case numero of
9 1 : writeln('Um');
10 2 : writeln('Dois');
11 3 : writeln('Trs');
12 4 : writeln('Quatro');
13 5 : writeln('Cinco');
14 otherwise writeln('Nmero Invlido!!!');
15 end;
16 END.

Listagem 1.53: micro06.cs


1 using System;
2
3 class micro06 {
1.3

4 public static void Main(){


5 int numero;
6
7 Console.Write("Digite um nmero de 1 a 5: ");
8 numero = Convert.ToInt32(Console.ReadLine());
9 switch(numero){
10 case 1: Console.WriteLine("Um"); break;
11 case 2: Console.WriteLine("Dois"); break;
12 case 3: Console.WriteLine("Trs"); break;
13 case 4: Console.WriteLine("Quatro"); break;
14 case 5: Console.WriteLine("Cinco"); break;
15 default: Console.WriteLine("Nmero Invlido!!!"); break;
16 }
17 }
18 }

Listagem 1.54: micro06.il


1 .assembly extern mscorlib
2 {
3 .ver 4:0:0:0
4 .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4..
5 }
6 .assembly 'micro06'
7 {
8 .custom instance void class [mscorlib]System.Runtime.
CompilerServices.RuntimeCompatibilityAttribute::'.ctor'() = (
9 01 00 01 00 54 02 16 57 72 61 70 4E 6F 6E 45 78 // ....T..
WrapNonEx
10 63 65 70 74 69 6F 6E 54 68 72 6F 77 73 01 ) //
ceptionThrows.
11
12 .hash algorithm 0x00008004
13 .ver 0:0:0:0
14 }
15 .module micro06.exe // GUID = {391E3A29-66A6-47DB-9887-756DA4470E40}
16
17
18 .class private auto ansi beforefieldinit micro06
19 extends [mscorlib]System.Object
20 {
21
22 // method line 1
23 .method public hidebysig specialname rtspecialname
24 instance default void '.ctor' () cil managed
25 {
26 // Method begins at RVA 0x2050
27 // Code size 7 (0x7)
28 .maxstack 8
29 IL_0000: ldarg.0
30 IL_0001: call instance void object::'.ctor'()
31 IL_0006: ret
32 } // end of method micro06::.ctor
33
34 // method line 2
35 .method public static hidebysig
36 default void Main () cil managed
37 {
38 // Method begins at RVA 0x2058
1.3

39 .entrypoint
40 // Code size 145 (0x91)
41 .maxstack 2
42 .locals init (
43 int32 V_0)
44 IL_0000: ldstr bytearray (
45 44 00 69 00 67 00 69 00 74 00 65 00 20 00 75 00 // D.i.g.i.t.e. .u
.
46 6d 00 20 00 6e 00 fa 00 6d 00 65 00 72 00 6f 00 // m. .n...m.e.r.o
.
47 20 00 64 00 65 00 20 00 31 00 20 00 61 00 20 00 // .d.e. .1. .a.
.
48 35 00 3a 00 20 00 01 ) // 5.:. ..
49
50 IL_0005: call void class [mscorlib]System.Console::Write(string)
51 IL_000a: call string class [mscorlib]System.Console::ReadLine()
52 IL_000f: call int32 class [mscorlib]System.Convert::ToInt32(string
)
53 IL_0014: stloc.0
54 IL_0015: ldloc.0
55 IL_0016: ldc.i4.1
56 IL_0017: sub
57 IL_0018: switch (
58 IL_0036,
59 IL_0045,
60 IL_0054,
61 IL_0063,
62 IL_0072)
63 IL_0031: br IL_0081
64
65 IL_0036: ldstr "Um"
66 IL_003b: call void class [mscorlib]System.Console::WriteLine(
string)
67 IL_0040: br IL_0090
68
69 IL_0045: ldstr "Dois"
70 IL_004a: call void class [mscorlib]System.Console::WriteLine(
string)
71 IL_004f: br IL_0090
72

73 IL_0054: ldstr bytearray (


74 54 00 72 00 ea 00 73 00 01 ) // T.r...s..
75
76 IL_0059: call void class [mscorlib]System.Console::WriteLine(
string)
77 IL_005e: br IL_0090
78
79 IL_0063: ldstr "Quatro"
80 IL_0068: call void class [mscorlib]System.Console::WriteLine(
string)
81 IL_006d: br IL_0090
82

83 IL_0072: ldstr "Cinco"


84 IL_0077: call void class [mscorlib]System.Console::WriteLine(
string)
85 IL_007c: br IL_0090
86
87 IL_0081: ldstr bytearray (
88 4e 00 fa 00 6d 00 65 00 72 00 6f 00 20 00 49 00 // N...m.e.r.o. .I
1.3

.
89 6e 00 76 00 e1 00 6c 00 69 00 64 00 6f 00 21 00 // n.v...l.i.d.o
.!.
90 21 00 21 00 01 ) // !.!..
91
92 IL_0086: call void class [mscorlib]System.Console::WriteLine(
string)
93 IL_008b: br IL_0090
94
95 IL_0090: ret
96 } // end of method micro06::Main
97
98 } // end of class micro06

19. Micro07
Listagem 1.55: micro07.pas
1 PROGRAM MICRO07;
2 VAR
3 programa, numero : integer;
4 opc : char;
5
6 BEGIN
7 programa := 1;
8 while ( programa = 1 ) do
9 begin
10 write('Digite um nmero: ');
11 readln(numero);
12 if ( numero > 0 ) then
13 begin
14 writeln('Positivo');
15 end;
16 else
17 begin
18 if ( numero = 0 ) then
19 begin
20 writeln('O nmero igual a 0');
21 end;
22 if ( numero < 0 ) then
23 begin
24 writeln('Negativo');
25 end;
26 end;
27 write('Deseja finalizar? (S/N) ');
28 readln(opc);
29 if ( opc = 'S' ) then
30 begin
31 programa := 0;
32 end;
33 end;
34 END.

Listagem 1.56: micro02.cs


1 using System;
2

3 class micro07 {
4 public static void Main(){
1.3

5 int programa, numero;


6 char opc;
7
8 programa = 1;
9 while ( programa == 1 ){
10 Console.WriteLine("Digite um nmero: ");
11 numero = Convert.ToInt32(Console.ReadLine());
12 if ( numero > 0 )
13 Console.WriteLine("Positivo");
14 else {
15 if ( numero == 0 )
16 Console.WriteLine("O nmero igual a 0");
17 if ( numero < 0 )
18 Console.WriteLine("Negativo");
19 }
20

21 Console.Write("Desja finalizar? (S/N) ");


22 opc = Convert.ToChar(Console.ReadLine());
23 if ( opc == 'S' )
24 programa = 0;
25 }
26 }
27 }

Listagem 1.57: micro07.il


1 .assembly extern mscorlib
2 {
3 .ver 4:0:0:0
4 .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4..
5 }
6 .assembly 'micro07'
7 {
8 .custom instance void class [mscorlib]System.Runtime.
CompilerServices.RuntimeCompatibilityAttribute::'.ctor'() = (
9 01 00 01 00 54 02 16 57 72 61 70 4E 6F 6E 45 78 // ....T..
WrapNonEx
10 63 65 70 74 69 6F 6E 54 68 72 6F 77 73 01 ) //
ceptionThrows.
11
12 .hash algorithm 0x00008004
13 .ver 0:0:0:0
14 }
15 .module micro07.exe // GUID = {32D940C1-DA44-415F-BC9E-3FA07BAF935B}
16

17
18 .class private auto ansi beforefieldinit micro07
19 extends [mscorlib]System.Object
20 {
21
22 // method line 1
23 .method public hidebysig specialname rtspecialname
24 instance default void '.ctor' () cil managed
25 {
26 // Method begins at RVA 0x2050
27 // Code size 7 (0x7)
28 .maxstack 8
29 IL_0000: ldarg.0
30 IL_0001: call instance void object::'.ctor'()
1.3

31 IL_0006: ret
32 } // end of method micro07::.ctor
33
34 // method line 2
35 .method public static hidebysig
36 default void Main () cil managed
37 {
38 // Method begins at RVA 0x2058
39 .entrypoint
40 // Code size 122 (0x7a)
41 .maxstack 2
42 .locals init (
43 int32 V_0,
44 int32 V_1,
45 char V_2)
46 IL_0000: ldc.i4.1
47 IL_0001: stloc.0
48 IL_0002: br IL_0072
49
50 IL_0007: ldstr bytearray (
51 44 00 69 00 67 00 69 00 74 00 65 00 20 00 75 00 // D.i.g.i.t.e. .u
.
52 6d 00 20 00 6e 00 fa 00 6d 00 65 00 72 00 6f 00 // m. .n...m.e.r.o
.
53 3a 00 20 00 01 ) // :. ..
54
55 IL_000c: call void class [mscorlib]System.Console::WriteLine(
string)
56 IL_0011: call string class [mscorlib]System.Console::ReadLine()
57 IL_0016: call int32 class [mscorlib]System.Convert::ToInt32(string
)
58 IL_001b: stloc.1
59 IL_001c: ldloc.1
60 IL_001d: ldc.i4.0
61 IL_001e: ble IL_0032
62
63 IL_0023: ldstr "Positivo"
64 IL_0028: call void class [mscorlib]System.Console::WriteLine(
string)
65 IL_002d: br IL_0053
66
67 IL_0032: ldloc.1
68 IL_0033: brtrue IL_0042
69
70 IL_0038: ldstr bytearray (
71 4f 00 20 00 6e 00 fa 00 6d 00 65 00 72 00 6f 00 // O. .n...m.e.r.o
.
72 20 00 e9 00 20 00 69 00 67 00 75 00 61 00 6c 00 // ... .i.g.u.a.l
.
73 20 00 61 00 20 00 30 00 01 ) // .a. .0..
74
75 IL_003d: call void class [mscorlib]System.Console::WriteLine(
string)
76 IL_0042: ldloc.1
77 IL_0043: ldc.i4.0
78 IL_0044: bge IL_0053
79
80 IL_0049: ldstr "Negativo"
81 IL_004e: call void class [mscorlib]System.Console::WriteLine(
1.3

string)
82 IL_0053: ldstr "Desja finalizar? (S/N) "
83 IL_0058: call void class [mscorlib]System.Console::Write(string)
84 IL_005d: call string class [mscorlib]System.Console::ReadLine()
85 IL_0062: call char class [mscorlib]System.Convert::ToChar(string)
86 IL_0067: stloc.2
87 IL_0068: ldloc.2
88 IL_0069: ldc.i4.s 0x53
89 IL_006b: bne.un IL_0072
90

91 IL_0070: ldc.i4.0
92 IL_0071: stloc.0
93 IL_0072: ldloc.0
94 IL_0073: ldc.i4.1
95 IL_0074: beq IL_0007
96

97 IL_0079: ret
98 } // end of method micro07::Main
99
100 } // end of class micro07

20. Micro08
Listagem 1.58: micro08.pas
1 PROGRAM MICRO08;
2 VAR
3 numero : integer;
4
5 BEGIN
6 numero := 1;
7 while ( numero <> 0 ) do
8 begin
9 write('Digite um nmero: ');
10 readln(numero);
11
12 if ( numero > 10 ) then
13 begin
14 writeln('O nmero ', numero, ' maior que 10');
15 end;
16 else
17 begin
18 writeln('O nmero ', numero, ' menor que 10');
19 end;
20 end;
21 END.

Listagem 1.59: micro08.cs


1 using System;
2

3 class micro08 {
4 public static void Main(){
5 int numero;
6
7 numero = 1;
8 while ( numero != 0 ) {
9 Console.Write("Digite um nmero: ");
10 numero = Convert.ToInt32(Console.ReadLine());
1.3

11 if ( numero > 10 )
12 Console.WriteLine("O nmero " + numero + " maior que 10");
13 else
14 Console.WriteLine("O nmero " + numero + " menor que 10");
15 }
16 }
17 }

Listagem 1.60: micro08.il


1 .assembly extern mscorlib
2 {
3 .ver 4:0:0:0
4 .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4..
5 }
6 .assembly 'micro08'
7 {
8 .custom instance void class [mscorlib]System.Runtime.
CompilerServices.RuntimeCompatibilityAttribute::'.ctor'() = (
9 01 00 01 00 54 02 16 57 72 61 70 4E 6F 6E 45 78 // ....T..
WrapNonEx
10 63 65 70 74 69 6F 6E 54 68 72 6F 77 73 01 ) //
ceptionThrows.
11
12 .hash algorithm 0x00008004
13 .ver 0:0:0:0
14 }
15 .module micro08.exe // GUID = {70B027DE-8DAE-4497-B999-CB56BE1D776F}
16
17
18 .class private auto ansi beforefieldinit micro08
19 extends [mscorlib]System.Object
20 {
21

22 // method line 1
23 .method public hidebysig specialname rtspecialname
24 instance default void '.ctor' () cil managed
25 {
26 // Method begins at RVA 0x2050
27 // Code size 7 (0x7)
28 .maxstack 8
29 IL_0000: ldarg.0
30 IL_0001: call instance void object::'.ctor'()
31 IL_0006: ret
32 } // end of method micro08::.ctor
33
34 // method line 2
35 .method public static hidebysig
36 default void Main () cil managed
37 {
38 // Method begins at RVA 0x2058
39 .entrypoint
40 // Code size 100 (0x64)
41 .maxstack 3
42 .locals init (
43 int32 V_0)
44 IL_0000: ldc.i4.1
45 IL_0001: stloc.0
46 IL_0002: br IL_005d
1.3

47
48 IL_0007: ldstr bytearray (
49 44 00 69 00 67 00 69 00 74 00 65 00 20 00 75 00 // D.i.g.i.t.e. .u
.
50 6d 00 20 00 6e 00 fa 00 6d 00 65 00 72 00 6f 00 // m. .n...m.e.r.o
.
51 3a 00 20 00 01 ) // :. ..
52
53 IL_000c: call void class [mscorlib]System.Console::Write(string)
54 IL_0011: call string class [mscorlib]System.Console::ReadLine()
55 IL_0016: call int32 class [mscorlib]System.Convert::ToInt32(string
)
56 IL_001b: stloc.0
57 IL_001c: ldloc.0
58 IL_001d: ldc.i4.s 0x0a
59 IL_001f: ble IL_0043
60
61 IL_0024: ldstr bytearray (
62 4f 00 20 00 6e 00 fa 00 6d 00 65 00 72 00 6f 00 // O. .n...m.e.r.o
.
63 20 00 01 ) // ..
64

65 IL_0029: ldloc.0
66 IL_002a: box [mscorlib]System.Int32
67 IL_002f: ldstr bytearray (
68 20 00 e9 00 20 00 6d 00 61 00 69 00 6f 00 72 00 // ... .m.a.i.o.r
.
69 20 00 71 00 75 00 65 00 20 00 31 00 30 00 01 ) // .q.u.e. .1.0..
70
71 IL_0034: call string string::Concat(object, object, object)
72 IL_0039: call void class [mscorlib]System.Console::WriteLine(
string)
73 IL_003e: br IL_005d
74

75 IL_0043: ldstr bytearray (


76 4f 00 20 00 6e 00 fa 00 6d 00 65 00 72 00 6f 00 // O. .n...m.e.r.o
.
77 20 00 01 ) // ..
78
79 IL_0048: ldloc.0
80 IL_0049: box [mscorlib]System.Int32
81 IL_004e: ldstr bytearray (
82 20 00 e9 00 20 00 6d 00 65 00 6e 00 6f 00 72 00 // ... .m.e.n.o.r
.
83 20 00 71 00 75 00 65 00 20 00 31 00 30 00 01 ) // .q.u.e. .1.0..
84

85 IL_0053: call string string::Concat(object, object, object)


86 IL_0058: call void class [mscorlib]System.Console::WriteLine(
string)
87 IL_005d: ldloc.0
88 IL_005e: brtrue IL_0007
89

90 IL_0063: ret
91 } // end of method micro08::Main
92
93 } // end of class micro08

21. Micro09
1.3

Listagem 1.61: micro09.pas


1 PROGRAM MICRO09;
2 VAR
3 preco, venda, novo_preco : real;
4
5 BEGIN
6 write('Digite o preco: ');
7 readln(preco);
8 write('Digite a venda: ');
9 readln(venda);
10
11 if ((venda < 500) or (preco < 30)) then
12 begin
13 novo_preco := preco + 10/100 * preco;
14 end;
15 else
16 begin
17 if (((venda >= 500) and (venda < 1200)) or ((preco >= 30) and (
preco < 80))) then
18 begin
19 novo_preco := preco + 15/100 * preco;
20 end;
21 else
22 begin
23 if ((venda >= 1200) or (preco >= 80)) then
24 begin
25 novo_preco := preco - 20/100 * preco;
26 end;
27 end;
28 end;
29 writeln('O novo preco ', novo_preco);
30 END.

Listagem 1.62: micro09.cs


1 using System;
2
3 class micro09 {
4 public static void Main(){
5 double preco, venda, novo_preco;
6
7 novo_preco = 0;
8
9 Console.Write("Digite o preco: ");
10 preco = Convert.ToDouble(Console.ReadLine());
11 Console.Write("Digite a venda: ");
12 venda = Convert.ToDouble(Console.ReadLine());
13
14 if ( (venda < 500) || ( preco < 30 ) )
15 novo_preco = preco + 10/100 * preco;
16 else if ( (venda >= 500 && venda < 1200) || (preco >= 30 && preco
< 80) )
17 novo_preco = preco + 15/100 * preco;
18 else if ( venda >= 1200 || preco >= 80 )
19 novo_preco = preco - 20/100 * preco;
20
21 Console.Write("O novo preco e " + novo_preco);
22 }
23 }
1.3

Listagem 1.63: micro09.il


1 .assembly extern mscorlib
2 {
3 .ver 4:0:0:0
4 .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4..
5 }
6 .assembly 'micro09'
7 {
8 .custom instance void class [mscorlib]System.Runtime.
CompilerServices.RuntimeCompatibilityAttribute::'.ctor'() = (
9 01 00 01 00 54 02 16 57 72 61 70 4E 6F 6E 45 78 // ....T..
WrapNonEx
10 63 65 70 74 69 6F 6E 54 68 72 6F 77 73 01 ) //
ceptionThrows.
11
12 .hash algorithm 0x00008004
13 .ver 0:0:0:0
14 }
15 .module micro09.exe // GUID = {FDD43407-255F-4D04-9C33-05E9E89CD03D}
16
17
18 .class private auto ansi beforefieldinit micro09
19 extends [mscorlib]System.Object
20 {
21
22 // method line 1
23 .method public hidebysig specialname rtspecialname
24 instance default void '.ctor' () cil managed
25 {
26 // Method begins at RVA 0x2050
27 // Code size 7 (0x7)
28 .maxstack 8
29 IL_0000: ldarg.0
30 IL_0001: call instance void object::'.ctor'()
31 IL_0006: ret
32 } // end of method micro09::.ctor
33
34 // method line 2
35 .method public static hidebysig
36 default void Main () cil managed
37 {
38 // Method begins at RVA 0x2058
39 .entrypoint
40 // Code size 246 (0xf6)
41 .maxstack 3
42 .locals init (
43 float64 V_0,
44 float64 V_1,
45 float64 V_2)
46 IL_0000: ldc.r8 0.
47 IL_0009: stloc.2
48 IL_000a: ldstr "Digite o preco: "
49 IL_000f: call void class [mscorlib]System.Console::Write(string)
50 IL_0014: call string class [mscorlib]System.Console::ReadLine()
51 IL_0019: call float64 class [mscorlib]System.Convert::ToDouble(
string)
1.3

52 IL_001e: stloc.0
53 IL_001f: ldstr "Digite a venda: "
54 IL_0024: call void class [mscorlib]System.Console::Write(string)
55 IL_0029: call string class [mscorlib]System.Console::ReadLine()
56 IL_002e: call float64 class [mscorlib]System.Convert::ToDouble(
string)
57 IL_0033: stloc.1
58 IL_0034: ldloc.1
59 IL_0035: ldc.r8 500.
60 IL_003e: blt IL_0052
61
62 IL_0043: ldloc.0
63 IL_0044: ldc.r8 30.
64 IL_004d: bge.un IL_0065
65
66 IL_0052: ldloc.0
67 IL_0053: ldc.r8 0.
68 IL_005c: ldloc.0
69 IL_005d: mul
70 IL_005e: add
71 IL_005f: stloc.2
72 IL_0060: br IL_00e0
73
74 IL_0065: ldloc.1
75 IL_0066: ldc.r8 500.
76 IL_006f: blt.un IL_0083
77
78 IL_0074: ldloc.1
79 IL_0075: ldc.r8 1200.
80 IL_007e: blt IL_00a1
81
82 IL_0083: ldloc.0
83 IL_0084: ldc.r8 30.
84 IL_008d: blt.un IL_00b4
85
86 IL_0092: ldloc.0
87 IL_0093: ldc.r8 80.
88 IL_009c: bge.un IL_00b4
89
90 IL_00a1: ldloc.0
91 IL_00a2: ldc.r8 0.
92 IL_00ab: ldloc.0
93 IL_00ac: mul
94 IL_00ad: add
95 IL_00ae: stloc.2
96 IL_00af: br IL_00e0
97
98 IL_00b4: ldloc.1
99 IL_00b5: ldc.r8 1200.
100 IL_00be: bge IL_00d2
101
102 IL_00c3: ldloc.0
103 IL_00c4: ldc.r8 80.
104 IL_00cd: blt.un IL_00e0
105
106 IL_00d2: ldloc.0
107 IL_00d3: ldc.r8 0.
108 IL_00dc: ldloc.0
109 IL_00dd: mul
1.3

110 IL_00de: sub


111 IL_00df: stloc.2
112 IL_00e0: ldstr "O novo preco e "
113 IL_00e5: ldloc.2
114 IL_00e6: box [mscorlib]System.Double
115 IL_00eb: call string string::Concat(object, object)
116 IL_00f0: call void class [mscorlib]System.Console::Write(string)
117 IL_00f5: ret
118 } // end of method micro09::Main
119

120 } // end of class micro09

22. Micro10
Listagem 1.64: micro10.pas
1 PROGRAM MICRO10;
2 VAR
3 numero : integer;
4 fat : integer;
5
6 FUNCTION fatorial( numero : integer) : integer;
7 begin
8 if ( numero <= 0) then
9 begin
10 fatorial := 1;
11 end;
12
13 else
14 begin
15 fatorial := numero * fatorial(numero-(1));
16 end;
17 end;
18
19 BEGIN
20 write('Digite um nmero: ');
21 readln(numero);
22 fat := fatorial(numero);
23 write('O fatorial de ');
24 write(numero);
25 write(' ');
26 writeln(fat);
27 END.

Listagem 1.65: micro10.cs


1 using System;
2
3 class micro10 {
4 public static int fatorial (int n){
5 if ( n <= 0)
6 return 1;
7 else
8 return n * fatorial(n-1);
9 }
10
11 public static void Main(){
12 int numero, fat;
13
1.3

14 Console.Write("Digite um nmero: ");


15 numero = Convert.ToInt32(Console.ReadLine());
16 fat = fatorial(numero);
17

18 Console.Write("O fatorial de ");


19 Console.Write(numero);
20 Console.Write(" ");
21 Console.WriteLine(fat);
22 }
23 }

Listagem 1.66: micro10.il


1 .assembly extern mscorlib
2 {
3 .ver 4:0:0:0
4 .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4..
5 }
6 .assembly 'micro10'
7 {
8 .custom instance void class [mscorlib]System.Runtime.
CompilerServices.RuntimeCompatibilityAttribute::'.ctor'() = (
9 01 00 01 00 54 02 16 57 72 61 70 4E 6F 6E 45 78 // ....T..
WrapNonEx
10 63 65 70 74 69 6F 6E 54 68 72 6F 77 73 01 ) //
ceptionThrows.
11
12 .hash algorithm 0x00008004
13 .ver 0:0:0:0
14 }
15 .module micro10.exe // GUID = {39967959-DCDD-4DFC-BC91-99FC03A7AB34}
16
17
18 .class private auto ansi beforefieldinit micro10
19 extends [mscorlib]System.Object
20 {
21
22 // method line 1
23 .method public hidebysig specialname rtspecialname
24 instance default void '.ctor' () cil managed
25 {
26 // Method begins at RVA 0x2050
27 // Code size 7 (0x7)
28 .maxstack 8
29 IL_0000: ldarg.0
30 IL_0001: call instance void object::'.ctor'()
31 IL_0006: ret
32 } // end of method micro10::.ctor
33
34 // method line 2
35 .method public static hidebysig
36 default int32 fatorial (int32 n) cil managed
37 {
38 // Method begins at RVA 0x2058
39 // Code size 20 (0x14)
40 .maxstack 8
41 IL_0000: ldarg.0
42 IL_0001: ldc.i4.0
43 IL_0002: bgt IL_0009
1.3

44
45 IL_0007: ldc.i4.1
46 IL_0008: ret
47 IL_0009: ldarg.0
48 IL_000a: ldarg.0
49 IL_000b: ldc.i4.1
50 IL_000c: sub
51 IL_000d: call int32 class micro10::fatorial(int32)
52 IL_0012: mul
53 IL_0013: ret
54 } // end of method micro10::fatorial
55
56 // method line 3
57 .method public static hidebysig
58 default void Main () cil managed
59 {
60 // Method begins at RVA 0x2070
61 .entrypoint
62 // Code size 61 (0x3d)
63 .maxstack 1
64 .locals init (
65 int32 V_0,
66 int32 V_1)
67 IL_0000: ldstr bytearray (
68 44 00 69 00 67 00 69 00 74 00 65 00 20 00 75 00 // D.i.g.i.t.e. .u
.
69 6d 00 20 00 6e 00 fa 00 6d 00 65 00 72 00 6f 00 // m. .n...m.e.r.o
.
70 3a 00 20 00 01 ) // :. ..
71
72 IL_0005: call void class [mscorlib]System.Console::Write(string)
73 IL_000a: call string class [mscorlib]System.Console::ReadLine()
74 IL_000f: call int32 class [mscorlib]System.Convert::ToInt32(string
)
75 IL_0014: stloc.0
76 IL_0015: ldloc.0
77 IL_0016: call int32 class micro10::fatorial(int32)
78 IL_001b: stloc.1
79 IL_001c: ldstr "O fatorial de "
80 IL_0021: call void class [mscorlib]System.Console::Write(string)
81 IL_0026: ldloc.0
82 IL_0027: call void class [mscorlib]System.Console::Write(int32)
83 IL_002c: ldstr bytearray (
84 20 00 e9 00 20 00 01 ) // ... ..
85
86 IL_0031: call void class [mscorlib]System.Console::Write(string)
87 IL_0036: ldloc.1
88 IL_0037: call void class [mscorlib]System.Console::WriteLine(int32
)
89 IL_003c: ret
90 } // end of method micro10::Main
91

92 } // end of class micro10

23. Micro11
Listagem 1.67: micro11.pas
1 PROGRAM MICRO11;
1.3

2 VAR
3 numero : integer;
4 x : integer;
5

6 FUNCTION verifica ( n : integer ): integer;


7 var
8 res : integer;
9 begin
10 if ( n > 0 ) then
11 begin
12 res := 1;
13 end;
14
15 if ( n < 0 ) then
16 begin
17 res := -1;
18 end;
19
20 else
21 begin
22 res := 0;
23 end;
24 verifica := res;
25 end;
26
27 BEGIN
28 write('Digite um nmero: ');
29 readln(numero);
30 x := verifica(numero);
31 if ( x = 1) then
32 begin
33 writeln('Numero positivo');
34 end;
35 else
36 begin
37 if ( x = 0 ) then
38 begin
39 writeln ('Zero');
40 end;
41 else
42 begin
43 writeln('Nmero negativo');
44 end;
45 end;
46 END.

Listagem 1.68: micro11.cs


1 using System;
2
3 class micro11 {
4 public static int verifica(int n){
5 int res;
6 if ( n > 0 )
7 res = 1;
8 else if ( n < 0)
9 res = -1;
10 else
11 res = 0;
1.3

12 return res;
13 }
14
15 public static void Main(){
16 int numero, x;
17
18 Console.Write("Digite um nmero: ");
19 numero = Convert.ToInt32(Console.ReadLine());
20 x = verifica(numero);
21 if ( x == 1 )
22 Console.WriteLine("Numero positivo");
23 else if ( x == 0)
24 Console.WriteLine("Zero");
25 else Console.WriteLine("Numero negativo");
26 }
27 }

Listagem 1.69: micro11.il


1 .assembly extern mscorlib
2 {
3 .ver 4:0:0:0
4 .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4..
5 }
6 .assembly 'micro11'
7 {
8 .custom instance void class [mscorlib]System.Runtime.
CompilerServices.RuntimeCompatibilityAttribute::'.ctor'() = (
9 01 00 01 00 54 02 16 57 72 61 70 4E 6F 6E 45 78 // ....T..
WrapNonEx
10 63 65 70 74 69 6F 6E 54 68 72 6F 77 73 01 ) //
ceptionThrows.
11
12 .hash algorithm 0x00008004
13 .ver 0:0:0:0
14 }
15 .module micro11.exe // GUID = {62078E8D-54BD-4D4B-B6AB-49F59AB55B10}
16
17

18 .class private auto ansi beforefieldinit micro11


19 extends [mscorlib]System.Object
20 {
21
22 // method line 1
23 .method public hidebysig specialname rtspecialname
24 instance default void '.ctor' () cil managed
25 {
26 // Method begins at RVA 0x2050
27 // Code size 7 (0x7)
28 .maxstack 8
29 IL_0000: ldarg.0
30 IL_0001: call instance void object::'.ctor'()
31 IL_0006: ret
32 } // end of method micro11::.ctor
33
34 // method line 2
35 .method public static hidebysig
36 default int32 verifica (int32 n) cil managed
37 {
1.3

38 // Method begins at RVA 0x2058


39 // Code size 32 (0x20)
40 .maxstack 2
41 .locals init (
42 int32 V_0)
43 IL_0000: ldarg.0
44 IL_0001: ldc.i4.0
45 IL_0002: ble IL_000e
46
47 IL_0007: ldc.i4.1
48 IL_0008: stloc.0
49 IL_0009: br IL_001e
50
51 IL_000e: ldarg.0
52 IL_000f: ldc.i4.0
53 IL_0010: bge IL_001c
54
55 IL_0015: ldc.i4.m1
56 IL_0016: stloc.0
57 IL_0017: br IL_001e
58
59 IL_001c: ldc.i4.0
60 IL_001d: stloc.0
61 IL_001e: ldloc.0
62 IL_001f: ret
63 } // end of method micro11::verifica
64
65 // method line 3
66 .method public static hidebysig
67 default void Main () cil managed
68 {
69 // Method begins at RVA 0x2084
70 .entrypoint
71 // Code size 82 (0x52)
72 .maxstack 2
73 .locals init (
74 int32 V_0,
75 int32 V_1)
76 IL_0000: ldstr bytearray (
77 44 00 69 00 67 00 69 00 74 00 65 00 20 00 75 00 // D.i.g.i.t.e. .u
.
78 6d 00 20 00 6e 00 fa 00 6d 00 65 00 72 00 6f 00 // m. .n...m.e.r.o
.
79 3a 00 20 00 01 ) // :. ..
80
81 IL_0005: call void class [mscorlib]System.Console::Write(string)
82 IL_000a: call string class [mscorlib]System.Console::ReadLine()
83 IL_000f: call int32 class [mscorlib]System.Convert::ToInt32(string
)
84 IL_0014: stloc.0
85 IL_0015: ldloc.0
86 IL_0016: call int32 class micro11::verifica(int32)
87 IL_001b: stloc.1
88 IL_001c: ldloc.1
89 IL_001d: ldc.i4.1
90 IL_001e: bne.un IL_0032
91
92 IL_0023: ldstr "Numero positivo"
93 IL_0028: call void class [mscorlib]System.Console::WriteLine(
1.3

string)
94 IL_002d: br IL_0051
95
96 IL_0032: ldloc.1
97 IL_0033: brtrue IL_0047
98
99 IL_0038: ldstr "Zero"
100 IL_003d: call void class [mscorlib]System.Console::WriteLine(
string)
101 IL_0042: br IL_0051
102
103 IL_0047: ldstr "Numero negativo"
104 IL_004c: call void class [mscorlib]System.Console::WriteLine(
string)
105 IL_0051: ret
106 } // end of method micro11::Main
107
108 } // end of class micro11
Captulo 2

Analisador Lxico

Anlise lxica (scanning) o primeiro estgio de um processo em trs partes que o com-
pilador utiliza para entender o programa de entrada. O scanner, ou analisador lxico, l um
fluxo de caracteres e produz um fluxo de palavras. Ele agrega caracteres para formar pala-
vras e aplica um conjunto de regras para determinar se cada uma delas uma palavra vlida
na linguagem-fonte. Se a palavra vlida, o scanner atribui-lhe uma categoria sinttica, ou
classe gramatical. Eis o analisador lxico em Ocaml da linguagem Pascal:
Listagem 2.1: lexico.mll
1 {
2 open Lexing
3 open Printf
4 open Sintatico
5
6 exception Erro of string
7
8 let incr_num_linha lexbuf =
9 let pos = lexbuf.lex_curr_p in
10 lexbuf.lex_curr_p <-
11 { pos with pos_lnum = pos.pos_lnum + 1;
12 pos_bol = pos.pos_cnum
13 }
14
15 let pos_atual lexbuf = lexbuf.lex_start_p
16
17 }
18

19 let digito = ['0' - '9']


20 let letra = ['a' - 'z' 'A' - 'Z']
21 let ponto = "."
22 let inteiro = '-'?(digito)+
23 let real = ( digito )+ ponto (digito)+
24

25
26 let identificador = letra ( letra | digito | '_')*
27
28 let brancos = [' ' '\t']+
29 let novalinha = '\r' | '\n' | "\r\n"
30

31 let comentario = "//" [^ '\r' '\n' ]*


32

60
2.0

33 rule token = parse


34 brancos { token lexbuf }
35 | novalinha { incr_num_linha lexbuf; token lexbuf }
36 | comentario { token lexbuf }
37 | "(*" { comentario_bloco 0 lexbuf }
38 | '+' { MAIS (pos_atual lexbuf) }
39 | '-' { MENOS (pos_atual lexbuf) }
40 | '*' { MULTIPLICACAO (pos_atual lexbuf) }
41 | '/' { DIVISAO (pos_atual lexbuf) }
42 | '=' { IGUAL (pos_atual lexbuf) }
43 | "<>" { DIFERENTE (pos_atual lexbuf) }
44 | '>' { MAIOR (pos_atual lexbuf) }
45 | '<' { MENOR (pos_atual lexbuf) }
46 | '.' { PONTO (pos_atual lexbuf) }
47 | ';' { PONTO_VIRGULA (pos_atual lexbuf) }
48 | '(' { ABRE_PARENTESE (pos_atual lexbuf) }
49 | ')' { FECHA_PARENTESE (pos_atual lexbuf) }
50 | ':' { DOIS_PONTOS (pos_atual lexbuf) }
51 | "<=" { MENOR_IGUAL (pos_atual lexbuf) }
52 | ">=" { MAIOR_IGUAL (pos_atual lexbuf) }
53 | ":=" { ATRIBUICAO (pos_atual lexbuf) }
54 | ',' { VIRGULA (pos_atual lexbuf) }
55 | "AND" { AND (pos_atual lexbuf) }
56 | "and" { AND (pos_atual lexbuf) }
57 | "BEGIN" { BEGIN (pos_atual lexbuf) }
58 | "begin" { BEGIN (pos_atual lexbuf) }
59 | "CASE" { CASE (pos_atual lexbuf) }
60 | "case" { CASE (pos_atual lexbuf) }
61 | "CHAR" { CHAR (pos_atual lexbuf) }
62 | "char" { CHAR (pos_atual lexbuf) }
63 | "DO" { DO (pos_atual lexbuf) }
64 | "do" { DO (pos_atual lexbuf) }
65 | "ELSE" { ELSE (pos_atual lexbuf) }
66 | "else" { ELSE (pos_atual lexbuf) }
67 | "END" { END (pos_atual lexbuf) }
68 | "end" { END (pos_atual lexbuf) }
69 | "FOR" { FOR (pos_atual lexbuf) }
70 | "for" { FOR (pos_atual lexbuf) }
71 | "FUNCTION" { FUNCTION (pos_atual lexbuf) }
72 | "function" { FUNCTION (pos_atual lexbuf) }
73 | "IF" { IF (pos_atual lexbuf) }
74 | "if" { IF (pos_atual lexbuf) }
75 | "INTEGER" { INTEGER (pos_atual lexbuf) }
76 | "integer" { INTEGER (pos_atual lexbuf) }
77 | "MOD" { MOD (pos_atual lexbuf) }
78 | "mod" { MOD (pos_atual lexbuf) }
79 | "NOT" { NOT (pos_atual lexbuf) }
80 | "not" { NOT (pos_atual lexbuf) }
81 | "OF" { OF (pos_atual lexbuf) }
82 | "of" { OF (pos_atual lexbuf) }
83 | "OR" { OR (pos_atual lexbuf) }
84 | "or" { OR (pos_atual lexbuf) }
85 | "OTHERWISE" { OTHERWISE (pos_atual lexbuf) }
86 | "otherwise" { OTHERWISE (pos_atual lexbuf) }
87 | "PROGRAM" { PROGRAM (pos_atual lexbuf) }
88 | "program" { PROGRAM (pos_atual lexbuf) }
89 | "REAL" { REAL (pos_atual lexbuf) }
90 | "real" { REAL (pos_atual lexbuf) }
91 | "READLN" { READLN (pos_atual lexbuf) }
2.0

92 | "readln" { READLN (pos_atual lexbuf) }


93 | "THEN" { THEN (pos_atual lexbuf) }
94 | "then" { THEN (pos_atual lexbuf) }
95 | "TO" { TO (pos_atual lexbuf) }
96 | "to" { TO (pos_atual lexbuf) }
97 | "VAR" { VAR (pos_atual lexbuf) }
98 | "var" { VAR (pos_atual lexbuf) }
99 | "WHILE" { WHILE (pos_atual lexbuf) }
100 | "while" { WHILE (pos_atual lexbuf) }
101 | "WRITE" { WRITE (pos_atual lexbuf) }
102 | "write" { WRITE (pos_atual lexbuf) }
103 | "WRITELN" { WRITELN (pos_atual lexbuf) }
104 | "writeln" { WRITELN (pos_atual lexbuf) }
105 | eof { EOF }
106 | inteiro as num { let numero = int_of_string num in
107 LITERAL_INTEGER (numero, pos_atual lexbuf) }
108 | real as num { let numero = float_of_string num in
109 LITERAL_REAL (numero,pos_atual lexbuf) }
110 | identificador as id { IDENTIFICADOR(id, pos_atual lexbuf) }
111 | '"' { let pos = lexbuf.lex_curr_p in
112 let lin = pos.pos_lnum
113 and col = pos.pos_cnum - pos.pos_bol - 1 in
114 let buffer = Buffer.create 1 in
115 let str = leia_string lin col buffer lexbuf in
116 LITERAL_STRING (str,pos_atual lexbuf) }
117
118 | '\'' { let pos = lexbuf.lex_curr_p in
119 let lin = pos.pos_lnum
120 and col = pos.pos_cnum - pos.pos_bol - 1 in
121 let buffer = Buffer.create 1 in
122 let str = leia_string lin col buffer lexbuf in
123 LITERAL_STRING (str,pos_atual lexbuf) }
124 | _ {raise (Erro ("Caracter desconhecido: "^Lexing.lexeme lexbuf )) }
125 | eof { EOF }
126
127 and comentario_bloco n = parse
128 "(*" { if n=0 then token lexbuf
129 else comentario_bloco (n-1) lexbuf }
130 | "*)" { comentario_bloco (n+1) lexbuf }
131 | _ { comentario_bloco n lexbuf }
132 | eof { raise (Erro "Comentrio no terminado") }
133
134 and leia_string lin col buffer = parse
135 '"' { Buffer.contents buffer}
136 | ''' { Buffer.contents buffer}
137 | "\\t" { Buffer.add_char buffer '\t'; leia_string lin col buffer
lexbuf }
138 | "\\n" { Buffer.add_char buffer '\n'; leia_string lin col buffer
lexbuf }
139 | '\\' '"' { Buffer.add_char buffer '"'; leia_string lin col buffer lexbuf
}
140 | '\\' '\'' { Buffer.add_char buffer '\''; leia_string lin col buffer
lexbuf }
141 | '\\' '\\' { Buffer.add_char buffer '\\'; leia_string lin col buffer
lexbuf }
142 | _ as c { Buffer.add_char buffer c; leia_string lin col buffer lexbuf
}
143 | eof { raise (Erro "A string no foi fechada")}
Captulo 3

Analisador Sinttico

A anlise sinttica (parsing) o segundo estgio do front-end do compilador. O parser


trabalha com o programa transformado pelo scanner; ele v um fluxo de palavras, onde
cada palavra est associada a uma categoria sinttica (semelhante sua classe gramatical).
Ele deriva uma estrutura sinttica para o programa, encaixando as palavras em um modelo
gramatical da linguagem de programao-fonte. Se o parser determina que o fluxo de entrada
um programa vlido, constri um modelo concreto do programa para uso pelas ltimas
fases da compilao. Caso contrrio, ele informa o problema e a informao de diagnstico
apropriada ao usurio. Eis o programa em Ocaml do analisador sinttico:
Listagem 3.1: sintatico.mly
1
2 %{
3
4 open Lexing
5 open Ast
6 open Sast
7
8 %}
9
10 %token<Lexing.position> DO
11 %token<Lexing.position> DOIS_PONTOS
12 %token<Lexing.position> FOR
13 %token<Lexing.position> FUNCTION
14 %token<Lexing.position> OF
15 %token<Lexing.position> PONTO_VIRGULA
16 %token<Lexing.position> PONTO
17 %token<Lexing.position> TO
18 %token<Lexing.position> VAR
19 %token<Lexing.position> VIRGULA
20 %token<Lexing.position> WHILE
21
22
23 %token<int * Lexing.position> LITERAL_INTEGER
24 %token<float * Lexing.position> LITERAL_REAL
25 %token<string * Lexing.position> LITERAL_STRING
26 %token<bool * Lexing.position> LITERAL_BOOLEAN
27 %token<string * Lexing.position> IDENTIFICADOR
28
29 %token<Lexing.position> INTEGER REAL STRING BOOLEAN CHAR

63
3.0

30
31 %token<Lexing.position> PROGRAM
32 %token<Lexing.position> BEGIN
33 %token<Lexing.position> END
34
35 %token<Lexing.position> IF THEN ELSE
36 %token<Lexing.position> CASE
37 %token<Lexing.position> OTHERWISE
38 %token<Lexing.position> READLN
39 %token<Lexing.position> WRITE WRITELN
40 %token<Lexing.position> ATRIBUICAO
41
42 %token<Lexing.position> OR
43 %token<Lexing.position> AND
44 %token<Lexing.position> NOT
45 %token<Lexing.position> IGUAL
46 %token<Lexing.position> DIFERENTE
47 %token<Lexing.position> MAIOR
48 %token<Lexing.position> MAIOR_IGUAL
49 %token<Lexing.position> MENOR
50 %token<Lexing.position> MENOR_IGUAL
51

52 %token<Lexing.position> MAIS
53 %token<Lexing.position> MENOS
54 %token<Lexing.position> MULTIPLICACAO
55 %token<Lexing.position> DIVISAO
56 %token<Lexing.position> MOD
57

58
59 %token<Lexing.position> ABRE_PARENTESE FECHA_PARENTESE
60 %token EOF
61
62 %right NOT
63 %left OR
64 %left AND
65 %left IGUAL DIFERENTE MAIOR MENOR MAIOR_IGUAL MENOR_IGUAL
66 %left MULTIPLICACAO DIVISAO MOD
67 %left MAIS MENOS
68
69 %start <Sast.expressao Ast.programa> programa
70
71 %%
72
73 programa: PROGRAM identificador=IDENTIFICADOR PONTO_VIRGULA
74 VAR
75 ds = declaracao*
76 fs = funcao*
77 BEGIN
78 cs = comando*
79 END PONTO
80 EOF { Programa (identificador, List.flatten ds, fs, cs) }
81

82 declaracao: ids = separated_nonempty_list(VIRGULA, IDENTIFICADOR)


DOIS_PONTOS t=tipo PONTO_VIRGULA {
83 List.map (fun id -> DecVar (id,t)) ids
84 }
85
86 argumento : nome = IDENTIFICADOR DOIS_PONTOS t = tipo {
87 (nome,t)
3.0

88 }
89
90 funcao: FUNCTION id=IDENTIFICADOR ABRE_PARENTESE parametros=separated_list
(VIRGULA, argumento) FECHA_PARENTESE DOIS_PONTOS r=tipo PONTO_VIRGULA
91 VAR
92 ds = declaracao*
93 BEGIN
94 cs = comando*
95 END PONTO_VIRGULA {
96 DecFun {
97 fn_nome = id;
98 fn_tiporet = r;
99 fn_formais = parametros;
100 fn_locais = List.flatten ds;
101 fn_corpo = cs
102 }
103 }
104
105
106 tipo: INTEGER { TipoInteger }
107 | REAL { TipoReal }
108 | STRING { TipoString }
109 | CHAR { TipoString }
110 | BOOLEAN { TipoBool }
111
112
113 comando: c=comando_atribuicao { c }
114 | c=comando_if { c }
115 | c=comando_readln { c }
116 | c=comando_write { c }
117 | c=comando_for { c }
118 | c=comando_while { c }
119 | c=comando_case { c }
120 | c=comando_chamada_funcao { c }
121
122
123 comando_atribuicao: esq=expressao ATRIBUICAO dir=expressao PONTO_VIRGULA {
124 CmdAtrib (esq,dir)
125 }
126

127
128
129
130 comando_if: IF ABRE_PARENTESE teste=expressao FECHA_PARENTESE THEN
131 BEGIN
132 entao=comando*
133 END PONTO_VIRGULA
134 senao=option ( ELSE
135 BEGIN
136 cs = comando*
137 END PONTO_VIRGULA {cs} ) {
138 CmdIf (teste, entao, senao)
139 }
140
141 comando_readln: READLN ABRE_PARENTESE xs=separated_nonempty_list(VIRGULA,
expressao) FECHA_PARENTESE PONTO_VIRGULA {
142 CmdReadln xs
143 }
144
3.0

145 funcaoSaida:
146 | c=WRITE { c }
147 | c=WRITELN { c }
148

149 comando_write: funcaoSaida ABRE_PARENTESE xs=separated_nonempty_list(


VIRGULA, expressao) FECHA_PARENTESE PONTO_VIRGULA {
150 CmdWrite xs
151 }
152
153 comando_for: FOR v=expressao ATRIBUICAO e1=expressao TO e2=expressao DO
154 BEGIN
155 corpo=comando*
156 END PONTO_VIRGULA {
157 CmdFor(v, e1, e2,corpo)
158 }
159

160 comando_while: WHILE teste=expressao DO


161 BEGIN
162 corpo=comando+
163 END PONTO_VIRGULA {
164 CmdWhile(teste, corpo)
165 }
166
167
168 caso: e=expressao DOIS_PONTOS cmd=comando { CmdOpCase (e, cmd) }
169
170 comando_case: CASE teste=expressao OF
171 corpo=caso+
172 senao=option(OTHERWISE cs=comando* {cs})
173 END PONTO_VIRGULA {
174 CmdCase(teste, corpo, senao)
175 }
176
177 comando_chamada_funcao: exp=chamada PONTO_VIRGULA {
178 CmdChamFunc exp
179 }
180
181 chamada: id=IDENTIFICADOR ABRE_PARENTESE args=separated_list(VIRGULA,
expressao) FECHA_PARENTESE {
182 ExpressaoChamadaFuncao (id, args)
183 }
184
185 expressao:
186 | v=variavel { ExpressaoVariavel v }
187 | i=LITERAL_INTEGER { ExpressaoInteger i}
188 | s=LITERAL_STRING { ExpressaoString s }
189 | b=LITERAL_BOOLEAN { ExpressaoBool b }
190 | r=LITERAL_REAL { ExpressaoReal r }
191 | c = chamada { c }
192 | e1=expressao op=oper e2=expressao { ExpressaoOperador (op, e1, e2
) }
193 | ABRE_PARENTESE e=expressao FECHA_PARENTESE { e }
194
195 %inline oper:
196 | pos = MAIS { (Mais, pos) }
197 | pos = MENOS { (Menos, pos) }
198 | pos = MULTIPLICACAO { (Multiplicacao, pos) }
199 | pos = DIVISAO { (Divisao, pos) }
200 | pos = MOD { (Mod, pos) }
3.0

201 | pos = MENOR { (Menor, pos) }


202 | pos = MENOR_IGUAL { (MenorIgual, pos) }
203 | pos = MAIOR { (Maior, pos) }
204 | pos = MAIOR_IGUAL { (MaiorIgual,pos) }
205 | pos = IGUAL { (Igual,pos) }
206 | pos = DIFERENTE { (Diferente,pos) }
207 | pos = OR { (Or,pos) }
208 | pos = AND { (And,pos) }
209 | pos = NOT { (Not,pos) }
210

211 variavel: x=IDENTIFICADOR { VarSimples x }

Os compiladores, em geral, so organizados como uma srie de passos. medida que


o compilador deriva conhecimento sobre o cdigo que compila, precisa transmitir esta in-
formao de um passo para outro. E, portanto, necessita de uma representao para todos
os fatos que deriva sobre o programa. Chamamos isto de representao intermediria (IR).
Um exemplo a rvore sinttica abstrata (AST) retm a estrutura essencial da rvore de
derivao, mas elimina os ns irrelevantes. Eis o programa em Ocaml da rvore sinttica
abstrata:
Listagem 3.2: ast.ml
1 (* The type of the abstract syntax tree (AST). *)
2 open Lexing
3
4 type ident = string
5
6 type 'a pos = 'a * Lexing.position (* tipo e posio no arquivo fonte *)
7
8 type 'expr programa = Programa of (ident pos) * declaracoes * ('expr
funcoes) * ('expr comandos)
9

10 and declaracoes = declaracao list


11
12 and 'expr funcoes = ('expr funcao) list
13
14 and 'expr comandos = ('expr comando) list
15

16 and 'expr funcao = DecFun of ('expr decfn)


17
18 and declaracao = DecVar of (ident pos) * tipo
19
20 and 'expr decfn = {
21 fn_nome : ident pos;
22 fn_tiporet: tipo;
23 fn_formais: (ident pos * tipo) list;
24 fn_locais: declaracoes;
25 fn_corpo: 'expr comandos
26 }
27

28 and tipo = TipoInteger


29 | TipoReal
30 | TipoString
31 | TipoBool
32 | TipoVoid
33

34 and 'expr comando =


35 | CmdAtrib of 'expr * 'expr
3.0

36 | CmdIf of 'expr * ('expr comandos) * ('expr comandos option)


37 | CmdReadln of ('expr expressoes)
38 | CmdWrite of ('expr expressoes)
39 | CmdFor of 'expr * 'expr * 'expr * ('expr comandos)
40 | CmdWhile of 'expr * ('expr comandos)
41 | CmdChamFunc of 'expr
42 | CmdCase of 'expr * ('expr comandos) * ('expr comandos option)
43 | CmdOpCase of 'expr * ('expr comando)
44 | CmdReturn of 'expr option
45

46 and constante = ConstInteger of int


47 | ConstString of string
48 | ConstBool of bool
49 | ConstChar of char
50 | ConstReal of float
51

52 and 'expr variaveis = ('expr variavel) list


53
54 and 'expr variavel = VarSimples of ident pos
55
56 and 'expr expressoes = 'expr list
57

58 and operacao =
59 | Mais
60 | Menos
61 | Multiplicacao
62 | Divisao
63 | Mod
64 | Menor
65 | MenorIgual
66 | Maior
67 | MaiorIgual
68 | Igual
69 | Diferente
70 | Or
71 | And
72 | Not

Eis o programa em Ocaml da rvore sinttica abstrata tipada:


Listagem 3.3: tast.ml
1 open Ast
2
3 type expressao =
4 | ExpressaoVariavel of (expressao variavel) * tipo
5 | ExpressaoInteger of int * tipo
6 | ExpressaoString of string * tipo
7 | ExpressaoBool of bool * tipo
8 | ExpressaoReal of float * tipo
9 | ExpressaoVoid
10 | ExpressaoOperador of (operacao * tipo) * (expressao * tipo) * (expressao
* tipo)
11 | ExpressaoChamadaFuncao of ident * (expressao expressoes) * tipo
Captulo 4

Analisador Semntico

A anlise semntica trata a entrada sinttica e transforma-a numa representao mais


simples e mais adaptada a gerao de cdigo. O objetivo da anlise semntica trabalhar
nesse nvel de inter-relacionamento entre partes distintas do programa. As tarefas bsicas
desempenhadas durante a anlise semntica incluem a verificao de tipos, a verificao
do fluxo de controle e a verificao da unicidade da declarao de variveis. Dependendo
da linguagem de programao, outros tipos de verificaes podem ser necessrios. Eis o
programa em Ocaml da rvore sinttica abstrata semntica:
Listagem 4.1: sast.ml
1 open Ast
2
3 type expressao =
4 | ExpressaoVariavel of (expressao variavel)
5 | ExpressaoInteger of int pos
6 | ExpressaoString of string pos
7 | ExpressaoBool of bool pos
8 | ExpressaoReal of float pos
9 | ExpressaoOperador of (operacao pos) * expressao * expressao
10 | ExpressaoChamadaFuncao of (ident pos) * (expressao expressoes)

Eis o programa em Ocaml do analisador semntico:


Listagem 4.2: semantico.ml
1 module Amb = Ambiente
2 module A = Ast
3 module S = Sast
4 module T = Tast
5
6 let rec posicao exp = let open S in
7 match exp with
8 | ExpressaoVariavel v -> (match v with
9 | A.VarSimples (_,pos) -> pos
10 )
11 | ExpressaoInteger (_,pos) -> pos
12 | ExpressaoString (_,pos) -> pos
13 | ExpressaoBool (_,pos) -> pos
14 | ExpressaoReal (_,pos) -> pos
15 | ExpressaoOperador ((_,pos),_,_) -> pos

69
4.0

16 | ExpressaoChamadaFuncao ((_,pos), _) -> pos


17
18 type classe_op = Aritmetico | Relacional | Logico
19

20 let classifica op =
21 let open A in
22 match op with
23 | Not
24 | Or
25 | And -> Logico
26 | Menor
27 | MenorIgual
28 | Maior
29 | MaiorIgual
30 | Igual
31 | Diferente -> Relacional
32 | Mod
33 | Mais
34 | Menos
35 | Multiplicacao
36 | Divisao -> Aritmetico
37

38 let msg_erro_pos pos msg =


39 let open Lexing in
40 let lin = pos.pos_lnum
41 and col = pos.pos_cnum - pos.pos_bol - 1 in
42 Printf.sprintf "Semantico -> linha %d, coluna %d: %s" lin col msg
43

44 let msg_erro nome msg =


45 let pos = snd nome in
46 msg_erro_pos pos msg
47
48 let nome_tipo t =
49 let open A in
50 match t with
51 | TipoInteger -> "integer"
52 | TipoString -> "string"
53 | TipoBool -> "boolean"
54 | TipoReal -> "real"
55 | TipoVoid -> "void"
56
57 let mesmo_tipo pos msg tinf tdec =
58 if tinf <> tdec
59 then
60 let msg = Printf.sprintf msg (nome_tipo tinf) (nome_tipo tdec) in
61 failwith (msg_erro_pos pos msg)
62
63 let rec infere_exp amb exp =
64 match exp with
65 S.ExpressaoInteger n -> (T.ExpressaoInteger (fst n, A.TipoInteger), A.
TipoInteger)
66 | S.ExpressaoString s -> (T.ExpressaoString (fst s, A.TipoString), A.
TipoString)
67 | S.ExpressaoBool b -> (T.ExpressaoBool (fst b, A.TipoBool), A.TipoBool)
68 | S.ExpressaoReal r -> (T.ExpressaoReal (fst r, A.TipoReal), A.TipoReal)
69 | S.ExpressaoVariavel v ->
70 (match v with
71 A.VarSimples nome ->
72 (* Tenta encontrar a definio da varivel no escopo local, se no
4.0

*)
73 (* encontar tenta novamente no escopo que engloba o atual.
Prossegue-se *)
74 (* assim at encontrar a definio em algum escopo englobante ou at
*)
75 (* encontrar o escopo global. Se em algum lugar for encontrado,
*)
76 (* devolve-se a definio. Em caso contrrio, devolve uma exceo
*)
77 let id = fst nome in
78 (try (match (Amb.busca amb id) with
79 | Amb.EntVar tipo -> (T.ExpressaoVariavel (A.VarSimples
nome, tipo), tipo)
80 | Amb.EntFun _ ->
81 let msg = "nome de funcao usado como nome de variavel: "
^ id in
82 failwith (msg_erro nome msg)
83 )
84 with Not_found ->
85 let msg = "A variavel " ^ id ^ " nao foi declarada" in
86 failwith (msg_erro nome msg)
87 )
88 (* | _ -> failwith "infere_exp: no implementado" *)
89 )
90 | S.ExpressaoOperador (op, esq, dir) ->
91 let (esq, tesq) = infere_exp amb esq
92 and (dir, tdir) = infere_exp amb dir in
93

94 let verifica_aritmetico () =
95 (match tesq with
96 A.TipoInteger ->
97 let _ = mesmo_tipo (snd op)
98 "O operando esquerdo eh do tipo %s mas o direito eh
do tipo %s"
99 tesq tdir
100 in tesq (* O tipo da expresso aritmtica como um todo *)
101
102 | A.TipoReal ->
103 let _ = mesmo_tipo (snd op)
104 "O operando esquerdo eh do tipo %s mas o direito eh
do tipo %s"
105 tesq tdir
106 in tesq (* O tipo da expresso aritmtica como um todo *)
107
108 | t -> let msg = "um operador aritmetico nao pode ser usado com o
tipo " ^
109 (nome_tipo t)
110 in failwith (msg_erro_pos (snd op) msg)
111 )
112
113 and verifica_relacional () =
114 (match tesq with
115 A.TipoInteger
116 | A.TipoReal
117 | A.TipoString ->
118 let _ = mesmo_tipo (snd op)
119 "O operando esquerdo eh do tipo %s mas o direito eh do
tipo %s"
120 tesq tdir
4.0

121 in A.TipoBool (* O tipo da expresso relacional sempre booleano


*)
122
123 | t -> let msg = "um operador relacional nao pode ser usado com o
tipo " ^
124 (nome_tipo t)
125 in failwith (msg_erro_pos (snd op) msg)
126 )
127
128 and verifica_logico () =
129 (match tesq with
130 A.TipoBool ->
131 let _ = mesmo_tipo (snd op)
132 "O operando esquerdo eh do tipo %s mas o direito eh do
tipo %s"
133 tesq tdir
134 in A.TipoBool (* O tipo da expresso lgica sempre booleano *)
135
136 | t -> let msg = "um operador logico nao pode ser usado com o tipo
" ^
137 (nome_tipo t)
138 in failwith (msg_erro_pos (snd op) msg)
139 )
140 (*
141 and verifica_cadeia () =
142 (match tesq with
143 A.TipoString ->
144 let _ = mesmo_tipo (snd op)
145 "O operando esquerdo eh do tipo %s mas o direito eh do
tipo %s"
146 tesq tdir
147 in A.TipoString (* O tipo da expresso relacional sempre string
*)
148

149 | t -> let msg = "um operador relacional nao pode ser usado com o
tipo " ^
150 (nome_tipo t)
151 in failwith (msg_erro_pos (snd op) msg)
152 )
153 *)
154 in
155 let op = fst op in
156 let tinf = (match (classifica op) with
157 Aritmetico -> verifica_aritmetico ()
158 | Relacional -> verifica_relacional ()
159 | Logico -> verifica_logico ()
160 (* | Cadeia -> verifica_cadeia () *)
161 )
162 in
163 (T.ExpressaoOperador ((op,tinf), (esq, tesq), (dir, tdir)), tinf)
164
165 | S.ExpressaoChamadaFuncao (nome, args) ->
166 let rec verifica_parametros ags ps fs =
167 match (ags, ps, fs) with
168 (a::ags), (p::ps), (f::fs) ->
169 let _ = mesmo_tipo (posicao a)
170 "O parametro eh do tipo %s mas deveria ser do tipo %s
" p f
171 in verifica_parametros ags ps fs
4.0

172 | [], [], [] -> ()


173 | _ -> failwith (msg_erro nome "Numero incorreto de parametros")
174 in
175 let id = fst nome in
176 try
177 begin
178 let open Amb in
179
180 match (Amb.busca amb id) with
181 (* verifica se 'nome' est associada a uma funo *)
182 Amb.EntFun {tipo_fn; formais} ->
183 (* Infere o tipo de cada um dos argumentos *)
184 let argst = List.map (infere_exp amb) args
185 (* Obtem o tipo de cada parmetro formal *)
186 and tipos_formais = List.map snd formais in
187 (* Verifica se o tipo de cada argumento confere com o tipo
declarado *)
188 (* do parmetro formal correspondente.
*)
189 let _ = verifica_parametros args (List.map snd argst)
tipos_formais
190 in (T.ExpressaoChamadaFuncao (id, (List.map fst argst),
tipo_fn), tipo_fn)
191 | Amb.EntVar _ -> (* Se estiver associada a uma varivel, falhe
*)
192 let msg = id ^ " eh uma variavel e nao uma funcao" in
193 failwith (msg_erro nome msg)
194 end
195 with Not_found ->
196 let msg = "Nao existe a funcao de nome " ^ id in
197 failwith (msg_erro nome msg)
198 let rec verifica_cmd amb tiporet cmd =
199 let open A in
200 match cmd with
201
202 CmdReturn exp ->
203 (match exp with
204 (* Se a funo no retornar nada, verifica se ela foi declarada como
void *)
205 None ->
206 let _ = mesmo_tipo (Lexing.dummy_pos)
207 "O tipo retornado eh %s mas foi declarado como %s"
208 TipoVoid tiporet
209 in CmdReturn None
210 | Some e ->
211 (* Verifica se o tipo inferido para a expresso de retorno confere
com o *)
212 (* tipo declarado para a funo.
*)
213 let (e1,tinf) = infere_exp amb e in
214 let _ = mesmo_tipo (posicao e)
215 "O tipo retornado eh %s mas foi declarado
como %s"
216 tinf tiporet
217 in CmdReturn (Some e1)
218 )
219 | CmdIf (teste, entao, senao) ->
220 let (teste1,tinf) = infere_exp amb teste in
221 (* O tipo inferido para a expresso 'teste' do condicional deve ser
4.0

booleano *)
222 let _ = mesmo_tipo (posicao teste)
223 "O teste do if deveria ser do tipo %s e nao %s"
224 TipoBool tinf in
225 (* Verifica a validade de cada comando do bloco 'ento' *)
226 let entao1 = List.map (verifica_cmd amb tiporet) entao in
227 (* Verifica a validade de cada comando do bloco 'seno', se houver *)
228 let senao1 =
229 match senao with
230 None -> None
231 | Some bloco -> Some (List.map (verifica_cmd amb tiporet) bloco)
232 in
233 CmdIf (teste1, entao1, senao1)
234
235
236 (*
237 | ExpressaoVariavel v -> (match v with
238 | A.VarSimples (_,pos) -> pos
239 )
240 *)
241
242 | CmdAtrib (elem, exp) -> let open Amb in
243 let (exp2, tdir) = infere_exp amb exp in
244 (match elem with
245 S.ExpressaoVariavel v ->
246 ( match v with
247 | A.VarSimples(ch,_) ->
248 ( try
249 (match (Amb.busca amb ch ) with
250 Amb.EntVar tipo -> let (elem_tip, telem) =
infere_exp amb elem
251 and (exp_tip, ttip) = infere_exp amb exp
in
252 let _ = mesmo_tipo (posicao elem) "
Atribuicao com tipos diferentes: %s = %
s"
253 telem ttip
254 in CmdAtrib (elem_tip, exp_tip)
255
256 | Amb.EntFun { tipo_fn; _} -> ( match tipo_fn
with
257 TipoVoid -> let _ = mesmo_tipo (
posicao elem) "Funcao do tipo %
s nao pode receber o valor do
tipo %s"
258 TipoVoid tdir in
259 CmdReturn (None)
260 | tipo -> let _ = mesmo_tipo (
posicao elem) "Funcao do tipo %s
nao pode receber o valor do tipo
%s"
261 tipo tdir in
262 CmdReturn (Some exp2)
263
264 )
265 )
266 with Not_found -> failwith ("A varivel " ^ ch ^ " no
foi declarada")
267 )
4.0

268 )
269 | _ -> failwith ""
270 )
271

272
273 | CmdCase (teste, corpo, senao) ->
274 (* Infere o tipo da variavel a ser tomada no case *)
275 let (teste1,tinf) = infere_exp amb teste in
276
277 (* Verifica a validade de cada comando do bloco 'corpo' *)
278 let corpo1 = List.map (verifica_cmd amb tiporet) corpo in
279
280 (* Verifica a validade de cada comando do bloco 'seno', se houver *)
281 let senao1 =
282 match senao with
283 None -> None
284 | Some bloco -> Some (List.map (verifica_cmd amb tiporet) bloco)
285 in
286 CmdCase(teste1, corpo1, senao1)
287
288 | CmdOpCase (expressao, comando) ->
289 (* Verifica a validade da expressao *)
290 let (expressao1,tinf) = infere_exp amb expressao in
291
292 (* Verifica a validade de cada comando do bloco 'comandos' *)
293 let comando1 = verifica_cmd amb tiporet comando in
294 CmdOpCase (expressao1, comando1)
295

296 | CmdFor (variavel, valorInicial, valorFinal, corpo) ->


297 (* Infere o tipo da variavel *)
298 let (variavel1, tvariavel) = infere_exp amb variavel
299
300 (* Infere o tipo do valorInicial *)
301 and (valorInicial1, tvalorInicial) = infere_exp amb valorInicial in
302
303 let _ = mesmo_tipo (posicao variavel) "Variavel de controle do tipo %s e
valor inicial do tipo %s" tvariavel tvalorInicial in
304
305
306 (* Infere o tipo do valorFinal *)
307 let (valorFinal1, tvalorFinal) = infere_exp amb valorFinal in
308
309 let _ = mesmo_tipo (posicao valorInicial) "Valor inicial do tipo %s e
final do tipo %s" tvalorInicial tvalorFinal in
310
311 (* Verifica a validade de cada comando do bloco 'corpo' *)
312 let corpo1 = List.map (verifica_cmd amb tiporet) corpo in
313
314 CmdFor(variavel1, valorInicial1, valorFinal1, corpo1)
315
316
317 | CmdWhile (teste, comandos) ->
318 let (teste1,tinf) = infere_exp amb teste in
319 (* O tipo inferido para a expresso 'teste' do condicional deve ser
booleano *)
320 let _ = mesmo_tipo (posicao teste)
321 "O teste do if deveria ser do tipo %s e nao %s"
322 TipoBool tinf in
323
4.0

324 (* Verifica a validade de cada comando do bloco 'comandos' *)


325 let comandos1 = List.map (verifica_cmd amb tiporet) comandos in
326 CmdWhile(teste1, comandos1)
327

328 | CmdChamFunc exp ->


329 let (exp,tinf) = infere_exp amb exp in
330 CmdChamFunc exp
331
332 | CmdReadln exps ->
333 (* Verifica o tipo de cada argumento da funo 'entrada' *)
334 let exps = List.map (infere_exp amb) exps in
335 CmdReadln (List.map fst exps)
336
337 | CmdWrite exps ->
338 (* Verifica o tipo de cada argumento da funo 'saida' *)
339 let exps = List.map (infere_exp amb) exps in
340 CmdWrite (List.map fst exps)
341
342 and verifica_fun amb ast =
343 let open A in
344 match ast with
345 A.DecFun {fn_nome; fn_tiporet; fn_formais; fn_locais; fn_corpo} ->
346 (* Estende o ambiente global, adicionando um ambiente local *)
347 let ambfn = Amb.novo_escopo amb in
348 (* Insere os parmetros no novo ambiente *)
349 let insere_parametro (v,t) = Amb.insere_param ambfn (fst v) t in
350 let _ = List.iter insere_parametro fn_formais in
351 (* Insere as variveis locais no novo ambiente *)
352 let insere_local = function
353 (DecVar (v,t)) -> Amb.insere_local ambfn (fst v) t in
354 let _ = List.iter insere_local fn_locais in
355 (* Verifica cada comando presente no corpo da funo usando o novo
ambiente *)
356 let corpo_tipado = List.map (verifica_cmd ambfn fn_tiporet) fn_corpo
in
357 A.DecFun {fn_nome; fn_tiporet; fn_formais; fn_locais; fn_corpo =
corpo_tipado}
358
359
360 let rec verifica_dup xs =
361 match xs with
362 [] -> []
363 | (nome,t)::xs ->
364 let id = fst nome in
365 if (List.for_all (fun (n,t) -> (fst n) <> id) xs)
366 then (id, t) :: verifica_dup xs
367 else let msg = "Parametro duplicado " ^ id in
368 failwith (msg_erro nome msg)
369
370 let insere_declaracao_var amb dec =
371 let open A in
372 match dec with
373 DecVar (nome, tipo) -> Amb.insere_local amb (fst nome) tipo
374
375 let insere_declaracao_fun amb dec =
376 let open A in
377 match dec with
378 DecFun {fn_nome; fn_tiporet; fn_formais; fn_corpo} ->
379 (* Verifica se no h parmetros duplicados *)
4.0

380 let formais = verifica_dup fn_formais in


381 let nome = fst fn_nome in
382 Amb.insere_fun amb nome formais fn_tiporet
383

384
385 (* Lista de cabealhos das funes pr definidas *)
386 let fn_predefs = let open A in [
387 ("readln", [("x", TipoInteger); ("y", TipoInteger)], TipoVoid);
388 ("write", [("x", TipoInteger); ("y", TipoInteger)], TipoVoid);
389 ("writeln", [("x", TipoInteger); ("y", TipoInteger)], TipoVoid)
390 ]
391
392 (* insere as funes pr definidas no ambiente global *)
393 let declara_predefinidas amb =
394 List.iter (fun (n,ps,tr) -> Amb.insere_fun amb n ps tr) fn_predefs
395

396 let semantico ast =


397 (* cria ambiente global inicialmente vazio *)
398 let amb_global = Amb.novo_amb [] in
399 let _ = declara_predefinidas amb_global in
400 let (A.Programa (nome, decs_globais, decs_funs, corpo)) = ast in
401 let _ = List.iter (insere_declaracao_var amb_global) decs_globais in
402 let _ = List.iter (insere_declaracao_fun amb_global) decs_funs in
403 (* Verificao de tipos nas funes *)
404 let decs_funs = List.map (verifica_fun amb_global) decs_funs in
405 (* Verificao de tipos na funo principal *)
406 let corpo = List.map (verifica_cmd amb_global A.TipoVoid) corpo in
407 (A.Programa (nome, decs_globais, decs_funs, corpo), amb_global)
Captulo 5

Interprete

Interpretadores e compiladores tm muito em comum, e executam muitas das mesmas


tarefas. Ambos analisam o programa de entrada e determinam se ou no um programa
vlido; constroem um modelo interno da estrutura e significado do programa; determinam
onde armazenar valores durante a execuo. No entanto, interpretar o cdigo para produzir
um resultado bastante diferente de emitir um programa traduzido que pode ser executado
para produzir o resultado. Eis o programa em Ocaml do interprete:
Listagem 5.1: interprete.ml
1 module Amb = AmbInterp
2 module A = Ast
3 module S = Sast
4 module T = Tast
5
6 exception Valor_de_retorno of T.expressao
7
8 let obtem_nome_tipo_var exp = let open T in
9 match exp with
10 | ExpressaoVariavel (v,tipo) ->
11 (match v with
12 | A.VarSimples (nome,_) -> (nome,tipo)
13 | _ -> failwith "obtem_nome_tipo_var: nao implementado"
14 )
15 | _ -> failwith "obtem_nome_tipo_var: nao eh variavel"
16
17 let pega_int exp =
18 match exp with
19 | T.ExpressaoInteger (i,_) -> i
20 | _ -> failwith "pega_int: nao eh inteiro"
21
22 let pega_real exp =
23 match exp with
24 | T.ExpressaoReal (i,_) -> i
25 | _ -> failwith "pega_real: nao eh real"
26
27 let pega_string exp =
28 match exp with
29 | T.ExpressaoString (s,_) -> s
30 | _ -> failwith "pega_string: nao eh string"
31
32 let pega_bool exp =

78
5.0

33 match exp with


34 | T.ExpressaoBool (b,_) -> b
35 | _ -> failwith "pega_bool: nao eh booleano"
36

37 type classe_op = Aritmetico | Relacional | Logico


38
39 let classifica op =
40 let open A in
41 match op with
42 | Not
43 | Or
44 | And -> Logico
45 | Menor
46 | MenorIgual
47 | Maior
48 | MaiorIgual
49 | Igual
50 | Diferente -> Relacional
51 | Mod
52 | Mais
53 | Menos
54 | Multiplicacao
55 | Divisao -> Aritmetico
56
57
58 let rec interpreta_exp amb exp =
59 let open A in
60 let open T in
61 match exp with
62 | ExpressaoInteger _
63 | ExpressaoString _
64 | ExpressaoReal _
65 | ExpressaoVoid
66 | ExpressaoBool _ -> exp
67 | ExpressaoVariavel _ ->
68 let (id,tipo) = obtem_nome_tipo_var exp in
69 (* Tenta encontrar o valor da varivel no escopo local, se no *)
70 (* encontrar, tenta novamente no escopo que engloba o atual. Prossegue
-se *)
71 (* assim at encontrar o valor em algum escopo englobante ou at *)
72 (* encontrar o escopo global. Se em algum lugar for encontrado,
*)
73 (* devolve-se o valor. Em caso contrrio, devolve uma exceo *)
74 (match (Amb.busca amb id) with
75 | Amb.EntVar (tipo, v) ->
76 (match v with
77 | None -> failwith ("varivel nao inicializada: " ^ id)
78 | Some valor -> valor
79 )
80 | _ -> failwith "interpreta_exp: expvar"
81 )
82 | ExpressaoOperador ((op,top), (esq, tesq), (dir,tdir)) ->
83 let vesq = interpreta_exp amb esq
84 and vdir = interpreta_exp amb dir in
85
86 let interpreta_aritmetico () =
87 (match tesq with
88 | TipoInteger ->
89 (match op with
5.0

90 | Mais -> ExpressaoInteger (pega_int vesq + pega_int vdir, top)


91 | Menos -> ExpressaoInteger (pega_int vesq - pega_int vdir, top)
92 | Multiplicacao -> ExpressaoInteger (pega_int vesq * pega_int
vdir, top)
93 | Divisao -> ExpressaoInteger (pega_int vesq / pega_int vdir,
top)
94 | Mod -> ExpressaoInteger (pega_int vesq mod pega_int vdir, top)
95 | _ -> failwith "interpreta_aritmetico"
96 )
97 | TipoReal ->
98 (match op with
99 | Mais -> ExpressaoReal (pega_real vesq +. pega_real vdir, top)
100 | Menos -> ExpressaoReal (pega_real vesq -. pega_real vdir, top)
101 | Multiplicacao -> ExpressaoReal (pega_real vesq *. pega_real
vdir, top)
102 | Divisao -> ExpressaoReal (pega_real vesq /. pega_real vdir,
top)
103 | _ -> failwith "interpreta_aritmetico"
104 )
105 | _ -> failwith "interpreta_aritmetico"
106 )
107

108 and interpreta_relacional () =


109 (match tesq with
110 | TipoInteger ->
111 (match op with
112 | Menor -> ExpressaoBool (pega_int vesq < pega_int vdir, top)
113 | MenorIgual -> ExpressaoBool (pega_int vesq <= pega_int vdir, top)
114 | Maior -> ExpressaoBool (pega_int vesq > pega_int vdir, top)
115 | MaiorIgual -> ExpressaoBool (pega_int vesq >= pega_int vdir, top)
116 | Igual -> ExpressaoBool (pega_int vesq == pega_int vdir, top)
117 | Diferente -> ExpressaoBool (pega_int vesq != pega_int vdir,
top)
118 | _ -> failwith "interpreta_relacional"
119 )
120 | TipoReal ->
121 (match op with
122 | Menor -> ExpressaoBool (pega_real vesq < pega_real vdir, top)
123 | MenorIgual -> ExpressaoBool (pega_real vesq <= pega_real vdir, top
)
124 | Maior -> ExpressaoBool (pega_real vesq > pega_real vdir, top)
125 | MaiorIgual -> ExpressaoBool (pega_real vesq >= pega_real vdir, top
)
126 | Igual -> ExpressaoBool (pega_real vesq == pega_real vdir,
top)
127 | Diferente -> ExpressaoBool (pega_real vesq != pega_real vdir
, top)
128 | _ -> failwith "interpreta_relacional"
129 )
130 | TipoString ->
131 (match op with
132 | Menor -> ExpressaoBool (pega_string vesq < pega_string vdir,
top)
133 | MenorIgual -> ExpressaoBool (pega_string vesq <= pega_string vdir,
top)
134 | Maior -> ExpressaoBool (pega_string vesq > pega_string vdir,
top)
135 | MaiorIgual -> ExpressaoBool (pega_string vesq >= pega_string vdir,
top)
5.0

136 | Igual -> ExpressaoBool (pega_string vesq == pega_string vdir,


top)
137 | Diferente -> ExpressaoBool (pega_string vesq != pega_string
vdir, top)
138 | _ -> failwith "interpreta_relacional"
139 )
140 | TipoBool ->
141 (match op with
142 | Menor -> ExpressaoBool (pega_bool vesq < pega_bool vdir, top)
143 | MenorIgual -> ExpressaoBool (pega_bool vesq <= pega_bool vdir, top
)
144 | Maior -> ExpressaoBool (pega_bool vesq > pega_bool vdir, top)
145 | MaiorIgual -> ExpressaoBool (pega_bool vesq >= pega_bool vdir, top
)
146 | Igual -> ExpressaoBool (pega_bool vesq == pega_bool vdir, top)
147 | Diferente -> ExpressaoBool (pega_bool vesq != pega_bool vdir,
top)
148 | _ -> failwith "interpreta_relacional"
149 )
150 | _ -> failwith "interpreta_relacional"
151 )
152

153 and interpreta_logico () =


154 (match tesq with
155 | TipoBool ->
156 (match op with
157 | Not -> ExpressaoBool ( not ( pega_bool vdir ), top)
158 | Or -> ExpressaoBool (pega_bool vesq || pega_bool vdir, top)
159 | And -> ExpressaoBool (pega_bool vesq && pega_bool vdir, top)
160 | _ -> failwith "interpreta_logico"
161 )
162 | _ -> failwith "interpreta_logico"
163 )
164 (*
165 and interpreta_cadeia () =
166 (match tesq with
167 | TipoString ->
168 (match op with
169 | Concat -> ExpString (pega_string vesq ^ pega_string vdir, top)
170 | _ -> failwith "interpreta_cadeia"
171 )
172 | _ -> failwith "interpreta_cadeia"
173 )
174 *)
175 in
176 let valor = (match (classifica op) with
177 Aritmetico -> interpreta_aritmetico ()
178 | Relacional -> interpreta_relacional ()
179 | Logico -> interpreta_logico ()
180 (* | Cadeia -> interpreta_cadeia () *)
181 )
182 in
183 valor
184
185 | ExpressaoChamadaFuncao (id, args, tipo) ->
186 let open Amb in
187 ( match (Amb.busca amb id) with
188 | Amb.EntFun {tipo_fn; formais; locais; corpo} ->
189 (* Interpreta cada um dos argumentos *)
5.0

190 let vargs = List.map (interpreta_exp amb) args in


191 (* Associa os argumentos aos parmetros formais *)
192 let vformais = List.map2 (fun (n,t) v -> (n, t, Some v))
formais vargs
193 in interpreta_fun amb id vformais locais corpo
194 | _ -> failwith "interpreta_exp: expchamada"
195 )
196
197 and interpreta_fun amb fn_nome fn_formais fn_locais fn_corpo =
198 let open A in
199 (* Estende o ambiente global, adicionando um ambiente local *)
200 let ambfn = Amb.novo_escopo amb in
201 let insere_local d =
202 match d with
203 (DecVar (v,t)) -> Amb.insere_local ambfn (fst v) t None
204 in
205 (* Associa os argumentos aos parmetros e insere no novo ambiente *)
206 let insere_parametro (n,t,v) = Amb.insere_param ambfn n t v in
207 let _ = List.iter insere_parametro fn_formais in
208 (* Insere as variveis locais no novo ambiente *)
209 let _ = List.iter insere_local fn_locais in
210 (* Interpreta cada comando presente no corpo da funo usando o novo
211 ambiente *)
212 try
213 let _ = List.iter (interpreta_cmd ambfn) fn_corpo in T.ExpressaoVoid
214 with
215 Valor_de_retorno expret -> expret
216

217 and interpreta_cmd amb cmd =


218 let open A in
219 let open T in
220 match cmd with
221 CmdReturn exp ->
222 (* Levantar uma exceo foi necessria pois, pela semntica do comando
de
223 retorno, sempre que ele for encontrado em uma funo, a computao
224 deve parar retornando o valor indicado, sem realizar os demais
comandos.
225 *)
226 (match exp with
227 (* Se a funo no retornar nada, ento retorne ExpVoid *)
228 None -> raise (Valor_de_retorno ExpressaoVoid)
229 | Some e ->
230 (* Avalia a expresso e retorne o resultado *)
231 let e1 = interpreta_exp amb e in
232 raise (Valor_de_retorno e1)
233 )
234
235 | CmdIf (teste, entao, senao) ->
236 let teste1 = interpreta_exp amb teste in
237 (match teste1 with
238 ExpressaoBool (true,_) ->
239 (* Interpreta cada comando do bloco 'ento' *)
240 List.iter (interpreta_cmd amb) entao
241 | _ ->
242 (* Interpreta cada comando do bloco 'seno', se houver *)
243 (match senao with
244 None -> ()
245 | Some bloco -> List.iter (interpreta_cmd amb) bloco
5.0

246 )
247 )
248
249

250 (*
251 | CmdAtrib (elem, exp) ->
252 (* Interpreta o lado direito da atribuio *)
253 let exp = interpreta_exp amb exp
254 (* Faz o mesmo para o lado esquerdo *)
255 and (elem1,tipo) = obtem_nome_tipo_var elem in
256 Amb.atualiza_var amb elem1 tipo (Some exp)
257 *)
258
259 | CmdAtrib (elem, exp) ->
260 (* Interpreta o lado direito da atribuio *)
261 let exp = interpreta_exp amb exp
262 (* Faz o mesmo para o lado esquerdo *)
263 and (elem1,tipo) = obtem_nome_tipo_var elem in
264 Amb.atualiza_var amb elem1 tipo (Some exp)
265
266 | CmdChamFunc exp -> ignore ( interpreta_exp amb exp )
267

268 | CmdWhile (teste, comandos) ->


269 let teste1 = interpreta_exp amb teste in
270 (match teste1 with
271 ExpressaoBool (true,_) ->
272 (* Interpreta cada comando do bloco 'comandos' *)
273 let _ = List.iter (interpreta_cmd amb) comandos in interpreta_cmd
amb cmd
274 | ExpressaoBool (false,_) -> ignore()
275 | _ -> failwith "Teste de while invalido"
276 )
277
278 | CmdFor (variavel, valorInicial, valorFinal, corpo) ->
279
280 (* Interpreta o valorInicial*)
281 let valorInicial1 = interpreta_exp amb valorInicial and
282
283 (* Faz o mesmo para a variavel *)
284 (variavel1,tipo) = obtem_nome_tipo_var variavel in
285 let _ = Amb.atualiza_var amb variavel1 tipo (Some valorInicial1) in
286
287
288
289 let exp = ExpressaoOperador ((MenorIgual, tipo), (variavel, tipo), (
valorFinal,tipo)) in
290 let teste1 = interpreta_exp amb exp in
291 (match teste1 with
292 (* Interpreta cada comando do bloco 'corpo' *)
293 ExpressaoBool (true,_) ->
294 (match valorInicial1 with
295 ExpressaoInteger(val1,_) ->
296 (match valorFinal with
297 ExpressaoInteger(val2,_) ->
298 for var = val1 to val2 do
299 List.iter (interpreta_cmd amb) corpo
300 done
301 | _ -> failwith "Teste de while invalido"
302 )
5.0

303 | _ -> failwith "Teste de while invalido"


304 )
305 | ExpressaoBool(false,_) -> ignore()
306 | _ -> failwith "Teste de while invalido"
307 )
308
309 | CmdOpCase (expressao, comando) -> ignore()
310 | CmdCase (teste, corpo, senao) -> ignore()
311 | CmdReadln exps ->
312 (* Obtem os nomes e os tipos de cada um dos argumentos *)
313 let nts = List.map (obtem_nome_tipo_var) exps in
314 let leia_var (nome,tipo) =
315 let valor =
316 (match tipo with
317 | A.TipoInteger -> T.ExpressaoInteger (read_int (), tipo)
318 | A.TipoString -> T.ExpressaoString (read_line (), tipo)
319 | A.TipoReal -> T.ExpressaoReal (read_float(), tipo)
320 | _ -> failwith "leia_var: nao implementado"
321 )
322 in Amb.atualiza_var amb nome tipo (Some valor)
323 in
324 (* L o valor para cada argumento e atualiza o ambiente *)
325 List.iter leia_var nts
326
327 | CmdWrite exps ->
328 (* Interpreta cada argumento da funo 'saida' *)
329 let exps = List.map (interpreta_exp amb) exps in
330 let imprima exp =
331 (match exp with
332 | T.ExpressaoInteger (n,_) -> let _ = print_int n in
print_string " "
333 | T.ExpressaoString (s,_) -> let _ = print_string s in print_string
" "
334 | T.ExpressaoBool (b,_) ->
335 let _ = print_string (if b then "true" else "false")
336 in print_string " "
337 | T.ExpressaoReal (n,_) -> let _ = print_float n in print_string " "
338 | _ -> failwith "imprima: nao implementado"
339 )
340 in
341 let _ = List.iter imprima exps in
342 print_newline ()
343
344 let insere_declaracao_var amb dec =
345 match dec with
346 A.DecVar (nome, tipo) -> Amb.insere_local amb (fst nome) tipo
None
347
348 let insere_declaracao_fun amb dec =
349 let open A in
350 match dec with
351 DecFun {fn_nome; fn_tiporet; fn_formais; fn_locais; fn_corpo} ->
352 let nome = fst fn_nome in
353 let formais = List.map (fun (n,t) -> ((fst n), t)) fn_formais in
354 Amb.insere_fun amb nome formais fn_locais fn_tiporet fn_corpo
355
356
357 (* Lista de cabealhos das funes pr definidas *)
358 let fn_predefs = let open A in [
5.0

359 ("readln", [("x", TipoInteger); ("y", TipoInteger)], TipoVoid, []);


360 ("write", [("x", TipoInteger); ("y", TipoInteger); ("x", TipoReal); ("y
", TipoReal)], TipoVoid, []);
361 ("writeln", [("x", TipoInteger); ("y", TipoInteger); ("x", TipoReal);
("y", TipoReal)], TipoVoid, [])
362 ]
363
364 (* insere as funes pr definidas no ambiente global *)
365 let declara_predefinidas amb =
366 List.iter (fun (n,ps,tr,c) -> Amb.insere_fun amb n ps [] tr c)
fn_predefs
367
368 let interprete ast =
369 (* cria ambiente global inicialmente vazio *)
370 let amb_global = Amb.novo_amb [] in
371 let _ = declara_predefinidas amb_global in
372 let (A.Programa (nome, decs_globais, decs_funs, corpo)) = ast in
373 let _ = List.iter (insere_declaracao_var amb_global) decs_globais in
374 let _ = List.iter (insere_declaracao_fun amb_global) decs_funs in
375 (* Interpreta a funo principal *)
376 let resultado = List.iter (interpreta_cmd amb_global) corpo in
377 resultado

You might also like