You are on page 1of 78

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva1

UTN - FRM: Fundamentos de sintaxis y semntica

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva2

Introduccin

Lenguajes de programacin

Programas
Lenguajes de alto nivel y de mquina
Traductores
Especificaciones gramaticales y semnticas

Lenguajes formales
Alfabeto
Palabras

Sintaxis

Semntica

Reglas de formacin de palabras


Significado de las palabras

UTN - FRM: Fundamentos de sintaxis y semntica

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva3

Reconocimiento del cdigo fuente de


un programa
alfabeto

Texto del programa


(caracteres)

Lxico
tokens
(palabras)

Sintctico

gramtica

Anlisis

rboles
(frases)

Lenguaje de mquina

Semntico

UTN - FRM: Fundamentos de sintaxis y semntica

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva4

Conceptos sobre lenguajes

Smbolos

Cadenas o palabras

Alfabeto: = {a, b, c, ...}


n con n >= 0
0 = {}
(vaco , , , )
* = 0 1 2 ...
+ = 1 2 ... = * - {}

Universo de un alfabeto W()

Lenguaje sobre un alfabeto

Todas las palabras formadas con smbolos de


L() W()

UTN - FRM: Fundamentos de sintaxis y semntica

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva5

Conceptos sobre lenguajes

Operaciones con palabras


Concatenacin:X.Y
Potencia:Xi
Reflexin:X,X1

Operaciones con lenguajes


Unin:L1 L2
Resta:L1 L2
Potencia:Li
Cierre:L* =L+ U{}

Interseccin:L1 L2
Concatenacin:L1 L2
Clausura:L+ =Ui=1 Li
Reflexin:L1

UTN - FRM: Fundamentos de sintaxis y semntica

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva6

Conceptos sobre lenguajes

Derivacin

Regla de produccin: x y : x, y *
Derivacin directa: v w
Derivacin: v v1 v2 w
Derivacin por izquierda y por derecha
Ejemplo:
01 11
00 10
Derivaciones para la palabra?
00011
Regla compresora: x y si |y| < |x|
UTN - FRM: Fundamentos de sintaxis y semntica

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva7

Gramticas formales

Definicin
G = {t, n, S, P}
t: conjunto de smbolos terminales
n: conjunto de no-terminales (=t n y t n=)
S: axioma : S n
P: reglas de produccin

Lenguaje generado
L(G) es el conjunto de todas las palabras o cadenas generadas
por la gramtica.

Equivalencia
L(G1) = L(G2)

UTN - FRM: Fundamentos de sintaxis y semntica

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva8

Gramticas formales

Sea P = { S -> a S b, S -> a S b b, S -> b }


t = ? n = ?
S=?
Qu genera?

Sea G = ({A}, {a, b, c}, P, S)


conjunto P que genera L1 = {wcw / w E {a, b}*} ?

Sea = {a, b} y la palabra aaba


dos reglas para obtener aaab por derecha ?
Sea t = {a, b}
gramtica que genera { ar b / r > 0 } ?

Sea t={a,b,c}
gramtica que genera { ar b cr/r0 } ?

UTN - FRM: Fundamentos de sintaxis y semntica

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva9

Jerarqua de Chomsky
Tipo 0
(sin restricciones)
uv
u = xA y
u (n t)+
v, x, y (n t)*
A n

Tipo 1
(sensible al contexto)
xA y x v y
x, y (n t)*
v (n t)+
A n
S (regla compresora)

1
2

Tipo 2
(independiente del contexto)
Av
A n
v (n t)*

Notacin BNF, Pascal

Tipo 3
(regular a dcha. o izq.)
A aB
Aa
A
A, B n
a t
Expresiones regulares

UTN - FRM: Fundamentos de sintaxis y semntica

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva10

G3 (regulares)
Regular x izquierda

Regular x derecha
S 1A
A 1A | 0B | 0
B 0B | 0

S C0
C C0 | D1 | 1
D D1 | 1

Ambas generan
11000

UTN - FRM: Fundamentos de sintaxis y semntica

10

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva11

G2 (independientes de contexto)
G1 (no estricta)

G2 (estricta)

S AB
A 0A1 |
B 2B |

S AB | A | B |
A 0A1 | 01
B 2B | 2

Ambas generan
0n1n2m con n, m 0
G1 no es estricta ya que incluye reglas nulas
asociadas a smbolos que no son el axioma

UTN - FRM: Fundamentos de sintaxis y semntica

11

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva12

rbol de derivacin

SeaG={t,n,S,P}
t:{0,1,[,],+,*}
n:{E}
S:E
P:{E[EE+],E[EE*],E0,E1}

Paralacadena:[0[01*]+]

UTN - FRM: Fundamentos de sintaxis y semntica

12

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva13

rbol de derivacin: ambigedad

Sea:S SaS|SbS|c
Qupasaparacbcac ?

Sea:E E+E|E*E|E^E|id|(E)
Necesidaddereglasdeprecedencia
* (izq adcha) + (izq adcha) ^ (dcha aizq)
E E*E|E
E id|(E)

E E+E|E
E E^E|E

EjemploenlenguajeFortran:
x+algo(3,4)
algoesunarregloounafuncin?

UTN - FRM: Fundamentos de sintaxis y semntica

13

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva14

rbol de derivacin: ambigedad


<assign> <id> := <expr>
<id> A | B | C
<expr> <expr> + <expr>
| <expr> * <expr>
| ( <expr> )
| <id>
Para ? B := B + A * C (ambigua)

Para ? B := B + ( A * C )

Para ? C := (B + C) * (A := B)
UTN - FRM: Fundamentos de sintaxis y semntica

14

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva15

Notacin BNF y EBNF

Es un meta-lenguaje
Smbolos no terminales (abstractiones BNF)
Smbolos terminales (lexemas)

BNF (John Bakus, Peter Naur Normal Form - 1959)


Notacin
<smbolo>
a
+
::=

Ejemplo

()

<dgito>::=0|1||9
<nmero>::=<dgito><nmero>
<nmero>::=<dgito>

EBNF (Extended BNF)


Notacin
{ }* o {}

Ejemplo

{ }+

[]

<dgito>::=0|1||9
<nmero>::=<dgito>{<dgito>}*

UTN - FRM: Fundamentos de sintaxis y semntica

15

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva16

Diagramas sintcticos

UTN - FRM: Fundamentos de sintaxis y semntica

16

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva17

BNF EBNF Diagramas

BNF:
<expr> ::= <expr> + <term> |
<expr> - <term> | <term>

EBNF:
<expr> ::= <term> { (+ | -) <term> }

Diagrama sintctico
expr

term
term

+
-

UTN - FRM: Fundamentos de sintaxis y semntica

17

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva18

Notaciones para expresiones


Infija
a+d*g-h

Postfija
adg*+h-

C
a=a+ b

PostScript
/a a b add def

Prefija
-+a*dgh
Lisp
(setf a (+ a b))

Infija: operadores entre los operandos


Postfija: operadores posteriores a los
operandos
Prefija: operadores anteriores a los
operandos

UTN - FRM: Fundamentos de sintaxis y semntica

18

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva19

UTN - FRM: Fundamentos de sintaxis y semntica

19

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva20

Autmatas

Permiten simular procesos para tratar informacin

la informacin se codifica en cadenas de smbolos


son dispositivos que manipulan cadenas de smbolos
procesan cadenas de entrada y producen cadenas de salida
reciben los smbolos de entrada secuencialmente

El smbolo de salida, en un instante dado depende de


el ltimo smbolo de entrada
la secuencia o cadena, que ha recibido hasta ese instante
el estado en que se encuentra

Estado de un autmata
en un instante de tiempo dado, slo puede estar en un estado
estado inicial y estados finales

Formas de descripcin: grfica, matricial, funcional

Se usan como reconocedores de lenguajes


Existen distintos tipos de autmatas

UTN - FRM: Fundamentos de sintaxis y semntica

20

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva21

Mquina de Mealy

M = (e, s, Q, f, g)
e: alfabeto de entrada
s: alfabeto de salida
Q: conjunto de estados
f: Q x e Q
g: Q x e s

Transiciones x/y donde


x es el smbolo de entrada
y es el smbolo de salida

La salida depende del estado actual y de la entrada

UTN - FRM: Fundamentos de sintaxis y semntica

21

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva22

Mquina de Moore

M = (e, s, Q, f, g)
e: alfabeto de entrada
s: alfabeto de salida
Q: conjunto de estados
f: Q x e Q
g: Q s

La salida depende slo del estado actual


Para el mismo proceso, suelen tener ms estados
que las mquinas de Mealy

UTN - FRM: Fundamentos de sintaxis y semntica

22

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva23

Autmata finito determinista


AFD = (, q0, Q, F, f)
: alfabeto de entrada
Q: estados
f: Q x Q

q0: estado inicial Q


F: estados finales Q
Representaciones
Notacin
Notacin
matricialfuncional
f(1,
a
b a) $ 2 2
f(1, b) 3
1
2
3 a)
- 2 f(2,
f(3,
2
2
- b) - 2 f(3,
3
2 $) 4 4 f(4, $) 4
4
4 3 3
f(4,2)

Habitualmente slo se representan las transiciones que conducen al


reconocimiento de alguna cadena, considerndose implcito un "estado
de captacin global", donde se supone que llegan los arcos omitidos.
UTN - FRM: Fundamentos de sintaxis y semntica

23

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva24

Autmata finito no-determinista


AFND = (, q0, Q, F, f)
: alfabeto de entrada
q0: estado inicial Q
Q: estados
F: estados finales Q
f: Q x ( {}) P(Q)
1 0 1 0 0

1
q1

1
q0

0,1
,1

q2

q3

UTN - FRM: Fundamentos de sintaxis y semntica

24

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva25

Gramticas G3 y autmatas

Gramtica regular
T ={0,1}
N ={A,B,S}
P={S>0A,A>0S,A>1B,B>1,B>0 }

Autmata

Expresin regular
0.(0.0)*.1.(1|0)

UTN - FRM: Fundamentos de sintaxis y semntica

25

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva26

Expresiones regulares

Introducidas en 1956 por Kleene


Describen AEF

Operadores
Unin

Concatenacin

Cierre (Kleene)

Cierre (positivo) +

Sea a.(b|c*).d cul es el AEF y la gramtica?

UTN - FRM: Fundamentos de sintaxis y semntica

26

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva27

Propiedades de las ER
SeaL={a,b,c}*
Sonequivalentes:c*.c|c*= c*?
4)
3)

2)
1)

UTN - FRM: Fundamentos de sintaxis y semntica

27

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva28

Expresiones regulares y AEF

Se pueden transformar aplicando reglas de


la forma:
a

qi

a|b

qf

a.b

qi

qk

qf

a
qi

a*

qk

qf

Existen algoritmos formales


Algoritmo de McNaughton-Yamada-Thompson

UTN - FRM: Fundamentos de sintaxis y semntica

28

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva29

Algoritmo de transformacin

Por ejemplo sea (1|0)*1seobtieneunAFND


luego se lo
convierte a
un AFD

UTN - FRM: Fundamentos de sintaxis y semntica

29

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva30

Equivalencia de autmatas
AFND AFD
Un AFD es un caso particular de AFND
Sean N=(, q0, Q, F, f) y D=(, {q0}, Q, F, f)

N = D / L(D)=L(N)
Si se cumple:
Q = 2|Q| (conjunto potencia P(Q) )
qi = [qi , , qf ] => {qi , , qf} Q

q0 = {q0}
F = { q Q / q F } (al menos uno sea final)
f(q, a) = { qq f(q, a)} / q Q ^ a
UTN - FRM: Fundamentos de sintaxis y semntica

30

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva31

Equivalencia de autmatas
Se basa en la construccin de subconjuntos
La idea general es que cada estado del AFD
le corresponde un conjunto de estados del
AFND
Algoritmo:

Para cada estado del AFND y cada smbolo de


entrada, analizar cules estados son alcanzables
Agrupar esos estados en estados compuestos
Hacer lo mismo con los estados compuestos
Finalmente, eliminar los estados que no son
alcanzables (menos inicial y final)
UTN - FRM: Fundamentos de sintaxis y semntica

31

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva32

Equivalencia de autmatas

AFND

AFD: estados alcanzables desde {q0}

UTN - FRM: Fundamentos de sintaxis y semntica

32

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva33

Minimizacin de autmatas
Sean AFD=(, q0, Q, F, f) = AFDM=(, q0, Q, F, f) / L(AFD)=L(AFDM)
a) Eliminar los estados no alcanzables desde el estado inicial
b) Eliminar los estados desde los que no se alcanza un estado final
Algoritmo:
1. particin inicial P en dos grupos G(F), G(Q F)
2. G de P (|G| > 1) obtener nueva Pn de modo que:
1. qi, qj Gi <=> / f(qi, ), f(qj, ) Gi
2. sustituir G en Pn por el nuevo conjunto de subgrupos
3. si Pn= P (indistinguibles) entonces Pfinal := P e ir a (5)
4. sino P := Pn e ir a (2)
5. elegir en cada grupo de Pfinal, un qi como representante del
grupo
6. se eliminan estados pasivos (que no son finales y hay transiciones
hacia ellos, pero no desde ellos hacia otros estados)

UTN - FRM: Fundamentos de sintaxis y semntica

33

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva34

Minimizacin de autmatas
Sea el AFD que reconoce L = (a|b)*abb
Minimizacin:
1.

P := G1{Q5} + G2{Q1,Q2,Q3,Q4}

2.

Pn := {Q5} y (Q1, Q2, Q3) x b G2 y Q4 x b G1

3.

Pn := G1{Q5} + G2{Q1, Q2, Q3} + G3{Q4}

4.

si Pn P entonces P := Pn y repite

5.

Pn := {Q5} + {Q4} y {Q1, Q3} x b G2 y Q2 x b G3

6.

Pn := G1{Q5} + G2{Q4} + G3{Q1, Q3} + G4{Q2}

7.

como Pn P entonces P := Pn y repite

1.

luego Pn = P entonces

1.

Q1 representa a G3

pero se obtiene la misma P


Pfinal := P

UTN - FRM: Fundamentos de sintaxis y semntica

34

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva35

Conceptos
Lenguajes regulares
Gramticas regulares (G3)

Lema del bombeo


Si Lr =>
xyz L / y ,
xynz L para n > 0
Exp. Reg.Y AEF

Expresiones regulares
Autmatas de estado finito

UTN - FRM: Fundamentos de sintaxis y


semntica

35

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva36

Casos

AEFND AEFD

Minimizar

UTN - FRM: Fundamentos de sintaxis y semntica

36

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva37

Autmatas de pila
Autmata de Pila
AP = ( , , Q, a0, q0, F, f )
: alfabeto de pila
Q: conjunto de estados
a0: smbolo inicial pila

: alfabeto de entrada
q0: estado inicial
F: estados finales
f: Q ({}) Q

Para cada gramtica G independiente del contexto, existe un autmata de


pila M tal que L(G)=L(M)
Los smbolos en la pila se ordenan en sentido cima base (convencin)
cinta

pila

Control

UTN - FRM: Fundamentos de sintaxis y semntica

37

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva38

Gramticas G2 y AP
Gramtica libre de contexto Autmata de Pila
T = {a, b}

N = {S}

P = { S -> aSb| }
L1 =

{anbn

/ n >= 0}

: {a, b}

q0: e0

: {#, $}

F: {e3}

Q: {e0,e1,e2,e3}

a0:

a, a

q0

b, a
b, a

q1

q2

, $ $

q3

Descripcin instantnea: terna (q, h / w) donde:


q = estado actual
h = smbolo ledo de la cima de la pila
w = smbolo escrito en la pila
UTN - FRM: Fundamentos de sintaxis y semntica

38

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva39

Autmatas de pila

Descripcin funcional
f: e0 x
e1 x
e1 x
e2 x
e2 x

x e1 x $
x e2 x
0 x e1 x #
x $ e3 x
1 x # e2 x

Descripcin tabular
Estado

Entrada

Pila

Transicin

e0

e1,$

e1

e2,

e1

e1,#

e2

e3,

e2

e2,

UTN - FRM: Fundamentos de sintaxis y semntica

39

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva40

Autmatas de pila

Reconocimiento por vaciado de pila


Lvp(M)= {w * / (q0, w, a0) (p, ,),p Q}

Reconocimiento por estado final


Lef(M)={w */ (q0, w, a0) (p, , h),p F, h *}

Lvp puede ser diferente de Lef

UTN - FRM: Fundamentos de sintaxis y semntica

40

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva41

Autmatas de pila

Es determinista si cumple
(q Q
(q Q

A ) si |f(q, ,A)|>0
a , f(q, a, A)=
A a {} ), |f(q, a, A)|<2

Construccin de un AP (, , Q, a0, q0, f, F)


Dados: ={a, b, c}, ={#, $, }, a0 = #, q0=X, Q={X,Y, Z}, F= {Z}

f ? para reconocer: L = { an b cn+1 / n > 0 }

AP <=> G2

UTN - FRM: Fundamentos de sintaxis y semntica

41

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva42

Autmatas de pila y gramticas


Representar G2 con AP
AP ( , , Q, a0, q0, F, f ) entonces construir
APND=(, N, {q}, S, q, fi, f)
sea Aw P entonces (q, w) f(q, , A)
sea a entonces (q, ) f(q, a, a)
El reconocimiento es por vaciado de pila
Sea P = { S0S1, Sc } entonces
f(q, , A)= {(q, 0S1), (q, c)}
f(q, 0, 0)= f(q,1,1)= f(q, c, c)= {(q, )}

UTN - FRM: Fundamentos de sintaxis y semntica

42

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva43

Algoritmo para convertir G2 en AP


Dada una gramtica G independiente del contexto, se construye un
autmata de pila M de la siguiente forma:
1.

Designar el alfabeto de M como los smbolos terminales de G; y los


smbolos de pila de M como los smbolos terminales y no terminales
de G, junto con # (si # no es un smbolo terminal o no terminal a G)

2.

Designar los estados de M como i, p, q y fi; donde i es el estado inicial y


fi es el nico estado de aceptacin

3.

Agregar la transicin (i, , ; p, #)

4.

Agregar una transicin (p, , ; q, S) donde S es el smbolo inicial de G

5.

Agregar una transicin de la forma (q, ,N; q,w) para cada regla de
reescritura Nw en G, donde w puede ser una cadena de cero o mas
smbolos, incluyendo terminales y no terminales

6.

Agregar una transicin de la forma (q, x, x; q, ) para cada terminal x de


G (para cada smbolo del alfabeto de M)

7.

Agregar la transicin (q, , #; fi, )

UTN - FRM: Fundamentos de sintaxis y semntica

43

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva44

Algoritmo para convertir G2 en AP


SzMNz
MaMa
Mz
NbNb
Nz

G2:

AP:

= {a, b, z}
= {a, b, z, S, M, N, #}
Q = {i, p, q, fi}
a0 = #
q0 = i
F = fi

Comportamiento
UTN - FRM: Fundamentos de sintaxis y semntica

44

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva45

Autmata Linealmente Acotado


ALA= (Q, , , , e0, b, F)
donde b = blanco
longitudcinta = longitudcadena
Q: conjunto finito estados
: alfabeto de entrada;
: {b} otros smbolos, b
: Q x Q x x {D, I, N}
e0: estado inicial Q
F: estados finales Q
estados

(input)
(output)

cinta

Control

UTN - FRM: Fundamentos de sintaxis y semntica

45

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva46

Mquinas de Turing
AP = (, , b, Q, q0, F, f)
: alfabeto de entrada c
: alfabeto de la cinta
b: blanco c, e
Q: conjunto de estados
q0: estado inicial Q
F: estados finales Q
f: Q x c Q x c x {I, D, P}
cinta

estados

Control

UTN - FRM: Fundamentos de sintaxis y semntica

46

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva47

Mquinas de Turing

Los movimientos se repiten hasta que:


llega al estado final (se detiene aceptando la entrada)
intenta acceder a la celda a la izquierda de la celda
inicial (se detiene rechazando la entrada)
entra en una situacin para la que no hay definido
movimiento (se detiene rechazando la entrada)
ante determinada entrada, la mquina siga realizando
movimientos indefinidamente sin aceptar ni rechazar
dicha entrada

Palabra y lenguaje aceptado


x L(M) q0x 1q2 : 1,2 , q F
L(M) = { x * | q0x 1q2 : 1,2 , q F }

UTN - FRM: Fundamentos de sintaxis y semntica

47

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva48

Mquinas de Turing
Mquina que acepta el lenguaje de palabras sobre {0, 1}
que comienzan y terminan con el mismo smbolo

UTN - FRM: Fundamentos de sintaxis y semntica

48

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva49

Mquinas de Turing
Concatenador

1 $, R

1 1, L

1 1, R

q0 , L q1 $ 1, R

Duplicador

, R
q3

q2

1, L

UTN - FRM: Fundamentos de sintaxis y semntica

49

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva50

Gramticas y autmatas
3: lenguajes regulares
autmatas finitos
2: lenguajes
independientes del
contexto
autmatas de pila
1: lenguajes sensibles al
contexto
autmatas linealmente
acotados
0: lenguajes irrestrictos
mquinas de Turing

UTN - FRM: Fundamentos de sintaxis y semntica

50

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva51

UTN - FRM: Fundamentos de sintaxis y semntica

51

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva52

Anlisis lxico

Scanner
agrupar caracteres de entrada en tokens
detectar algunos significados y errores
a veces debe realizar una doble funcin: identificar el token y
evaluar el token

introducir informacin adicional


algunos tokens requieren algo ms que su propia identificacin
constantes: su valor, identificadores: el string, etc.

eliminar separadores innecesarios


sustituir macros

UTN - FRM: Fundamentos de sintaxis y semntica

52

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva53

Anlisis lxico

UTN - FRM: Fundamentos de sintaxis y semntica

53

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva54

Anlisis lxico
lexema

token

patrn

secuencia de
caracteres,
que se
asocia a un
token

nombre de
cada
componente
lxico

conjunto de
lexemas

Lexemas
index
=
2
*
count
+
17
;

Enunciado
index = 2 * count + 17

Tokens
identifier
equal_sign
int_literal
mult_op
identifier
plus_op
int_literal
semicolon

UTN - FRM: Fundamentos de sintaxis y semntica

54

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva55

Anlisis sintctico

Parser
agrupar los tokens suministrados por el scanner
para reconocer frases
determinar si son sintcticamente correctas
establecer la estructura subyacente

recibir tokens y agruparlos de acuerdo a


producciones especificadas por la G3
detectar errores sintcticos
generar rboles sintcticos

UTN - FRM: Fundamentos de sintaxis y semntica

55

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva56

Anlisis sintctico

Proceso de anlisis

UTN - FRM: Fundamentos de sintaxis y semntica

56

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva57

Anlisis sintctico

rboles de sintaxis
Concreta: sirve para el anlisis sintctico
Abstracta: sirve para el anlisis semntico

Sea: S if expr then A endif ;


Concreta

Abstracta (AST)

UTN - FRM: Fundamentos de sintaxis y semntica

57

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva58

Anlisis sintctico

Analizadores recursivos

cada no-terminal tiene asociada una rutina de anlisis,


creada a partir de las reglas gramaticales
scan de izquierda a derecha

Estrategias de anlisis
DESCENDENTE(Top-Down)
construye el rbol desde la raz (S) hacia las hojas
problemas con recursividad a izquierda

ASCENDENTE(Bottom-Up)
construye el rbol desde las hojas hacia la raz (S)
se basa en encontrar una derivacin por la derecha
UTN - FRM: Fundamentos de sintaxis y semntica

58

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva59

Analizador por izquierda (a)

Sea la gramtica G = (N, T, S, P) con


N = {A, S}, T = {a, b, c},
P = {S aAc, A Ab | }
L = {a bn c / n > 0}.

Se quiere reconocer: abbc

UTN - FRM: Fundamentos de sintaxis y semntica

59

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva60

Analizador por izquierda (b)

Sea la gramtica G = (N, T, S, P) con


N = {A, S}, T = {a, b, c},
P = {S aAc, A | Ab}
L = {a bn c / n>=0}.

Se quiere reconocer: abbc

UTN - FRM: Fundamentos de sintaxis y semntica

60

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva61

Recursividad a izquierda
Analizador top-down no puede procesarla
RI Inmediata

A A |

Para eliminarla
Se trabaja con el trmino (que no es RI)
AB
BB |

UTN - FRM: Fundamentos de sintaxis y semntica

61

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva62

Eliminacin recursividad izq.

Sea
S Aa | b
A Ac | Sd | f
Reemplazar: A Sd por A Aad | bd
Queda: A Ac | Aad | bd | f
Eliminar recursividad inmediata:
A bdA | fA
A cA | adA |
Resolver:
SaB|c
Finalmente:

S Aa | b
A bdA | fA
A cA | adA |

BBa|c

UTN - FRM: Fundamentos de sintaxis y semntica

62

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva63

Analizador descendente

Problema del retroceso, sea: G = (N, T, S, P)

N = {<PROGRAMA>, <DECLARACIONES>, <PROCEDIMIENTOS> }


T = {module, d, p, ;, end}
S = <PROGRAMA>
P={
<PROGRAMA> ::= module <DECLARACIONES>; <PROCEDIMIENTOS> end
<DECLARACIONES> ::= d | d; <DECLARACIONES>
<PROCEDIMIENTOS> ::= p | p; <PROCEDIMIENTOS> }

Analizar aplicando derivaciones Leftmost module d ; d ; p ; p end

UTN - FRM: Fundamentos de sintaxis y semntica

63

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva64

Anlisis sintctico

Gramticas LL(k) y analizadores

subconjunto de las gramticas libres de contexto


permiten un anlisis descendente sin retroceso
L = reconocimiento de la cadena de entrada de
izquierda a derecha
L = toman las derivaciones ms hacia la izquierda
("Leftmost") con slo mirar los k tokens situados a
continuacin de donde se halla
si k=1 se habla de gramticas LL(1)

permiten construir un analizador determinista


descendente
slo examinan en cada momento el smbolo actual de la
cadena de entrada para saber que produccin aplicar

UTN - FRM: Fundamentos de sintaxis y semntica

64

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva65

Anlisis sintctico

Gramticas LR(k) y analizadores


Analizadores LR
L = lee entrada de izquierda a derecha (Left-to-right)
R = analiza aplicando derivaciones ms a la derecha
en sentido inverso (Rightmost)
k = nmero de smbolos de entrada por delante
(lookaheads) que lee el analizador (gramtica LR(k))
eficiente anlisis ascendente sin retroceso
detectan errores sintcticos rpidamente
pueden construirse para la mayora de las G2
complicados de construir

UTN - FRM: Fundamentos de sintaxis y semntica

65

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva66

Analizador ascendente

Sean

Produccin: EE+E | E*E | (E) | -E | id


Enunciado: id+id*id
Derivaciones:

UTN - FRM: Fundamentos de sintaxis y semntica

66

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva67

Analizador ascendente

Esquema del algoritmo

UTN - FRM: Fundamentos de sintaxis y semntica

67

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva68

Analizador ascendente
Pila

rbol

Entrada

Regla

UTN - FRM: Fundamentos de sintaxis y semntica

68

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva69

UTN - FRM: Fundamentos de sintaxis y semntica

69

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva70

Fases de anlisis
sup = alto*ancho;
anlisis lxico
(id,sup)(asignador)(id,alto)(opMult)(id,ancho)(separador)
anlisis sintctico
(asignador)
(id,sup)

(opMult)
(id,alto)

(id,ancho)

anlisis semntico

UTN - FRM: Fundamentos de sintaxis y semntica

70

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva71

Semntica

La sintaxis no es suficiente para describir un


lenguaje.
La semntica:
Define qu hacen los enunciados de un lenguaje.
Posibilita implementar correctamente el lenguaje.
Sirve para desarrollar tcnicas y herramientas de:

Anlisis y Optimizacin
Depuracin
Verificacin
Transformacin

Ayuda a razonar sobre el funcionamiento de un


programa (recursos usados, correccin, )
UTN - FRM: Fundamentos de sintaxis y semntica

71

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva72

Semntica esttica

Se calcula en tiempo de compilacin


Tipologa de datos
De la signatura de funciones
Accesos a variables deben coincidir con su declaracin
Identificadores y expresiones deben ser evaluables
Left-side debe ser asignable
Expresiones, funciones y operadores compatibles

Flujo de control
Accesibilidad de las variables para su uso

Unicidad
Uso de identificadores nicos

Ejemplo

var A: integer;

Significado almacenamiento para A

UTN - FRM: Fundamentos de sintaxis y semntica

72

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva73

Semntica dinmica

Ciertos significados se pueden detectar durante


la ejecucin

Punteros con referencias nulas


Valores lmites de subndices de arreglos
Consistencia en el pasaje de argumentos
Otros: x := z / y si y == 0?

Otros no es posible
Errores de lgica cambian la semntica de un
enunciado, pero no son estrictamente, errores
semnticos de los enunciados
x := z / y si lo que se quera escribir era x := z * y

Ejemplo

s = hola; s = 45.78;

25 + 5 255

UTN - FRM: Fundamentos de sintaxis y semntica

73

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva74

Especificacin de la semntica

La especificacin sintctica, en notacin BNF es prcticamente


universal, en tanto que para la semntica, existen diversas tcnicas
sin que ninguna sea universal.

Es deseable satisfacer caractersticas tales como:


No ambigedad: facilitar la creacin de descripciones rigurosas.
Demostracin: permitir la posterior demostracin de propiedades de
los programas escritos en el lenguaje especificado.
Prototipado: posibilitar obtener prototipos ejecutables de los lenguajes
que se disean de forma automtica.
Modularidad: realizar la especificacin de forma incremental.
Reusabilidad: facilitar la reutilizacin de descripciones en diferentes
lenguajes.
Legibilidad: ser legibles por personas con formaciones heterognea.
Flexibilidad: adaptarse a la variedad de lenguajes existentes.
Experiencia: ser capaz de describir lenguajes reales, no slo sencillos o
experimentales.

UTN - FRM: Fundamentos de sintaxis y semntica

74

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva75

Metodologas para especificar

Lenguaje Natural: con restricciones.


Operacional: se especifican las transiciones elementales
de un programa mediante reglas de inferencia definidas
por induccin sobre su estructura.
Denotacional: se describe modelando los significados
mediante entidades matemticas bsicas.
Axiomtica: se definen una serie de reglas de inferencia
que caracterizan las propiedades de las diferentes
construcciones del lenguaje.
Algebraica: permite definir una estructura matemtica
de forma abstracta junto con las propiedades que debe
cumplir.

UTN - FRM: Fundamentos de sintaxis y semntica

75

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva76

Metodologas para especificar

Mquina de Estado Abstracto: se definen algoritmos


mediante una abstraccin del estado sobre el que se
trabaja y una serie de reglas de transicin entre
elementos de dicho estado.
Semntica de Accin: se definen acciones, que expresan
computaciones.
Mondica Modular: se definen mnadas y
transformadores de ellas (una mnada separa una
computacin del valor devuelto por la misma).
Mondica Reutilizable: aade conceptos de
programacin genrica a la anterior.

UTN - FRM: Fundamentos de sintaxis y semntica

76

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva77

Resumen de caractersticas
NAM
Nat.

MOD
S

REU

DEM

PRO

Oper.

Reg

Reg

Deno.

Reg

Axio.

Reg

Alge.

S
Reg

LEG

FLE

EXP

Reg

Reg

Reg

Reg

Reg
S

Reg

Estad.

Reg

Reg

Reg

Acc.

Reg

Reg

Reg

Reg

Reg

Modu.

Reuti.

UTN - FRM: Fundamentos de sintaxis y semntica

77

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________

UTNFRM:SintaxisySemnticadeLenguajes

Diapositiva78

Implementacin de la semntica
Hardware

Intrprete en
hardware

Lenguaje de mquina
Lenguaje ensamblador o
pseudolenguajes

Natural

...

Axiomtica

Denotativa

Operacional

Especificaciones
semnticas

Implementacin de la semntica

Atributos

Estructuras de
datos + algoritmos

Construir
enlazador o
intrprete
Construir
compilador
(traductor)

C, C++, Java, Ruby, JS, PHP, Ada, Pascal, Cobol, Fortran,


UTN - FRM: Fundamentos de sintaxis y semntica

78

________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________