Beruflich Dokumente
Kultur Dokumente
jsp@di.uminho.pt!
- Estudo de uma linguagem imperativa simples! - Semntica operacional! - Semntica axiomtica (breve referncia)! - O !-calculus! - O sistema de tipos simples! - Estudo de linguagens de programao estrita e no-! - Semntica denotacional (introduo) e outros tpicos
Temas
Avaliao
- Dois testes com peso 50%! - Exame nal recurso ! - Trabalho a pedido (at 2 valores compensao)
Bibliograa Livros
- Reynolds, J.C. Theories of Programming Languages.
Cambridge Univ. Press, 1998!
Bibliograa Notas
- Pitts A. M. Lecture Notes on Semantics of
Programming Languages. Univ Cambridge, 1997-2002!
que constituem a linguagem, bem como das demais categorias sintcticas (comandos, programas)
Informal Semantics
Semntica Informal
O comando C executado enquanto o s executed repeatedly so long as therepetidamente value of antes da execuo do comando.
valor da expresso for Verdadeiro remains . The test B takes place before , sendo o teste feito
he command.
Semntica Formal
do comportamento independente da Especicao mquina" analisar, processar, e optimizar os Permite programas de forma correcta" desenho de novas linguagens de programao, No pode ser til na claricao de aspectos subtis
sugerir novas caractersticas das linguagens (por exemplo o !-calculus anterior programao funcional)
Temas
- Estudo de uma linguagem imperativa simples! - Semntica operacional! - Semntica axiomtica (breve referncia)! - O !-calculus! - O sistema de tipos simples! - Estudo de linguagens de programao estrita e no-! - Semntica denotacional (introduo) e outros tpicos
n systems dened
ed by
Sistemas de Transio
Transition systems dened
Um sistema de transies constitudo por um conjunto A transition system is speci ed byrelao binria de transio de conguraes e por uma entre conguraes:
a set , and . a binary relation .
The elements of
states), and the binary relation is written inx, i.e. are related by
by . means and
S.T. - Conceitos
fecho reexivo-transitivo da relao de transio! sistema de transio determinstico! congurao normal! conguraes iniciais e nais ou terminais
NB: uma congurao normal que no seja terminal de alguma forma mal-formada (bloqueada)
Syntax
Syntax Phrases
nds
Commands
ressions
expressions
Integer expressions
pressions
expressions
Boolean expressions
isaavery very simple language for for describing, incontext a structured structured on numbers via the manipulation of describing, state. In this we is simple language in a on numbers via the manipulation of state. state. In this this context context we ca ca on numbers via manipulation of In we nite number ofthe locations (registers) for, storing integers. , the set integer the set of of integers ; nite number of locations (registers) for storing integers. in nite number for of locations (registers) for storing integers. int are notations state-dependent integer and boolean values; arenotations notationsfor forstate-dependent state-dependent integer andof boolean values; are integer and boolean values; phrases is g state-manipulating operations. The syntax , the set of booleans ; , the of booleans ; phrases is give giv state-manipulating operations. operations. Theset syntax of phrases is state-manipulating The syntax of
, the set of intege the set ofset integers ; aa xed, in nite set of of symb xed, in set nite sy ,, the of integers ; call term program variable is is also common calllocations locations(the (the term program variable also , the set of booleans; comm the set set integer ofinteger booleans locations expression ,, the of booleans ;; locationsfor forstoring storingintegersthe integersthe expression stored storedin in ; ; a xed, in nite set of s a xed, in nite set of sym a xed, innite set call locations (theterm term program variable is also comm calllocations locations(the (the term program variable is also common call program variable is also a xed, nite set of integera xed, nite set of integ locations for storing integersthe integer expression locations for storing integersthe integer expression locations for storing integersthe integer expression stored in storedin in ;; ; stored a xed, nite set of boolea a xed, nite set of boo xed, nite set integ aa xed, xed, nite nite set ofof a set of integer
xed, nite set bo a set of of boole aa xed, xed, nite nite set
SMC-machine congurations
are triples
ntrol stack
a and S tack of (intermediate and nal) results P ::= ack of (intermediate nal) results
aM emory state,is ,a which byfunction denition is a partial function emory state, , which by denition partial locations. variveis em nmeros inteiros
ons.
Integer expressions
Integer expressions
if Boolean expressions
Boolean expressions if
if Commands
Commands if
if Commands
ent
al
ng
se
there.
hine can be used to execute commands for their effects on applies. integer and boolean expressions). We dene: uation of achine can be used to execute commands for their effects on integer and boolean expressions). We dene: aluation Conguraes of Iniciais e Finais
A partir de um comando e um estado inicial constri-se nsuma to be of the form where is an comm cong. inicial:
where
is an
comm
uma execuo da mquina abstracta levar-nos-, se tudo correr bem, a uma cong. nal da forma
where is a state.
where is a state.
A mquina abstracta constitui uma semntica operacional da linguagem porque descreve a execuo passo-a-passo dos seus programas.!
!
The SMC-machine can be used to execute commands for t integer and boolean expressions). W involving the evaluation of
Propriedade
Em execues (sequncias de transies) com incio numa congurao dathe forma " initial congurationsinicial to be of form where a state; conguraes mal formadas.! no ocorrem Prova: por induo no comprimento da sequncia de transies. Necessita de um lema sobre expresses colocadas no topo da stack de controlo.
terminal congurations to be of the form where is
Erros de execuo
Os erros de execuo de um programa devem naturalmente reectir-se em erros da mquina abstracta (transies bloquedas):!
! !l no topo da stack e s(l) no est denido! ! Erro de avaliao de expresses aritmticas: diviso por zero!
certo comando no topo da stack de controlo exige a presena de uma expresso inteira ou booleana no topo da stack de resultados)
Induo Matemtica
Tcnica bem conhecida: para provar que P(x) vlido para qualquer nmero natural x basta provar que:!
!
Sintaxe Abstracta
data Iop = Sum | Diff | Prod | Div | ! data Bop = Equal | LT | LTE | GT | !
!
data IntExp = IntConst Int ! | Pos Mem ! | IntOp Iop IntExp IntExp!
!
Sintaxe Abstracta
data Command = | | | | Skip ! Assignment Mem IntExp! Sequence Command Command! ITE BoolExp Command Command! While BoolExp Command!
Induo Estrutural
Para provar que uma propriedade P sobre rvores verdadeira para qualquer rvore pertencente a um conjunto de rvores etiquetadas, nitas, basta provar que:!
caso de base: P verdade para todas as folhas da rvore ! caso indutivo: para cada constructor c de nodos com n
sub-rvores, se P verdade para as sub-rvores t1 tn ento P(c(t1 tn) ) verdade
Nota !
!
A tcnica de prova por induo estrutural pode ser justicada com recurso induo matemtica. Dada uma propriedade P sobre rvores de expresso denimos:!
!
Ento P(E) verdade para todas as rvores nitas E ! sse ! P(n) verdade para todos os inteiros n
rvores de Prova
Dado um conjunto de frmulas lgicas, a denio de um sub-conjunto de frmulas (vlidas) pode ser denida por induo; em particular, podem ser denidas como as concluses das rvores que obedecem a uma determinada denio indutiva. !
!
Here is an inductively dened relation that captures this he need for control and phrase stacks). We will extend this on. Exemplo (avaliao de LC) a subset of the set of all triples , where is an d is an integer. It is inductively dened by the axioms and ! an inFrmula x notation instead of writing . ! is a valid instance of the f that
E uma expresso de LC; s um estado; ! n um inteiro!
!
n, s ! n
!
!l, s ! n
se s(l) = n!
se n = n iop n!
axiomas: para todo o axioma a de A tem-se P(a)! regras: para toda a regra h1 hn de R,!
c! se P(h1) e e P(hn) ento P(c)
Nota !
!
Esta tcnica de prova pode ser justicada com recurso induo matemtica. Dado um conjunto F de frmulas e uma propriedade P sobre elas, dena-se P:!
!
P(n) = P( f ) verdade por todas as frmulas f " F que sejam concluso de derivaes com n ou menos nodos!
!
ento! P( f ) verdade para todas as frmulas f sse! P(n) verdade para todos os inteiros n!
Princpios bsicos:!
!
simplicar as conguraes (=> mais abstractas)! eliminar transies no-semnticas! transies so estruturais:!
!
transies de um elemento composto de um programa so construdas indutivamente a partir das transies dos seus componentes
Expresses:
( )( )
if
se if s(l) = n
(
( )
)
if
if
transition relation
and
Slide 18
LC Relao de Transio ( )
Comandos: transition relation
and ( )
Slide 19
Transition semantics of
transition relation conditional transition relation conditional & while& while transition relation conditional & while transition relation conditional & while
Comandos:
)
)
( ) )
) ) )
( (
)
) ) )
( ( (
) ( ) ( )
Slide 20
Exemplos de conguraes A conguration is stuck if bloqueadas and only if it: is not terminal, but
. !!l, (For example, Note-se que
{ }"
is stuck if de .) no ocorre nenhuma forma congurao mal formada. As congs. bloqueadas correspondem a erros de execuo.
Algumas Questes
Seria possvel ter-se duas relaes distintas para expresses e comandos?! Faria sentido outra denio para a relao de transio? Ou seja, feita alguma escolha (estratgia) inteligente na denio?! Qual a diferena essencial no estilo de denio das transies em relao s da mquina abstracta da aula anterior?
Exerccios
Se se pretender acrescentar operadores booleanos para conjuno, disjuno, e negao, que regras devem ser acrescentadas semntica de transies?! E no caso de operadores com efeitos laterais, como x++ da linguagem C?! E como se procederia para lidar com outros tipos de ciclos (for, do while)?
Propriedades
Sistema Determinstico: se
!P, s" # !P, s" e !P, s" # !P, s"! ento !P, s" = !P, s"
!
Propriedades
Propriedades
Sequncias de Avaliao
(pra sem atingir terminal)! the sequence eventually reaches a stuckcong. conguration. Bloquear Divergir pra sequncia innita) sequence ent : the is(no innite.
exemplo: while true do ()
Uma sequncia pode ! ating : the sequence eventually reaches a terminal Terminar (atinge uma cong. terminal)! guration (cf. Slide 21).
ee possible types of evaluation sequence, shown on Slide 24. For on sequences can be avoided by restricting attention to sensible cong : see Exercise 3.4.4. certainly possesses divergent ev he simplest possible example is given on Slide 25. In this section we ve denition of the terminating evaluation sequences, i.e. of the relation
Relao de Avaliao
terminal. terminal
3 STRUCTURAL OPERATIONAL
luation relation, will be given as an inductively dened subse ser expresso por uma nova , written with inrelao: x notation
d rules inductively dening (5) are given in Figure 2 and on ivable, then is a terminal conguration (this is easily
integer o if c = n1 op n2
)
)
( ( ( ( (
) ( ( ) ) )
if
if
) if
integer or boolea )
() () )
) ( )
()
()
( ( ( ( ( ( ( (
) )
Figure 2: Axioms and rules for Figure 2: Axioms and rules for
evaluation evaluation
Evaluation rules for for Evaluation rules Evaluation rules for Evaluation rules for
) ) )
) )
relation, will be given as an inductively dened subset of , written with inx notation 3 STRUCTURAL OPERATIONAL
Propriedade
is uma a terminal conguration (this se is easily proved congurao terminal a frmula ! by Rule
! !
then
luation relation, will be given as an inductively dened subse nductively dening (5) are given in Figure 2 and on Slide 26. Note , written with in x notation
d rules inductively dening (5) are given in Figure 2 and on ! ivable, then isinduo a terminal conguration (this is easily Prova: por nas regras
Evaluation rules for
Exerccio
e and any state . W leof 3.2.1. transition Consider and evaluation semantics
. We argue by contradiction. Suppose (6) has a proof. Then by t le (see Slide 10), amongst all the proof trees with (6) as their conclu minimal number of nodescall it . Because of the structure of , y be ue by contradiction. Suppose (6) has a proof. Then by th
Provar (por contradio) que no existem estados and any state . We Consider inicial s e terminal s tais que
ide 10), amongst all the proof trees with (6) as their conclu
Propriedade
No provaremos, mas!
!
luation relation , will be given as an inductively de ned subse Existir um algoritmo que, dada uma congurao written with x notation inicial, diz se, esta ou noin avaliada numa congurao
nal?
d rules inductively dening (5) are given in Figure 2 and on ivable, then is a terminal conguration (this is easily
Propriedades
Propriedades
. So there cannot ex
Equivalen Equivalence
a proof of (6). But is a proper subtree of ntradicting the minimality property of . So there cannot exist any for Theorem. For For all congurations Theorem. congurations holds. Equivalence of all
Equivalncia das Semnticas de Transies e de Avaliao congurations transitioncongurations and evaluation semantics
Equivalence of
transition and eval transition and evalua and so has strictly fewer
gurations
com
(b) (c)
e part proof:
congurations
Prova
(i)! (a)
(b)
!
por induo nas regras de denio de $% (ii) (a) para & prova-se resultado mais forte:!
(b) (c) induo nas regras deSlide por def. de 27 !! e (ii) resulta por induo no compr. da sequncia de trans.!
quivalence of
Propriedades
Sistema Determinstico: se
!P, s" $ !V, s" e !P, s" $ !V, s"! ento !V, s" = !V, s" Prova por induo nas regras desnecessria dada a equivalncia com semntica de transies!
Relao de Igualdade
P=P P = P P= P P=P P=P ! P=P P = P C[P]= C[P]
.
P pode ser substitudo por P em qualquer contexto, expresso ou assero. Esta regra no ser imposta, tem que ser provada em cada linguagem!
Denition of semantic equivalence of equivalentes phrases Duas expresses ou comandos dizem-se Two phrases of the same type are semantically equivalent Two phrases of the same type are semantically equivalent
if and only if for all states and all terminal gurations se para todos os estados iniciais s econ cong. terminais!
this case. There similar characterisations of t; we write in in this case. There areare similar characterisations of sem we write integer and boolean expressions. ence for integer and boolean expressions. ce for
Semantic inequivalence of commands Semantic inequivalence of commands Para provar que ! To show , it suf ces to nd states basta encontrar estados inicial e nal tais que it suf ces to nd states ,either it ,suf ces to nd states
or and such that such that
such t
e and and
and and
and
(ou inversamente)! !
(identicamente para E.g. (Exercise 4.3.2) when E.g. (Exercise 4.3.2) when and and
expresses) ,
, , then , then
, , then
Teorema
Esta noo de equivalncia semntica estabelece uma relao de equivalncia congruente Prova: equivalncia trivial uma vez que a def. parte de uma equivalncia lgica!
!
Congruncia: expresses
s:expressions if Provar then or integer expressions : if and then forand all and que implica er : if for then for for all alland nteger expressions : if all then
implica nsboolean : if expressions then for all andthen for or expressions : if all and boolean : if and an expressions: if then for then all allfor and
Congruence properties of semantic equivalence Figure 4: Congruence properties of semantic equivalen Figure 4: Congruence properties of semantic eq
Congruncia: comandos
and
4 SEMANTIC EQUIVA
4 SEMAN
Provar que implica or commands : if then for all then for all mands : if and
(ltimo caso recorrendo ger expressions : if mais difcil, thenprova-se for all and
or integer expressions : if por induo then for and semntica de transies, no all comprimento de uma cadeia de transies)
ntic equivalence of
phrases
4 SEMANTIC EQUIVA
e 4.1.1.
Write
Examples of
if if if if
.
.
-equivalent expression
Expresses
if
Primeiro caso seria til na presena de variveis com ! mbito (scope) local
)
)
Expresses
) )
) )
) ))
)) ) )
Comandos
)
)
)
))
s) rules ( ) and (
) on Slide 46.
) ) ) ) )
Comandos
) ) on Slide 46.
us rules ( ) and (
Questo
Propriedades
e and and ento , then , then
Some type-related
(ii) Cbn-evaluation at no
valuation atnon-command non-command types side-effect free . .If luation at typesis is side-effect free
For