Sie sind auf Seite 1von 82

Semntica da Programao

Jorge Sousa Pinto!

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!

- Winskel, G. The Formal Semantics of Programming


Languages. MIT Press, 1993!

- Hennessy, M. The Semantics of Programming


Languages. Wiley, 1990 [ disponvel online]

Bibliograa Notas
- Pitts A. M. Lecture Notes on Semantics of
Programming Languages. Univ Cambridge, 1997-2002!

- Mycroft A. Foundations of Functional Programming.


Univ. Cambridge, 2007!

- Winskel F. Lecture Notes on Denotational Semantics.


Univ. Cambridge, 1997-2002

Def. de uma Linguagem de Programao

Sintaxe: descrio dos smbolos e das expresses

que constituem a linguagem, bem como das demais categorias sintcticas (comandos, programas)

Semntica: descrio do signicado das vrias Ferramentas: interpretadores, compiladores,


debuggers, prolers

construes da linguagem, que permite prever o seu comportamento em tempo de execuo.!

Informal Semantics

Semntica Informal

deQual nition o of signicado da seguinte construo?

Kernighan and D. M. Ritchie, The C

uage (Prentice-Hall, 1978), p 202: !

Segundo Kernighan & Ritchie, The C Programming Language, !

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

Os prprios mtodos semnticos podem


!

sugerir novas caractersticas das linguagens (por exemplo o !-calculus anterior programao funcional)

Em Vericao de Programas, a actividade que


pretende certicar a correco do comportamento dos programas face s suas especicaes (cfr. UCE de 2o. ciclo MFES)

Estilos de Semnticas Formal

Operacional: descreve os estados de execuo de


um programa"

Denotacional: descreve o signicado de um


programas atravs de uma lgica

programa num domnio matemtico abstracto"

Axiomtica: descreve o comportamento de

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

Uma Linguagem Imperativa


[Pitts, Lecture Notes]

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 .

Se a congurao c transita para e often called congurations (orc escrevemos:


are often called congurations (or .

ation is written inx, i.e.

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

Linguagem de Comandos (LC) Sintaxe

Commands

ressions

expressions
Integer expressions

pressions

expressions

Comandos, Expr. Inteiras e Expr. Booleanas


Slide 5
Slide 5

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

a xed, nite set of boolean-valued binary operations.

a xed, nite set of boolean-valued binary operatio

SMC-machine congurations
are triples

Uma Mquina Abstracta SMC-machine con gurations


consisting of

SMC-machine consisting of congurations

ntrol stack consisting of aC ontrol stack


!

Stack de controlo ou de comandos: Stack de resultados:


C|E|B

ntrol stack

a and S tack of (intermediate and nal) results P ::= ack of (intermediate nal) results

ck of (intermediate and 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

ping locations to integers, dened only at nitely many

Um Estado: uma funo parcial nita que mapeia


mapping locations to integers, dened only at nitely many Slide 6

ons. state, , which by denition is a partial function mory

ing locations to integers, dened only at nitely many

ons.

Integer expressions
Integer expressions

Transies da Mq. Abstr.


if
if

if Boolean expressions
Boolean expressions if

if Commands
Commands if

if Commands

ent

al

ng

se

de condition means: the partial function

is dened at and has value

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:

tions to be of the form

where

is an

comm

uma execuo da mquina abstracta levar-nos-, se tudo correr bem, a uma cong. nal da forma

tions to be of the form

where is a state.
where is a state.

rations to be of the form

A mquina abstracta constitui uma semntica operacional da linguagem porque descreve a execuo passo-a-passo dos seus programas.!
!

Ser que todas as transies descrevem computaes?!


!

Muitas conguraes sintacticamente correctas so invlidas / mal formadas.!

Congurao bem formada



Se no topo da stack de controlo se encontra um operador iop ou bop, ento no topo da stack de resultados encontram-se duas constantes inteiras! Se :=, ento uma constante inteira e uma varivel! Se if, ento uma constante booleana seguida de dois comandos! Se while, ento uma constante booleana seguida de um comando

which transition applies.

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!

Note-se que no correspondem a conguraes mal formadas!

Limitaes da Semntica por Mquina Abstracta

Muitas transies fazem apenas anlise sintctica e


no tm portanto uma funo descritiva da linguagem! forma directa

Pouco intuitiva: as construes no so descritas de

Difcil de utilizar como instrumento para raciocinar


sobre propriedades da linguagem LC!

Existem muitas conguraes invlidas (quando um

certo comando no topo da stack de controlo exige a presena de uma expresso inteira ou booleana no topo da stack de resultados)

Tcnicas de Prova por Induo

Induo Matemtica
Tcnica bem conhecida: para provar que P(x) vlido para qualquer nmero natural x basta provar que:!
!

P(0) vlido! se P(x) vlido (x arbitrrio) ento P(x+1) vlido!


! sendo P uma propriedade qualquer sobre os nmeros naturais

Sintaxe Abstracta
data Iop = Sum | Diff | Prod | Div | ! data Bop = Equal | LT | LTE | GT | !
!

data IntExp = IntConst Int ! | Pos Mem ! | IntOp Iop IntExp IntExp!
!

data BoolExp = TT | FF! | BoolOp Bop IntExp IntExp

Sintaxe Abstracta
data Command = | | | | Skip ! Assignment Mem IntExp! Sequence Command Command! ITE BoolExp Command Command! While BoolExp Command!

Denio de tipos indutivos para Expresses e Comandos!


!

Em termos abstractos que forma tm estes tipos?

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

Induo Estrutural - Expresses Inteiras LC


caso de base: ! P(n) verdade para todos os nmeros inteiros n! P(!l) verdade para todas as variveis l! caso indutivo: !
sejam E, E expresses inteiras; se P(E) e P(E), ento ! P(E iop E), com iop um operador binrio sobre inteiros

Nota !
!

A tcnica de prova por induo estrutural pode ser justicada com recurso induo matemtica. Dada uma propriedade P sobre rvores de expresso denimos:!
!

P(n) = P(E) verdade para todas as rvores E com n ou !! menos nodos!


!

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. !
!

Estas rvores chamam-se provas ou derivaes. !


!

(cfr. bem conhecida Deduo Natural)

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!
!

signicado: a avaliao da expresso E no estado s tem como resultado o inteiro n!


!

Esta relao pode ser denida indutivamente

Exemplo (avaliao de LC)


Casos de base (axiomas): !
!

n, s ! n
!

!l, s ! n

se s(l) = n!

Caso Indutivo (regra):!


!

E,s ! n E,s ! n E iop E,s ! n

se n = n iop n!

Induo sobre Regras


Para provar que uma propriedade P sobre frmulas lgicas verdade para todas as frmulas resultantes de conjuntos de axiomas A e de regras R, basta provar que:!

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!

Semntica Operacional Estrutural (Plotkin, 1981)

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

transition relation expressions transition relation expressions LC Relao de Transio

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 & while

transition relation conditional transition relation conditional & while& while transition relation conditional & while transition relation conditional & while

LC transition Relao de Transio relation conditional & while


( )

Comandos:
)

)
( ) )

) ) )

( (
)

) ) )

( ( (

) ( ) ( )

Slide 20

Conguraes Terminais Terminal and stuck congurations


The terminal con gurations are by denition Denem-se como sendo:

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"
!

Prova por induo nas regras (exerccio)

Propriedades

Subject Reduction: seja


!P, s" # !P, s"! ento, ! se P um comando, P um comando! se P uma expr. inteira, P uma expr. int.! se P uma expr. booleana,! P uma expr. booleana

Propriedades

Expresses livres de efeitos laterais: seja


!P, s" # !P, s"! com P uma expresso, ento tem-se s = s

Semntica de Avaliao (Kahn / Milner, Toft, Harper)

Types of evaluation sequence


!

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

Regras de Avaliao Expresses


)) )) )
) ) (( if if ) )

integer o if c = n1 op n2

where is the where i (fo of of integer or boo

)
)

( ( ( ( (

) ( ( ) ) )

if
if

) if

( ) Regras de Avaliao Comandos ( )


( ( ) (

integer or boolea )

whe where is of va whereof is the integ (for of integer or

() () )

) ( )

()

()

( ( ( ( ( ( ( (

Regras de Avaliao Comandos


) ) ) ) ) ) ) and ( ) and ( ) on Slide 26. ) on Slide 26.

) )

plus rules ( plus rules (

Figure 2: Axioms and rules for Figure 2: Axioms and rules for

evaluation evaluation

Regras de Avaliao Comandos


(3 premissas)

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

for inferida pelas regras apresentadas!

quivalence of transition and evaluation semantics Considere-se o seguinte programa divergente:


such that

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!
!

3 LC STRUCTURAL OPERATIONAL possvel codicar em qualquer funo recursiva parcial.!


!

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

Expresses livres de efeitos laterais: seja


!P, s" $ !V, s"! com P uma expresso, ento tem-se s = s

Propriedades

Subject Reduction: seja


!P, s" $ !V, s"! ento, ! se P um comando, V um comando! se P uma expr. inteira ,V uma expr. int.! se P uma expr. booleana,! V uma expr. booleana

itcontradicting the minimality property of holds.

. 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

Theorem. For all congurations Para todas as conguraes congurations

and all terminal

transition and evaluation semantics

orem. For all congurations

gurations

Three Three part partproof: proof:

and all terminal

Three part proof: (a) (b)

com

(a) terminal (a) (b) (c)

(b) (c)

e part proof:

transition and evaluation semantics Theorem. For all congurations


Three part proof:

and all terminal

congurations

Prova

(i)! (a)
(b)
!

(c) Three part proof: !


! !

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

transition and evaluation semantics

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!

Equivalncia Semntica e Tipos

Relao de Igualdade
P=P P = P P= P P=P P=P ! P=P P = P C[P]= C[P]
.

Relao de Equivalncia Congruente:

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

Equivalncia Semntica phrases

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!

V, sif $ for se all tem if and#only states

and all terminal congurations

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

Inequivalncia deinequivalence Comandos Semantic of commands


show ToTo show
either either oror

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

E.g. (Exercise 4.3.2) when 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 implica analisar casos estruturalmente! como se segue

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

Exemplos de Comandos Examples of Equivalentes semantically equivalentof commands Examples


semantically equivalent commands

4 SEMANTIC EQUIVA

e 4.1.1.

Write

Examples of

Exemplos de Comandos semantically equivalent commands Equivalentes


semantically equivalent Examples of commands

if if if if

.
.

Exemplos de Comandos Equivalentes


Ser uma sequncia de duas instrues de atribuio comutativa de acordo com esta noo de equivalncia?

-equivalent expression

Um Sistema de Tipos Typing relation


Asseres de the tipagem: takes form
where: integers booleans location is a type

" ::= int | bool | loc | cmd

! uma funo parcial de variveis para tipos! commands M um termo de LC


functions.

is a type environment , i.e. a nite partial function m variables to types.

Expresses
if

Primeiro caso seria til na presena de variveis com ! mbito (scope) local

)
)

Expresses

) )

) )

) ))

)) ) )

Comandos
)

)
)

))

s) rules ( ) and (

) on Slide 46.

) ) ) ) )

Comandos

(por enquanto " s pode ser cmd)

) ) on Slide 46.

us rules ( ) and (

Questo

Para que servem os tipos?

Propriedades
e and and ento , then , then

Subject Reduction type-related properties ofevaluation evaluation e type-related properties of inin

Some type-related

(i) Subject reduction. If .

Se ct reduction If reduction . .If

(ii) Cbn-evaluation at no

valuation atnon-command non-command types side-effect free . .If luation at typesis is side-effect free

, que and condies ser, then . Em garantidamente s = s ? , and , then .

For

, property (i) holds

operty (i) holds, but property (ii) fails.

erty (i) holds, but property (ii) fails.

Das könnte Ihnen auch gefallen