• Nenhum resultado encontrado

Laboratório!de!Linguagens!de!Programação! Prof.!Andrei!Rimsa!Álvares! Trabalho(Prático(I(

N/A
N/A
Protected

Academic year: 2021

Share "Laboratório!de!Linguagens!de!Programação! Prof.!Andrei!Rimsa!Álvares! Trabalho(Prático(I("

Copied!
7
0
0

Texto

(1)

Trabalho(Prático(I(

1.(Objetivo(

O! objetivo! desse! trabalho! é! desenvolver! um! interpretador! para! uma!

linguagem!de!programação!fictícia!chamada!MiniLab.!Essa!linguagem!é!capaz!de!

executar!operações!sobre!matrizes!de!forma!mais!fácil!e!prática.!

2.(Contextualização(

Um!exemplo!de!aplicação!do!uso!de!matrizes!é!o!cálculo!do!determinante.!

A!seguir!é!dado!um!programa!para!esse!propósito.!

# read the random matrix

dim = input("Entre com a dimensao: ");

matrix = [].rand(dim, dim);

# show the matrix

show(matrix);

# calculate the first part of the determinant

det1 = 0;

for c = [].seq(0, dim-1)

j = c;

tmp = 1;

for i = [].seq(0, dim-1)

tmp = tmp * matriz.value(i, j);

j = (j + 1) % dim;

end

det1 = det1 + tmp;

end

# calculate the second part of the determinant

det2 = 0;

for c = [].iseq(dim-1, 0)

j = c;

tmp = 1;

for i = [].seq(0, dim-1)

tmp = tmp * matriz.value(i, j);

j = (j - 1) % dim;

if j < 0

j = j + dim;

end

end

det2 = det2 + tmp;

end

# print the determinant

show(" = " (det1 - det2));

det.lab

!

(2)

!

Um! programa! em! MiniLab! possui! uma! memória! indexada! através! de!

nomes!de!variáveis!que!armazenam!inteiros!ou!matrizes.!Todas!as!variáveis!do!

sistema!possuem!visibilidade!global.!Operações!aritméticas!só!podem!ser!feitas!

em!inteiros.!A!linguagem!possui!comentários!de!uma!linha!onde!são!ignorados!

qualquer! sequência! de! caracteres! após! o! símbolo! #! (hashtag).! A! linguagem!

possui!as!seguintes!características:!

• Declarações:(

o

input

:!ler!um!inteiro!do!usuário!pelo!teclado.!

o

show

:!imprimir!uma!sequência!de!texto!ou!matriz.!

o

assign

:!guardar!um!inteiro!ou!matriz!em!uma!variável.!

o

if

:!!executar!comandos!baseado!em!expressões!condicionais.!!

o

while

:! repetir! comandos! enquanto! a! expressão! condicional! for!

verdadeira.!

o

for

:!percorrer!os!elementos!de!uma!matriz.!

• Valores:(

!!!!!!!String:(uma!sequência!de!caracteres!entre!aspas!duplas.(

Variável:!começa!com!letra!seguido!de!letras!e!dígitos.!

Inteiro:(constante!inteiras!formadas!por!dígitos.!

Lógico:(operações!de!comparações!que!obtém!um!valor!lógico.!

Matriz:!uma!matriz!de!inteiros!com!dimensões.!

• Operadores:(

o Inteiro:!

+

! (adição),!

-

! (subtração),!

*

! (multiplicação),!

/

! (divisão),!

%

!(resto!inteiro)!

o Lógico:(

==

!(igual),!

!=

!(diferença),!

<

!(menor),!

>

!(maior),!

<=

!(menor!

igual),!

>=

!(maior!igual)!

o Conectores:!&!(E!lógico)!|!(OU!lógico)!!

• Funções(de(matrizes:!

o Geração:!

!

null(i, j)

:(cria!uma!matriz!

i x j

!preenchida!com!zeros!.!

!

fill(i, j, v)

:!cria!uma!matriz!

i x j

!preenchida!com!

v

.!

!

rand(i, j)

:!cria!uma!matriz!

i x j

!com!valores!aleatórios!

entre!0!e!100.!

!

id(i, j)

:!cria!uma!matriz!identidade!

i x j

!(diagonal!com!

valor!1,!outras!com!0).!

!

seq(x, y)

:! cria! uma! vetor! com! os! elementos! de! x! a! y!

incrementados!por!uma!unidade.!Ex.:!seq(2,!5)!=![2,!3,!4,!5].!

!

iseq(x, y)

:! cria! uma! vetor! com! os! elementos! de! x! a! y!

decrementados!por!uma!unidade.!Ex.:!seq(8,!5)!=![8,!7,!6,!5].!

o Operações:(

!

opposed()

:! obtém! uma! (nova)! matriz! oposta! (inverte! o!

sinal!dos!elementos).!

!

transposed()

:! obtém! uma! (nova)! matriz! transposta!

(3)

!

x.sum(y)

:!soma!a!matriz!

x

!com!matriz!

y

!e!retorna!uma!nova!

matriz! resultante.! As! matrizes! devem! ter! a! mesma!

dimensão.!

!

x.mul(y)

:!multiplica!a!matriz!

x

!com!matriz!

y

!e!retorna!uma!

nova! matriz! resultante.! A! linha! da! matriz!

x

! tem! que! casar!

com!a!coluna!da!matriz!

y

!e!a!coluna!da!matriz!

x

!com!a!linha!

da!matriz!

y

.!

!

x.mul(v)

:! multiplica! todos! os! elementos! da! matriz!

x

! pelo!

escalar!

v

!e!retorna!uma!nova!matriz!resultante.!

o Informação:!

!

size()

:!obtém!o!tamanho!da!matriz!(linhas!x!colunas).!

!

rows()

:!obtém!o!número!de!linhas.!

!

cols()

:!obtém!o!número!de!colunas.!

!

value(i, j)

:!obtém!o!valor!na!posição!

(i, j)

!da!matriz.!

3.(Gramática(

A!gramática!da!linguagem!MiniLab!é!dada!a!seguir!no!formato!de!Backus_

Naur!estendida!(EBNF):!

<statements> ::= <statement> { <statement> }

<statement> ::= <show> | <assign> | <if> | <while> | <for>

<show> ::= show '(' <text> ')' ';'

<assign> ::= <var> '=' <expr> ';'

<if> ::= if <boolexpr> <statements> [ else <statements> ] end

<while> ::= while <boolexpr> <statements> end

<for> ::= for <var> '=' <value> <statements> end

<text> ::= { <string> | <expr> }

<boolexpr> ::= <expr> <boolop> <expr> { ('&' | '|') <boolexpr> }

<boolop> ::= '==' | '!=' | '<' | '>' | '<=' | '>='

<expr> ::= <term> [ ('+' | '-') <term> ]

<term> ::= <factor> [ ('*' | '/' | '%') <factor> ]

<factor> ::= <number> | <input> | <value> | '(' <expr> ')'

<input> ::= input '(' <text> ')'

<value> ::= (<var> | <gen>)

{ '.' (<opposed> | <transposed> | <sum> | <mul>) }

[ '.' (<size> | <rows> | <cols> | <val>) ]

(4)

<transposed> ::= transposed '(' ')'

<sum> ::= sum '(' <expr> ')'

<mul> ::= mul '(' <expr> ')'

<size> ::= size '(' ')'

<rows> ::= rows '(' ')'

<cols> ::= cols '(' ')'

<val> ::= value '(' <expr> ',' <expr> ')'

<gen> ::= '[' ']' '.' (<null> | <fill> | <rand> | <id> | <seq> | <iseq>)

<null> ::= null '(' <expr> ',' <expr> ')'

<fill> ::= fill '(' <expr> ',' <expr> ',' <expr> ')'

<rand> ::= rand '(' <expr> ',' <expr> ')'

<id> ::= id '(' <expr> ',' <expr> ')'

<seq> ::= seq '(' <expr> ',' <expr> ')'

<iseq> ::= iseq '(' <expr> ',' <expr> ')'

4.(Instruções(

Deve!ser!desenvolvido!um!interpretador!em!linha!de!comando!que!recebe!

um! programa_fonte! na! linguagem! MiniLab! como! argumento! e! executa! os!

comandos!especificados!pelo!programa.!Por!exemplo,!para!o!programa!

det.lab

!

deve_se!produzir!uma!saída!semelhante!a:!

$ mlab

Usage: ./mlab [MiniLab File]

$ mlab det.lab

Entre com a dimensão:

3

[2, 3, 1]

[1, 2, 3]

[1, 0, 1]

= 8

O! programa! deverá! abortar! sua! execução,! em! caso! de! qualquer! erro!

léxico,!sintático!ou!semântico,!indicando!uma!mensagem!de!erro.!As!mensagens!

são!padronizadas!indicando!o!número!da!linha!(2!dígitos)!onde!ocorreram:!

Tipo(de(Erro(

Mensagem(

Léxico!

Lexema!inválido![lexema]!

Fim!de!arquivo!inesperado!

Sintático!

Lexema!não!esperado![lexema]!

Fim!de!arquivo!inesperado!

Semântico!

Operação!inválida!

Tipos!inválidos!

Exemplo!de!mensagem!de!erro:!

(5)

03: Lexema não esperado [;]

!

5.(Avaliação

!

(

O!trabalho!deve!ser!feito!em!grupo!de!até!dois!alunos,!sendo!esse!limite!

superior! estrito.! O! trabalho! será! avaliado! em! 15! pontos,! onde! essa! nota! será!

multiplicada! por! um! fator! entre! 0.0! e! 1.0! para! compor! a! nota! de! cada! aluno!

individualmente.! Esse! fator! poderá! estar! condicionado! a! apresentações!

presenciais!a!critério!do!professor.!

Trabalhos!copiados,!parcialmente!ou!integralmente,!serão!avaliados!com!

nota!ZERO,!sem!direito!a!contestação.!Você!é!responsável!pela!segurança!de!seu!

código,!não!podendo!alegar!que!outro!grupo!o!utilizou!sem!o!seu!consentimento.!

6.(Submissão(

(

O! trabalho! deverá! ser! submetido! até! as! 23:55! do! dia! 03/10/2016!

(segunda_feira)!via!sistema!acadêmico!(Moodle)!em!pasta!específica.!Não!serão!

aceitos,! em! hipótese! alguma,! trabalhos! enviados! por! e_mail! ou! por! quaisquer!

outras!fontes.!

(6)

1"

3"

letra&

Espaço&

\t&\r&\n&&&

letra&

dígito&

≠"letra,&dígito&

ungetc"

8"

;&&.&,&(&)&[&]&&&|&+&<&*&/&%&&

!&

=&

6"

≠"dígito&

ungetc"

=&<&>&

5"

=&

4"

≠"=&

ungetc"

2"

#&

≠"\n&

\n&

7"

"&

≠""&

"&

(7)

+ execute() : void

+ addCommand(c : Command) : void + execute() : void

+ value() : T + line() : int + Value(line : int) - line : int Value<T> + value() : String + StringValue(line : int) StringValue + value() : int + IntValue(line : int) IntValue + value() : boolean + BoolValue(line : int) BoolValue + value() : String + StringConcat(left : Value<?>, right : Value<?>) - right : Value<?> - left : Value<?>

StringConcat + value() : boolean

+ CompareBoolValue(op : RelOp, left : Value<?>, right : Value<?>, line : int) - right : Value<?> - left : Value<?> - op : RelOp CompareBoolValue + GreaterEqual : int = 6 + GreaterThan : int = 5 + LowerEqual : int = 4 + LowerThan : int = 3 + NotEqual : int = 2 + Equal : int = 1 <<enum>> RelOp * 1 <boolean> + Or : int = 2 + And : int = 1 <<enum>> BoolOp + value() : boolean

+ DualBoolExpr(op : BoolOp, left : CompareBoolValue, right : CompareBoolValue, line : int) - right : BoolValue - left : BoolValue - op : BoolOp DualBoolExpr * 1 + value() : int

+ DualIntExpr(op : IntOp, left : Value<?>, right : Value<?>, line : int) - right : Value<?> - left : Value<?> - op : IntOp DualIntExpr + Mod : int = 5 + Div : int = 4 + Mul : int = 3 + Sub : int = 2 + Add : int = 1 <<enum>> IntOp + value() : int + ConstIntValue(value : int, line : int) - value : int ConstIntValue * 1 + value() : String + ConstStringValue(value : String) - value : String ConstStringValue + execute() : void

+ AssignCommand(var : Variable, value : Value<?>, line : int)

+ execute() : void

+ WhileCommand(expr : BoolValue, cmd : Command, line : int) + execute() : void

+ IfCommand(expr : BoolValue, then : Command, else : Command, line : int) + IfCommand(expr : BoolValue, then : Command, line : int)

<string> + execute() : void

+ ForCommand(var : Variable, value : Value<?>, cmd : Command, line : int)

+ value() : Matrix + MatrixValue(line : int)

MatrixValue + iseq(from : int, to : int) : Matrix

+ seq(from : int, to : int) : Matrix + id(r : int, c : int) : Matrix + rand(r : int, c : int) : Matrix + fill(r : int, c : int, v : int) : Matrix + null(r : int, c : int) : Matrix + mul(n : int) : Matrix + mul(m : Matrix) : Matrix + sum(m : Matrix) : Matrix + transposed() : Matrix + opposed() : Matrix + value(r : int, c : int) : int + cols() : int + rows() : int + size() : int + show() : void + setValue(r : int, c : int, v : int) : void

+ value() : Matrix

+ NullMatrixValue(r : Value<?>, c : Value<?>, line : int) - c : Value<?>

- r : Value<?> NullMatrixValue

<Matrix>

+ value() : Matrix + OpposedMatrixValue(m : Value<?>, line : int) - matrix : Value<?>

OpposedMatrixValue

+ value() : Matrix + TransposedMatrixValue(m : Value<?>, line : int) - matrix : Value<?>

TransposedMatrixValue

+ value() : Matrix

+ MulMatrixValue(m : Value<?>, v : Value<?>, line : int) - value : Value<?>

- matrix : Value<?> MulMatrixValue

+ value() : Matrix

+ SumMatrixValue(m1 : Value<?>, m2 : Value<?>, line : int) - matrix2 : Value<?>

- matrix1 : Value<?> SumMatrixValue

+ value() : Matrix

+ FillMatrixValue(r : Value<?>, c : Value<?>, v : Value<?>, line : int) - v : Value<?>

- c : Value<?> - r : Value<?>

FillMatrixValue

+ value() : Matrix

+ RandMatrixValue(r : Value<?>, c : Value<?>, line : int) - c : Value<?>

- r : Value<?> RandMatrixValue

+ value() : Matrix

+ SeqMatrixValue(from : Value<?>, to : Value<?>, inverted : boolean, line : int) - inverted : boolean

- to : Value<?> - from : Value<?>

SeqMatrixValue

+ value() : Matrix + IdMatrixValue(r : Value<?>, c : Value<?>, line : int) - c : Value<?>

- r : Value<?> IdMatrixValue

+ value() : int + IntMatrixValue(m : Value<?>, line : int) # matrix : Value<?>

IntMatrixValue

+ value() : int + SizeIntMatrixValue(m : Value<?>, line : int)

SizeIntMatrixValue

+ value() : int + RowsIntMatrixValue(m : Value<?>, line : int)

RowsIntMatrixValue

+ value() : int + ColsIntMatrixValue(m : Value<?>, line : int)

ColsIntMatrixValue + value() : int

+ ValueIntMatrixValue(m : Value<?>, v1 : Value<?>, v2 : Value<?>, line : int) - v2 : Value<?>

- v1 : Value<?> ValueIntMatrixValue + value() : int

+ InputIntValue(string : Value<?>, line : int) - string : Value<?>

InputIntValue

+ value() : Value<?> + setValue(value : Value<?>) : void + getName() : String + Variable(name : String) - value : Value<?> - name : String Variable <Value<?>> <int> + value() : Matrix + RefMatrixValue(m : Matrix, line : int) - m : Matrix

Referências

Documentos relacionados