Document 10805460

advertisement
s
t
predictions are always correct.
©
CS 536 Fall 2012
©
CS 536 Fall 2012
247
CSE305 Practice Final Exam(Summer2013) ©
CS 536 Fall 2012
©
CS 536 Fall 2012
247
!"#$%&'()*+,'-.+/0)/1'#2+34"5331.6%7$8'
Duration :1 hour (August 6, 2013)
!"#$%&'(
(Recursive Descent Parsers
Example Duration :1 hour (August
6, 2013)
Name Predict(A
Personal Number → X ...X ) =
!"#$%&'(
(Recursive
AnX early
implementation of topExample
Predict(A
→
1...Xn) =Descent Parsers
LL(1) Grammars
Production
Predict Set
1
n
9+31''''''''!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-1.:;*+,'''953<1.'' down
(LL(1)) parsing was
If X1...Xn⇒* λ
*
rammar whose First(X
S→A
a Then whose
{b,d,a}
1...Xn) U Follow(A)
A context-free
grammar
always disjoint
Production
Predict
Set
!
Else
First(X
1...Xn)
n-terminal) is
said
Predict
sets
are
always
disjoint
LL(1)
Grammars
Question
1
(30pts)
:
→a
B D
{b, d, a}
→A A
{b,d,a}
(for Question
theSsame
non-terminal)
is said
If some
CFG,
G, has the property
A context-free
grammar
whose
1:
A
context-free
grammar
whose
that
for
all
pairs
are ideally
suited
to Consider be
LL(1).
b
}a} of distinct
Predict
sets
always
disjoint
LL(1)
LL(1)
Grammars
fB
ollowing ontext Free A are
→
B→
DbCGrammars
{b,G{ rammar d,with
Predict
sets
are
always
disjoint
productions
rsing because
it
is
(for LL(1)
the "#$%&'()!*#++#,&$-!"#$.(/.!0)((!1)2332)!!
same
non-terminal)
issuited
said the same
grammars
arelefthand
ideally
side,
B
→
λ
{d,
a}
to correctly
(for
the
same
non-terminal)
said
A
context-free
grammar
Afor
context-free
grammar
whose
to be
LL(1).
E top-down
->B T →
E' b
{...X
b }isand
parsing
because
it isA →whose
Y1...Ym
A
→
X
ansion of any
nonto
be
LL(1).
1
n
Predict
sets
are{always
disjoint
Predict
always
disjoint
E'E ->sets
+ TD
Tare
E'
|d
epsilon
->
E'
→
d
}
possible
to
correctly
ckup is LL(1)
ever always
grammars
are
ideally
suited
itsame
isideally
the{d,
case
that
λnon-terminal)
a}
(for
non-terminal)
is said
(for
the
same
issuited
said
E'->B
->
+A
Tcontext-free
E' |the
epsilon
grammars
are
TLL(1)
F→
T'
grammar
whose
predict
the
expansion
of
any
nonforto
top-down
parsing
because
it
is
Predict(A
→
X
T
->
F
T'
T'
->
* Predict
|
epsilon
to be
LL(1).
be
DF T'
→
λ sets
{ a }1it...X
n) ∩
forLL(1).
top-down
parsing
because
is
are
always
disjoint
If X1...Xn⇒
recursive
AnXλearly
implementation
of topPredict(A
→
)descent.
=
1...X)nU
Then
First(X
...X
Follow(A)
down
(LL(1))
parsing
was
Predict(A →
= organized as a set of
A Xparser
*11...Xnn) was
If
X1...X
λ
recursive
descent. one for each
n⇒
Else
First(X
*1...Xn) procedures,
parsing
If X1...X
n⇒ λ...X ) U Follow(A)
Then
First(X
non-terminal.
Each
parsingas a set o
Predict(A
X1...X
11...X
nn→
Predict(A
→
)was
=
A Xparser
organized
n) =
If
someFirst(X
CFG,
property
Then
...Xhas
Follow(A)
1G,
n) )U the
procedure
was
responsible
for each
...X
Else
First(X
*
*1X ...X
parsing
procedures,
one for
that
all
pairs
If
⇒
λ
If
Xfor
λ1 nof
...X
)nandistinct
Else
First(X
1...X
n⇒
1
parsing
sequence
of
tokens
non-terminal.
Each
Predict(A
→the
X...X
=parsing
1...X
n) Follow(A)
LL(1) Grammars
with
the
same
Ifproductions
someFirst(X
CFG,
G,
has
property
Then
First(X
)U
Then
...X
U
Follow(A)
1
nresponsible
1
n) the
derivable
from
its
non-terminal.
If
some
CFG,
G,
has
property
procedure
was
for
*
lefthand
side,
that
all
ofndistinct
Ifpairs
X1First(X
...X
⇒1...X
λ n)
Else
Elsefor
First(X
that
for
all
pairs
of
1...X
n) distinct
parsing
a
sequence
of
tokens
For
example,
a
parsing
procedure,
and
AFirst(X
→
Y1same
...Ym ) U Follow(A)
A → X1...XnThen
productions
with
the
productions
with
the
same
1...X
n the
derivable
from
its
non-terminal.
A,
when
called,
would
call
the
If
some
CFG,
G,
has
property
If
some
CFG,
G,
has
the
property
terminal.
No
backup
is
ever
itlefthand
is the case
thatFirst(X ...X
lefthand
side,
→
{ d→} Y ...Y ) = φ
alwaysFalways
possible
to
correctly
T'->D
->(E)
*possible
F|d
T'
|
epsilon
int
side,
)
Else
to
correctly
Predict(A
scanner
and
match
a
token
that
for
all
pairs
of
distinct
1
n
(forLL(1)
non-terminal)
said
that
for...X
allFor
pairs
of →
distinct
grammars
are1ideally
LL(1)
grammars
aresame
ideally
suited
m issuited
example,
a parsing
procedure
needed.
F
->expansion
(E)
|the
int
and
Y...Y
A
predict
the
of any
nonn and
1...Y
m from
AAn→
Y1with
A→
→X
X1
...X
)∩
Predict(A
X
predict
the
expansion
of{is
any
non1...X→
nsequence
mthe
1
derivable
A. the
productions
same
productions
with
the
same
to
be
LL(1).
for
top-down
parsing
because
it
is
D
→
λ
a
}
Since
the
predict
sets
of
both
B
for
top-down
parsing
because
it
is
then
G
LL(1).
A,
when
called,
would
call
If
some
CFG,
G,
has
the
*
terminal.
No let
backup
is going
ever
a) Assume
we
are
toboth
implement
a LL(1) Parser,
please
write
First Set property
Formally,
itlefthand
the
case
thatdown
terminal.
No
backup
isand
ever
itis
isplease
the
case
that
lefthand
side,
side,
1...Xn ⇒ a...}
always
possible
to
correctly
productions
D
always
possible
to
correctly
a)
Assume
we
are
going
to
implement
a
LL(1)
Parser,
write
down
First
Set
...Y
)
=
φ
Predict(A
→
Y
Starting
with
the
start
symbol’s
scanner
and
match
a token
that
pairs
of distinct
LL(1) grammars
are easy
to parse
LL(1) grammars
are ideally
suited
1 formall
needed.
needed.
and
Follow
Set
forinthe
all
non-terminal
variables
of itPredict(A
(5pts)
...X
)productions
=
First(X
and
Am
→the
Y1from
...Y
Aparsing
→
X...X
and
Anprocedure,
Y1with
...Y
A
→ X1...X→
)∩
→
X11...X
predict
expansion
of
anysince
nonare
disjoint,
this
predict
the
expansion
any
non)n→
∩
Predict(A
X
1
n
1...X
n
m A.then
nsequence
aoftop-down
manner
we
would
derivable
productions
same
and
Follow
Set
all
non-terminal
variables
n Vt | S ⇒+ ...Aa...}
for
top-down
parsing
because
is of it (6pts)
Since
thefor
predict
sets
of
both
Bit
then
G iscase
LL(1).
Formally,
let
Formally,
let
*
grammar
is
LL(1).
terminal.
No
backup
is
ever
terminal.
No
backup
is
ever
predictions
are
always
correct.
it
is
the
that
it
is
the
case
that
match
the
entire
input,
which
lefthand
side,
Aalways
→ X1...X
⇒
a...}
{a in Vt |productions
possible
to
correctly
and
both
D
) with
=
φ φthe start symbol’s
Predict(A →
YY11...Y
...Y
)=
Predict(A
→
Starting
mm
LL(1)
grammars
are
toA)parse
needed.
needed.n are disjoint,
...X
First(X
must
derivable
from
startthen
Ans:n)productions
...X
First(X
...X
Y1the
...Y
A
→1...X
Xbe
predict
of this
any non) easy
∩
Predict(A
→
X
1=
n) = the expansion
...X
∩ we
Predict(A
→
Xand
1
1
n
m
parsing
procedure,
would
n
1
n →
+
then
is
LL(1).
in
a
top-down
manner
since
then
G
is
LL(1).
Follow(A)
=
{a
in
V
|
S
⇒
...Aa...}
symbol.
*
Formally,
let
Formally,
let
*
t
grammar
is
LL(1).
terminal.
No
backup
is
ever
itmatch
is
case
that )input,
→ Xn1...X
⇒ a...}
the
which
| in
AV
→t |XA1...X
⇒ na...}
{a in Vt{a
...Y
) =Yentire
φ...Y
Predict(A
→
Y1the
=
φ
Predict(A
predictions
are
always
m→
1correct.
m
Recall
LL(1) grammars
grammars
are
easy
to to
parse
LL(1)
are
easy
parse
needed.
...X
)
=
First(X
must
be
derivable
from
the start
...X
)
=
First(X
1
n
Predict(A
→since
X1...Xn) ∩
1 +n +
in aa top-down
top-down
manner
Follow(A)
=V
{a in
V
| S* ...Aa...}
⇒ ...Aa...} *
then
G
is
LL(1).
then
G
is
LL(1).
in
manner
since
t
Follow(A)
=
{a
in
|
S
⇒
symbol.
→ X{a1t...X
⇒
a...}
{a in Vt | AFormally,
|A→
X1...Xn ⇒ a...}
in Vntlet
predictionsPredict(A
are
always
correct.
...Y
) = φto parse
Y1correct.
predictions
aregrammars
always
LL(1) grammars
are →
easy
to m
parse
LL(1)
are
easy
First(X1...Xn) =+
+
in
a
top-down
manner
since
in
a top-down
manner since
Follow(A)
in Vt | S ⇒
= {a...Aa...}
in Vt | S ⇒ ...Aa...}
then
G is LL(1).
and = {a Follow(A)
{a in Vt | A → X1...Xn ⇒* a...}
predictions
are always
predictions
arecorrect.
always correct.
LL(1) grammars are easy to parse
in a top-down manner since
Follow(A) = {a in Vt | S ⇒+ ...Aa...}
predictions are always correct.
LL(1) Grammars
©
CS 536 Fall 2012
247
248
©
CS 536 Fall 2012
©
©
CS 536 Fall 2012
CS 536 Fall 2012
!"#$%&'((Recursive Descent Parsers
so
©
©
249
247
CS 536 Fall 2012
©
CS 536 Fall 2012
©
CS 536 Fall 2012
249
247
247
©
CS 536 Fall 2012
CS 536 Fall 2012
248
©
CS 536 Fall 2012
248
©
CS 536 Fall 2012
248
AnX early
implementation of topPredict(A →
1...Xn) =
PredictCS Set
536 Fall 2012
CS 536 Fall 2012
CS 536 Fall 2012
CS 536 Fall 2012
down
(LL(1))
parsing was
*
If
X
...X
⇒
λ
recursive
descent.
1
n
{b,d,a}
hose
Then First(X
U
11...X
Predict(A
→
...Xnn))was
= Follow(A)
A Xparser
organized as a set of
oint
Recursive
Descent Parsers
{b, d, a} Example
CS 536 Fall 2012
CS 536 Fall 2012
247
...X
)
Else
First(X
*1
parsing
procedures,
one for each
n
is said
If X1...Xn⇒ λ
Example IfThen
Recursive
Descent Parsers
whose
non-terminal.
Each
parsing
Predict(A
→ X1...X
{b}
n) =
rs
An early implementation
of topsomeFirst(X
CFG,
property
...Xhas
Follow(A)
1G,
n) U the
sjoint
procedure
was
responsible
for
*
Production
Predict
Set
Therefore,
that
for
all
pairs
of
distinct
down
(LL(1))
parsing
was
If
X
...X
⇒
λ
suited
Else First(X
1 n) a
n
{d,
An early implementation of top1...X
l)
is a}
said
parsing
of tokens
grammar
productions
with
thesequence
same
se it is whose
recursive
descent.
Production
Predict
Set
Then
First(X
Follow(A) Recursive
1...X
n) U
S
→
A
a
{b,d,a}
down
(LL(1))
was ofParsers
derivable
from
its
non-terminal.
Example
always
disjoint
If
some
CFG,
G,
has
the
property
Example
Recursive
FIRST(E)
= { (,side,
int } FIRST(E') = { +, epsilon }An
FIRST(T)
=Descent
{ parsing
(, int Descent
}Parsers
early
implementation
toplefthand
y{ d }
...X
)
Else
First(X
1FIRST(F)
n
A
parser
was
organized
as a set of
on-terminal)
isSsaid
recursive
descent.
that
for
all
pairs
of
distinct
yysuited
Production
Predict
Set
FIRST(T')
=
{
*,
epsilon
}
=
{
(,
int
}
For
example,
a
parsing
procedure,
→
A
a
{b,d,a}
...Xnd,and
A
→
Y
...Y
→ X1{b,
non- A → B D Aproductions
down
(LL(1))
parsing
was
1
m
a} the
An
earlyprocedures,
implementation
topwith
same
ause
parsing
one
each
An
early implementation
when
called,
would
the
IfA,some
CFG,
G, has
the call
property
A parser
was
organized
asfor
aofset
of of topr{ a } it is Production
itlefthand
is{b,d,a}
the
case
that
recursive
descent.
Predict
Set
Production
Predict
Set
side,
S
→
A
a
tly
A
→
B
D
{b,
d,
a}
down
(LL(1))
parsing
was
scanner
and
match
a
token
that
for
all
pairs
of
distinct
non-terminal.
Each
parsing
down
(LL(1))
parsing
was
s are ideally
suited
parsing procedures, one for each
B → b
b→} and
A n→
Y1with
...Y
A →=X{1{...X
)∩
Predict(A
X
any
nonn
1...X
derivable
A.
A
organized
asfor
a set of
recursive
descent.
productions
same
arsing
because
it is
t sets
of
both
B
FOLLOW(S)
$a
}sequence
FOLLOW(E)
= {mthe
$, from
) } FOLLOW(E')
=parser
{ $, )was
}was
recursive
descent.
procedure
responsible
S
→
A
a
{b,d,a}
non-terminal.
Each
parsing
S
→
A
{b,d,a}
B
→
b
{
b
}
A
→
B
D
{b,
d,
a}
it
is
the
case
that
lefthand
side,
FOLLOW(T)
=
{
+,
epsilon
}
FOLLOW(T')
=
{
+,
$,
)
}
to correctly
deerboth
D B→ λ
parsing
each
early
implementation
{d,→Starting
a}Y1...Ymwith
) = φthe start symbol’s
Predict(A
parsing
sequence
ofone
tokens
A
parseraprocedures,
was
organized
asfor
a set
of aof
procedure
was
responsible
for
AAn
parser
was
organized
as
settopof
FOLLOW(F)
={b,
{ *,
epsilon
}and
Production
Predict
Set
Aa}
→we
Y1...Y
Aparsing
→
X1...X
ansion
ofA
any
nondisjoint,
this
...X
)∩
Predict(A
→
X
→
B
D
d,
a}
n
m
procedure,
would
then
non-terminal.
Each
parsing
A
→
B
D
{b,
d,
down
(LL(1))
parsing
was
1
n
B
→
λ
{d,
a}
derivable
from
its
non-terminal.
parsing
procedures,
one
for
each
parsing
a
sequence
of
tokens
B
→
b
{
b
}
then
G
is
LL(1).
parsing
procedures,
one
for
each
D → d
{ d itmatch
} is
1).
ackup
is ever
case
.}
recursive
descent.
procedure
was
responsible
for
...Ythe
) =entire
φthat input, which
Predict(A
Y1the
derivable
from
its
non-terminal.
non-terminal.
parsing
m
S LL(1)
→
A→grammars
abb{→
{b,d,a}
non-terminal.
Each parsing
B
→
b
{
}
For
example,
aEach
parsing
procedure,
are
easy
B
{
b
} ton)parse
D
→
d
d
}
must
be
derivable
from
the start parsing
...X
∩
Predict(A
→
X
B →D λ→ λ
{d,
a}
a
sequence
of
tokens
1
procedure
responsible
for
}symbol.
then
G{isaLL(1).
Awas
parser
was
organized
asfor
a set of
procedure
was
responsible
in
a top-down
manner since
Forwhen
example,
a parsing
procedure,
A,
called,
would
call
the
.Aa...}
...}
→
B
D
{b,
d,
a}
B →D λ→ λA predictions
{d,
a}
derivable
from
its
non-terminal.
parsing
a
sequence
of
tokens
...Y
)
=
φ
Predict(A
→
Y
{
a
}
B
→
λ
{d,
a}
are
always
correct.
parsing
procedures,
one
for
each
parsing
a
sequence
of
tokens
A,
when
called,
would
call
the
1 to m
LL(1)
are easy
parse
scanner and match a token
D → d
{ dgrammars
}
derivable
from
its
non-terminal.
in
a
top-down
manner
since
scanner
and
match
a
token
non-terminal.
Each
parsing
derivable
from
its
...Aa...} *D →
For
example,
a parsing
sequence
derivable
fromprocedure,
A.non-terminal.
is{ LL(1).
Since
→
b{ ddsets
b{ d
}B }
d theB predict
}thenofGboth
D {→
a...}λ Since the
predictions
are of
always
a }both
1...XnD⇒ →
sequence
derivable
from
A.
procedure
was
responsible
for
For
example,
a
parsing
procedure,
predict
sets
bothcorrect.
B are easy to parse A,
when
called,
would
call
theprocedure,
productions
and
Dgrammars
LL(1)
For the
example,
a parsing
Starting with
start symbol’s
D
λ
{
a
}
B
→
λ
{d,
a}
+ → productions
and
both
D
parsing
a
sequence
of
tokens
A,
when
called,
would
call
the
D
→
λ
{
a
}
scanner
and
match
a
token
in
a
top-down
manner
since
Starting
with
the
start
symbol’s
n Vt | S ⇒ ...Aa...}
productions are disjoint, this
A, when called,
would
call the
parsing procedure,
we would
then
productions
are disjoint,
scanner
and
match
afrom
token
predictions
derivable
its
parsingthe
procedure,
we
would
sequence
derivable
from
A.then
grammar
is LL(1).
scanner
and
match
anon-terminal.
token
Since
the
predict
sets
of boththis
Bare always correct.
match
entire
input,
which
©
©
247
©
247
©
©
248
©
Example
Recursive Descent Parsers
Example
249
Recursive Descent Parsers
©
CS 536 Fall 2012
250
248
b)b)
fill out
out following
followingform
formto
toderive
deriveaaa
LL(1)
According
tothe
theresult
resultin
in a),
following
form
to
derive
LL(1)
b)According
Accordingto
a), please
please fill
LL(1)
induction
induction
(6pts)
induction(5pts)
(6pts)
!!
"!
"!
#!
$!
%!%!
&'(!!
&'(!!
)*+,-'!
)*+,-'!
)!
)!
!!
!
E -> TT
E'
!!
-> TT
EE ->
E'
E'
!!
).!
).!
+ T E'
!
!
/!
/!
!!
!
T -> FF
T'
/.!
/.!
T ->
T' ->
epsilon * F T'
!
0!0!
!!
F -> ((
E )
!!
E' ->
->
E'
epsilon
epsilon
!!
-> FF
TT ->
T'
T'
!
!
T'
T' ->
->
epsilon
epsilon
!!
FF ->
->
int
int
!
!!
E' ->
->
E'
epsilon
epsilon
!!
T'
T' ->
->
epsilon
epsilon
!!
!!
c) Assume we need to parse 3+5*7 for the grammar describe above, please fill out
c) Assume
Assume we
we need to parse 3+5*7 for the
c)
the grammar
grammar describe
describeabove,
above,please
pleasefill
fillout
out
following
stack
trace
(5pts)
following stack
stack trace
trace (6pts)
(6pts) !!
following
!"#$%&
!"#$%&
'%(#)&&
'%(#)&&
'%*+,-&%.#&/0&."&1(2%3&&&
'%*+,-&%.#&/0&."&1(2%3&&&
456789&&&&&&
456789&&&&&&
:;&
:;&
<&<&
456789&&&&&&
456789&&&&&&
=;&&
=;&&
>&<?&&
>&<?&&
456789&&&&&&
456789&&&&&&
4;&&
4;&&
@&>?&<?&&
@&>?&<?&&
456789&&&&&&
456789&&&&&&
A;&&
A;&&
!"%&>?&<?&&
!"%&>?&<?&&
56789&&&&
56789&&&&
6;&&
6;&&
>?&<?&&
>?&<?&&
56789&&&&
56789&&&&
B;&&
B;&&
<?&&
<?&&
56789&&&&
56789&&&&
8;&&
8;&&
5&>&<?&&
5&>&<?&&
6789&&&
6789&&&
C;&&
C;&&
>&<?&&&&&
>&<?&&&&&
6789&&&
6789&&&
D;&&
D;&&
@&>?&<?&&&&
@&>?&<?&&&&
6789&&&
6789&&&
:E;&&
:E;&&
!"%&>?&<?&&&&&&&&&&
!"%&>?&<?&&&&&&&&&&
789&&&
789&&&
::;&&
::;&&
>?&<?&&&&&&&&&
>?&<?&&&&&&&&&
789&&&
789&&&
:=;&&
:=;&&
7&@&>?&<?&&&&&&&&
7&@&>?&<?&&&&&&&&
!"###
$%&##
'#()#*)#####
!"###
$+&##
,-.#()#*)####
"##
$/&##
()#*)###
"#
$0&##
*)##
"####
$!&##
123*4#####
#
#
d) 56##7889:;#<=,>,-?@@A#B;#B?-.#.<#,:C@;:;-.#D<@@<B,->#>=?::?=##
Assume originally we want to implement following grammar E
T
F
E->->E E+ +T T| |T T
T->->T T* *F F| |F F
F->->(E)
(E)| |int
int
Please answer why we would like to change the grammar into the alternative E@;?8;#?-8B;=#BFA#B;#B<9@5#@,G;#.<#HF?->;#.F;#>=?::?=#,-.<#.F;#?@.;=-?.,I;#
D<=:?.#5;8H=,J;5#?8#,-#<9=#K9;8.,<-#L0C.86###
format described as in our question (5pts) Ans:
Ans: This is a grammar for arithmetic. There are several orders of precedence
here: ()'s beat *, and * beats +. We'd like to parse sentences using this grammar
Since
it is recursive
left recursive,
which
is not good for look ahead 1 token
usingT->E+T,
a top-down,
descent
algorithm.
leftmost derivative(LL1) parser.
This algorithm traverses the grammar looking for matches between terminals (*,
+, (,
), and int)
and the
input sentence.
Wewhy
do this
search
depth-first,
But
anyway
we need
recursive
definition,
don’t
we change
it towhich
right
presents
a
problem.
If
we
start
at
the
starting
production
E,
and
derive
the
recursive to avoid infinite expanding rules on stack.
production E + T, we have E still on the left. In recursive-descent parsing, we can
onlyhere
expand
the change
left-mostE->E+T
non-terminal
at <left>
each step!
We're going to infinitely
OK,
is idea,
to E->
+ <right>.
loop if we try to parse sentences using this grammar.
Originally, <left> is E, now change it to T, so it is never left recursive.
How do we fix it? We use a technique known as left-recursion elimination to get
Atrid
theofsame
time, change <right> to E’, which could be right recursive, but for
the non-terminals on the left-hand side of each production that cause us to
LL1
parser,
it does
notnot
matter,
since, even
without
seeing any
in Tthe
now,
infinitely loop.
(Note:
all grammars
have
left recursion.
Youterminal
can identify
weones
canthat
see have
at least
one ‘+’ left
in E’,
which isbyterminal
to all
stop
recursive. -- if
immediate
recursion
looking at
of left
the productions
the non-terminal on the left side of the arrow is the same as the non-terminal in
This
we have
firstof
and
E right
-> T E’
E’ arrow,
-> + T then
E’ | epsilon
the way
left-most
position
anysecond
phraserule,
on the
sideand
of the
this
Same
way
we
have
third
and
fourth
rule,
F
->
F
T’
and
T’
->
*
F
T’
|
epsilon
grammar is left-recursive. There are other forms of left recursion that can show
up if you were to "recurse" down multiple rules in the grammar. If you
Soeventually
include Fwill
-> (E)
| int
, now
we loop,
have the
all of
the rules
need.
cause
any
infinite
grammar
is we
left-recursive.)
You can try to do the same thing for LR parser in order to remove all right
recursive rules.
e) Please convert following HTML/XML file into Context Free Grammar: (5pts)
<html>
<head>
<title> Try the frame tags</title>
</head>
<frameset rows="100,*">
<frame name= "top" src="banner.htm">
<frame name="left" src="menu.htm">
<frame name="middle" src="content.htm">
<frame name="right" src="right.htm">
</frameset>
</html>
Ans: <html> -­‐> <head> | <frameset> <frameset> -­‐> <frame> <frameset> <head> -­‐> <title> f) Based on following shell script (which is called mytest.sh),
#!/bin/sh
# A simple script who am i date pwd sum=0 for var in "$@" do if [ $var -­‐gt 2 ] then sum=`expr $sum + $var` fi printf "%s\n" $var done printf "%s\n" $sum Ans: Your user-­‐name Current time Current directory 2 4 5 9 What is the result if we type command: sh mytest.sh 2 4 5 (5pts)
Question 2 (12pts): Please answer the following questions based on SWI-Prolog.
All questions here is based on following:
parent(chester,irvin).
parent(chester,clarence).
parent(chester,mildred).
All questions here is based on following:
parent(irvin,ron).
parent(irvin,ken).
parent(chester,irvin).
parent(clarence,shirley).
parent(chester,clarence).
parent(clarence,sharon).
parent(chester,mildred).
parent(irvin,ron).
parent(clarence,charlie).
parent(irvin,ken).
parent(mildred,mary).
parent(clarence,shirley).
parent(clarence,sharon).
parent(clarence,charlie).
parent(mildred,mary). !
a) What are the results of following four queries ? !
(3pts) "#!$%"&!"'(!&%(!'()*+&)!,-!-,++,./01!-,*'!2*('/()!3!!!!
male(chester).
female(mildred).
male(irvin).
female(shirley).
male(chester).
male(clarence).
female(mildred).
female(sharon).
male(irvin).
male(ron).
female(shirley).
male(clarence).
female(mary).
female(sharon).
male(ken).
male(ron).
male(charlie)
female(mary).
male(ken).
male(charlie)
?- parent(chester,mildred).
?- parent(chester,mildred).
Ans:
true.
Ans: true.
??- parent(X,ron).
parent(X,ron).
Ans:
Ans: XX == irvin.
irvin.
?- parent(irvin,X).
?- parent(irvin,X).
Ans:
X = ron ;
Ans: X = ron ;
XX == ken.
ken.
?- parent(X,Y).
parent(X,Y).
?-
Ans: X = chester,
Y = irvin ;
X = chester,
Y = clarence ;
X = chester,
Y = mildred ;
X = irvin,
Y = ron ;
X = irvin,
Y = ken ;
X = clarence,
Y = shirley ;
X = clarence,
Y = sharon ;
X = clarence,
Y = charlie ;
X = mildred,
Y = mary.
b) Now we add some additional rules to the facts above:
b) Now we add some additional rules to the facts above:
father(X,Y) :-­‐ parent(X,Y), male(X). grandparent(X,Y) :-­‐ parent(X,Z), parent(Z,Y). paternalgrandfather(X,Y) :-­‐ father(X,Z), father(Z,Y). sibling(X,Y) :-­‐ parent(Z,X), parent(Z,Y). What are the results of following queries ? (3pts)
?- paternalgrandfather(X,ken).
Ans: X = chester
?- paternalgrandfather(chester,X).
Ans: X = ron ;
X = ken ;
X = shirley ;
X = sharon ;
X = charlie ;
?- sibling(ken,X).
Ans: X = ron ;
X = ken ;
c) What if we test following predefined predicates ? (3pts)
?- ken = ken.
Ans: true.
?- =(ken,ron).
Ans: false.
?- ken = X.
Ans: X = ken.
?- \+ (ken=ron).
Ans: true.
?- \+ (mary=mary).
Ans: false.
d) If we remove sibling rules previously and replace it with this one:
paternalgrandfather(X,Y) :- father(X,Z),
father(Z,Y).
paternalgrandfather(X,Y)
:- father(X,Z),
father(Z,Y).
What are the results of following queries ?
What are the results of following queries ? (3pts)
?- sibling(ken,X).
X = ron ;
?- Ans:
sibling(ken,X).
X
ken.
Ans: X = =ron
;
X = ken .
?- sibling(X,Y).
?- sibling(X,Y).
Ans:X X= =Y,Y, YY == Irvin.
irvin .
Ans:
Question 3 (28pts) : Please answer following questions and if there is operational
Question 3: Please answer following questions and if there is operational
semantics, by default it refers to big-step induction.
semantics, by default it refers to big-step induction.
a ) Consider the syntax if below, which is similar to C programming language :
a ) Consider the syntax if below, which is similar to C programming language :
if t1 then t2 else if t3 then t4 else t5
if t1 then t2 else if t3 then t4 else t5
An if expression first evaluates expression t1, if it is 1 then evaluate t2; its
An if expression first evaluates expression t1, if it is 1 then evaluate t2; its
evaluation result of t1 is false, then evaluate t3, if it is true, then evaluate t4;
evaluation result of t1 is false, then evaluate t3, if it is true, then evaluate t4;
otherwise evaluate t5.
otherwise evaluate t5.
The type of the whole expression is T. Please give type checking rule for the
The type of the whole expression is T. Please give type checking rule for the
expression. ( 5pts)
expression.
Ans:
true ! T
false ! T
t1 ! T
0!T
t1 ! T
succ t1 ! T
t1 ! T
pred t1 ! T
t3 ! T
iszero t1 ! T
t3 ! T
succ t3 ! T
pred t3 ! T
t1 ! T
if
t3 ! T
t1 then
t2
t2 ! T
else if
iszero t3 ! T
t3 ! T
t4 ! T
t3 then t4
t5 ! T
else t5 ! T
Or you can use following notation system:
! ! t1 : Bool
Oryou
youcan
canuse
usefollowing
followingnotation
notation
system:
Or
system:
Or you can use following notation system:
! ! t1 : Bool ! ! t3 : Bool
! ! t1 : Bool
! ! t3 : Bool ! ! t2 : T
! ! t3 : Bool
! ! t4 : T
! ! t2 : T
103
!9.2
! t2 The
: T Typing Relation
! ! t5 : T
! ! t4 : T
!
!
t
:
T
9.2 The Typing4 Relation
103
9.2 The Typing Relation
103 on λ (5-3)
→ (typed)
Based
! ! t :T
! ! t!5 :5!T if t then t else if
t3 then t4
else t5 " T
1
2
→ (typed) Syntax
Based on λ (5-3) t !→ t!
Evaluation
(typed)
Based on λ (5-3)
t ::=
! ! if t1 then t2 else if terms:
t then t4
else t5 t" !→
T !
!
!b)
if Assume
t1 then we
t2 have
else type
ifvariable
t3: S3 then
t4 U<:T,
else what
t5 "1inference
T t1 can you make?
yntax
,
S<:
U,
!
!
x
(E-App1)
Evaluation
t !→ t
ntax
!
!
t
t
!→
t
t
Evaluation
t
!→
t
1
2
2
Using
operational
semantics
to
represent
the
conclusion.
1
t ::=
terms:
λx :T .t
abstraction
!
tinference
::=
terms:
1 !→ t
!1
b)
we
have
type
,
S<:
U,
U<:T,
what
you
make?
τ
:
S
b) Assume
Assume
we
have
type
,
S<:
U,
U<:T,
what
inference
can
you
make?
!
:
S
x
variable
t
!→
t
tt
application
(E-App1)
1
tcan
t!2make?
1 ! can
2 !→
b) Assume
we have type
U, U<:T, what
inference
you
!
: S , S<:
x
variable
(E-App1)
t
t
!→
t
t
onal semantics
to
represent
the
conclusion.
(5pts)
1 2
2
(E-App2)
Usingoperati
operational
semantics
to
represent
the
conclusion.
1
!
λx :T Using
.t
abstraction
! ! t : Sto represent
S <:U the
U :<
t
t12 t2 !→ v1 t!2
1Tt2 !→ t1 v
Using operational semantics
conclusion.
λx :T .t
abstraction
!
Ans:
t t v ::=
application
t2 !→ t
values:
!2
tt
application ! ! t <: T
t
!→
t
2
(E-App2)
v2 ]t12 (E-AppAbs)
:T112 .t12
U :< Tvalue v(λx
! ) v2 !→ [x "
λx :T!.t! t : S S <:U
abstraction
(E-App2)
t
!→
v
t
1
2
1
!
!
t
:
S
S
<:U
U
:<
T
!2
v1 t2 !→ v1 t2
Ans:
v ::=
values:
Typing
Γ #t:T
Ans:
!!
t <: T
::=
values:
(λx :T11 .t12 ) v2 !→ [x " v2 ]t12 (E-AppAbs)
! ! t <:
T
λx T
:T .t
abstraction
value
::=
types:
(λx :T11 .t12 ) v2 !→ [x " v2 ]t12 (E-AppAbs)
λx :T .t
abstraction
value
c) The
typing rule
for variables follows
immediately
from
x:T
∈ Γthis our lectures. A
T→T
type of functions
Typing
Γ #t:T
(T-Var)
c) The typing rule for variables
follows
immediately from thisΓ our
Typing
Γ #At :x T: # " !
# xlectures.
T have:
T ::=
types:
variable has whatever
type we are currently assuming
it: to
. Next,
::=
types: follows immediately
c) The typing rule for variables
from
x:T
∈ Γthis our lectures.
x :τ ∈ Γ A ! ! x : T
T→T
functions
The typing
ruletype
for of
variables
immediately
from
this
our lectures. A.(T-Var)
variable
has whatever
type
we follows
are currently
assuming
have:
Next,
x:T
∈itΓto
Γ c)
::=
contexts:
T→T
type of
functions
: #xT"
we
need
a
rule
for
application:
, x:T
Γ # x it
:Γto
T
Γ
:
1 #t
2x:
2T!(T-Var)
variable
has
whatever
type
we
are
currently
assuming
have:
.
Next,
∅
empty context
Γ # x it
: to
T have: x : # " ! . Next,
(T-Abs)
variable
whatever
type we are currently assuming
!
!
x
:
T
we needhas
a rule
for application:
Γ
#
λx:T
.t
:
T
→T
1
2
1
2
Γ ::=
! ! x :T
Γ , x:T ! ! t : T "
term
variable
Tcontexts:
! ! t 2 : binding
T11
1
11
12
we need a rule
for
application:
Γ , x:T1 #
tt1
T2
::=
contexts:
2 :evaluates
.
In
English:
If
to a function
∅ we
context
rule
application:
Γ , x:T1 # t2 : T2
(T-Abs) mapping
Γ need
t1 : T11a →
T12 for empty
Γ
! tt21 : context
Tt11
!empty
∅
Γ
#
t
:
T
→T
Γ
#
t
: T11
2 :. TIn
12 English: If
(T-Abs)
Γ #
λx:T
.t
:
T
→T
1
11
12
2
1
2 to1 a function
2
t1 evaluates
mapping
Γ , x:T ! ! t :ΓT t"
term
variable
binding
Γ #
λx:T
.t2 : T1the
→T2assumption that the (T-App)
T
!
!
t
:
T
1(under
arguments
in
T2
to
results
in
T1
terms
t
:
T
1
11
12
2
11
Γ , x:T ! ! t : T "
term
1 T 2variable
to ta1 tfunction
! 12! t 2 : binding
T11 . In English: If t1 evaluatesΓ #
2 : T12 mapping
1
11
12
.
In
English:
If
t1
evaluates
to
a
function
mapping
by its free
yield
results
ofΓ the
! ! trepresented
: T12to results
arguments
in variables
T1Γ #
(under
the
assumption
that
the termsto them by ),
t1 :
T11
→T
# ttypes
T11associated
1 in t 2 T2
12
2 :
! ! t1 and
t 2 : if Tt2
Γ
#
t
:
T
→T
Γ
#
t
:
T
12
(T-App)
evaluates
to
a
result
in
T2,
then
the
result
of
applying
t1
to),t2 will be a
1
11
12
2
11
represented
yield
associated
them
by
arguments by
in its
T2free
to variables
results in
T1results
(underof
thet types
assumption
thatto the
terms
(T-App)
Γ
#
t
:
T
1
2
12
arguments
in
T2
to
results
in
T1
(under
the
assumption
that
the
terms
value
type
T1.in T2,
Please
derive
expression
using
operational
and
if t2Pure
evaluates
totyped
a variables
result
then
the
of
t1 to to
t2 them
will
be
Γ result
#)the
t1following
ttypes
T12associated
represented
by itsoffree
yield
results
of
bya),
Figure
9-1:
simply
lambda-calculus
(λ
2 :applying
→
represented
by
its
free
variables
yield
results
of
the
types
associated
to
them
by
),
semantics
:
value
T1. Please
derive in
following
operational
semantics
and ifoft2type
evaluates
to a result
T2, thenexpression
the result using
of applying
t1 to t2
will be a
and
if t2ofevaluates
to a result
inBoolean
T2, then
the resultexpression
of applyingusing
t1 to t2operational
will be a
(Assume
function
body
returns
value).
value
type
T1.
Please
derive
following
igure 9-1: Pure
simply
typedT1.
lambda-calculus
(λ → ) following expression using operational
value
of typed
type
(!x : Please
Bool . x)derive
true
gure 9-1: Pure
simply
lambda-calculus
(λ
semantics
:
→)
semantics
(λx : (6pts)
Bool . x) true
(5pts) (!x : Bool . x) true
Ans:. x) true
(!x : Bool
x:Bool ∈ x:Bool
(6pts)
T-Var
(6pts)
x:Bool # x : Bool
Ans:
x:Bool ∈ x:Bool
T-Abs
T-True
Ans:
x:Bool ∈ x:Bool T-Var
# λx:Bool.x
:
Bool→Bool
#
true
:
Bool
x:Bool # x : BoolT-Var
T-App
x:Bool # x : Bool
T-Abs
T-True
# (λx:Bool.x)
true
:
Bool
# λx:Bool.x : Bool→BoolT-Abs
# true : BoolT-True
# λx:Bool.x : Bool→Bool
# true : Bool T-App
T-App
9.2.2
Exercise [#
$]: Show (by drawing
derivation trees)
that the following terms
# (λx:Bool.x)
true : Bool
# (λx:Bool.x) true : Bool
have the indicated types:
9.2.2
Exercise [# $]: Show (by drawing derivation trees) that the following terms
9.2.2
Exercise [# $]: Show (by drawing derivation trees) that the following terms
1. f:Bool→Bool
# f (if false then true else false) : Bool
have the indicated
types:
have the indicated types:
� e1 : lambda x . e1�
� e1� [e2 /x ] : e
� (e1 e2 ) : e
�
�
Consider both rules:
� e1 : lambda x . e1�
� e1� [e2 /x ] : e
� (e1 e2 ) : e
Observe that in this rule, we are not evaluating e2 before
substitution.
�
� e1 : lambda
� e2 : e2�
� e1� [e2� /x ] : e
� (e1 e2 ) :
Consider the expression (lambda x.3 4+"duck"):
� Consider
the following
modified
rule:
d)
a
using
Standard
ML
The
Lambda
Rule
cont.
Ruleaa
1 real
evaluates
d) Please
Pleasewrite
write
aprogram
program
using
Standard
MLto
tocalculate
calculatepower
powerof
of
real this expression to ”3”
�
� consider
e1 : lambda x . einteger
number(
Notice
here
we
only
exponent).
Give
the
final
type
1
number( Notice here we only
consider integer exponent). Give theRule
final
2 “getstype
stuck” and returns no value since addin
e2 : e2�
� Consider�both
integer
and
string is undefined (we have not given a
rules:
inference
too(
there
is
no
need
to
write
down
operational
semantics)
.
(4pts)
�
�
� e1 [e2to
/x ] write
:e
inference too( there is no need
down operational semantics)
. (6pts)
�
�
mbda x . e1�
x] : e
1 e2 ) : e
�
Ans:
Ans:
�
e are not evaluating e2 before
fun
fun
(base:real,
0 ) = 1.0
powerpower
(base:real,
0) = 1.0
Thomas Dillig,
fied rule:
lambda x . e1�
e2�
� /x ] : e
2
(e1 e2 ) : e
Lecture 7: Operational Semantics I
�
CS312: Programming Languages
Lecture 7: Operational Semantics I
25/37
Consider the expression (lambda x.3 4+"duck"):
Two reasonable ways of defining application, but diff
semantics!
Thomas Dillig,
�
CS312: Programming Languages
Lecture 7: Operational Semantics I
;
;
�
Rule 1 evaluates this expression to ”3”
� Rule 2 “gets stuck” and returns no value since adding an
and before
string issubstitution
undefined (we
have as
not given a rule)
Not evaluating theinteger
argument
is known
call-by name, evaluating the argument before substitution as
� Two reasonable ways of defining application, but different
call-by-value.
�
semantics!
Consider the following expression in L syntax:
(lambda x.x+x+x (77*3-2))
�
Languages with call-by-name: classic lambda calculus, ALGOL
� Under call-by-name semantics, we substitute (77*3e)
60,our
L
e) Remember
Rememberin
in
ourlecture
lecturethat
thatwe
wetry
tryto
todefine
definethe
thesemantics
semanticsof
ofthe
thelet-binding
let-binding
and reduce the problem of evaluating (lambda x.x+
25/37
Thomas
Dillig,
CS312:
Programming
Languages
Lecture
7:
Operational
Semantics
I
26/37
in
L:
let
x
=
e1
in
e2
(77*3-2)) to evaluating ((77*3-2)+(77*3-2)+(7
in L: let x = �e1
in e2 with call-by-value: C, C++, Java, Python,
Languages
FORTRAN, . . .
One
Onepossibility:
possibility:
Call-by-name
vs. Call-by-value
� Advantage
of call-by-name:
If argument is not used, it will not
ue
�
| power
(base:real,
exp:int):real
= base * power(
base,
| power
(base:real,
exp:int):real
= base*pow(base,
exp
– 1 ) exp -1 )
Call-by-name vs. Call-by-value
Call-by-name vs. Call-by-value
ule, but it gives a different meaning
uages
� e1 : lambda x . e1
�
� e1 : lambda
� (ex1. ee21) : e
� e2 : e2�
�
� e1 [e2 /x ] : e
� e1� [e2� /x ] : e
This also is a well-formed
� (e1 e2 rule,
) : e but it gives a different meaning
� (e1 e2 ) : e
to the lambda expression
be evaluated
t before substitution is known as
e argument before substitution as
�
�
We compute the value of x three times
�
Under call-by-value semantics, we first evaluate (77*
229 and then evaluate 229+229+229
Disadvantage: If argument is uses k times, it will be evaluated
the following expression in L syntax:
times! � Consider
What
definition:
Whatabout
aboutthe
thekfollowing
following
definition:
(lambda
x.x+x+x (77*3-2))
e: classic lambda calculus, ALGOL
e: C, C++, Java, Python,
Thomas Dillig,
CS312: Programming Languages
Lecture 7: Operational Semantics I
27/37
Thomas Dillig,
CS312: Programming Languages
Under call-by-name semantics, we substitute (77*3-2) for x
and reduce the problem of evaluating (lambda x.x+x+x
Semantics of the(77*3-2))
let-bindingto evaluating ((77*3-2)+(77*3-2)+(77*3-2))
Eager vs. Lazy Evaluation
�
If argument is not used, it will not
�
We compute the value of x three times
Let’s try to define the semantics of the let-binding in L:
let x = e1 in e2
� Under call-by-value
Are
and
??evaluate
(4pts)
semantics,
we first
(77*3-2) to
Arethese
thesedefinition
definitionequivalent
equivalentor
ornot
not
andwhy
why
(6pts)
�
�
229 and then evaluate 229+229+229
One possibility:
s uses k times, it will be evaluated
uages
Lecture 7: Operational Semantics I
Lecture 7: Operational Semantics I
�
� e1 : e1�
� e2 [e1� /x ] : e
� let x = e1 in e2 : e
27/37
�
What
about the following definition?
Thomas Dillig,
CS312: Programming Languages
Lecture 7: Operational Semantics I
� e2 [e1 /x ] : e
� let x = e1 in e2 : e
�
Evaluating e1 before we know that it is used is called
evaluation
�
Waiting until we need it is lazy evaluation.
�
These
are analogous to call-by-name/call-by value in
28/37
offs.
Eager vs. Lazy Evaluation
Are these definitions equivalent?
ntics of the let-binding in L:
Thomas Dillig,
� e2 [e1� /x ] : e
= e1 in e2 : e
CS312: Programming Languages
Ans:
efinition?
2 [e1 /x ]
:e
= e1 in e2 : e
Lecture 7: Operational Semantics I
29/37
Thomas Dillig,
�
Evaluating e1 before we know that it is used is called eager
evaluation
�
Waiting until we need it is lazy evaluation.
�
These are analogous to call-by-name/call-by value in trade
offs.
CS312: Programming Languages
!
5
lent?
uages
Lecture 7: Operational Semantics I
29/37
Thomas Dillig,
CS312: Programming Languages
Lecture 7: Operational Semantics I
30/37
Lecture 7: Operational Semantics I
f) Consider following C++ data structure:
f) Consider following C++ data structure:
typedef
struct{
f)typedef
Consider
following C++ data structure:
struct{
char
mychar;
typedef
struct{
char
mychar;
int
myint;
char
mychar;
int
myint;
float
myfloat;
int
myint;
float
myfloat;
double
mydouble;
float
myfloat;
double
mydouble;
void*
myvoid();
double
mydouble;
void*
myvoid();
}myStruct;
void*
myvoid();
}myStruct;
Please
calculate size of memory needed to create object myStruct? What if we
}myStruct;
Please
calculate sizeisofthere
memory
object
What
if we
use sizeof(myStruct),
any needed
change to
in create
terms of
how myStruct?
many bytes?
Why
or
use
sizeof(myStruct),
is
there
any
change
in
terms
of
how
many
bytes?
Why
or
Please
calculate
size
of
memory
needed
to
create
object
myStruct?
What
if
we
why not? (5pts)
whysizeof(myStruct),
not? (5pts)
use
is there any change in terms of how many bytes? Why or
Ans:
why not? (5pts)
Ans: At least it needs 25 bytes.
Ans: At
At least
least itit needs
needs 17
25 bytes
bytes.on heap, since:
size of a char is: 1
size of a char is: 1
size of an int is: 4
size of an int is: 4
size of a float is: 4
size of a float is: 4
size of a double is: 8
size of a double is: 8
size of a void* is: 8
size of a void* is: 8
But sizeof(myStruct) is: 24
But sizeof(myStruct) is: 24
Sizeof simply calculate data field in C/C++ struct.
Sizeof simply calculate data field in C/C++ struct.
Reason for the difference of size is: different compiler will need different
information to refer to each field efficiently. In our case gnu c++ compiler will use
7 bytes additional space.
Question 4 (20pts): Please answer following questions based on object-oriented
programming knowledge you have learnt in lectures.
a) Assume we have following class/structure called c and object Counter.
c=
let
r = { x= ref 7 } in
{
get =
! _ :Unit. !(r.x),
set =
!i : Nat. r.x = i,
inc =
! _ :Unit. r.x := succ(!(r.x))
}
as Counter;
inc2 =
! c : Counter. (c.inc unit; c.inc unit);
what is the result of following statements? (5pts)
( c.set 7; inc2 c; c.get unit);
Ans:
9: Nat
b) Please consider following C++ program
#include <iostream>
using namespace std;
class AA{
public:
int mya;
float myb;
double myc;
AA(){
mya = 1;
myb = 1.0;
myc = 1.0;
cout<<" this is A's constructor! "<<endl;
} }
void
myprint();
void
myprint();
}; };
void
AA::myprint()
void
AA::myprint()
{ {
cout<<"
mya
:= "<<mya<<";
myb
:= "<<myb<<";
myc
:= "<<myc<<endl;
cout<<"
mya
:= "<<mya<<";
myb
:= "<<myb<<";
myc
:= "<<myc<<endl;
} }
class
BB:
public
AA{
class
BB:
public
AA{
public:
public:
BB()
BB()
{ {
mya
= 2;
mya
= 2;
myb
= 2.0;
myb = 2.0;
myc
= 2.0;
myc
= 2.0;
cout<<"
this
is B's
constructor!
"<<endl;
cout<<" this
is B's
constructor!
"<<endl;
} }
virtual
void
myprint();
virtual
void
myprint();
}; };
void
BB::myprint()
void
BB::myprint()
{ {
cout<<"
mya
:= "<<mya<<";
myb
:= "<<myb<<";
myc
:= "<<myc<<endl;
cout<<"
mya
:= "<<mya<<";
myb
:= "<<myb<<";
myc
:= "<<myc<<endl;
} }
!"#$%%%%
class
CC:
public
BB{
class
CC:
public
BB{
public:
public:
&'(#%(#%!)#%*+"#&,-*&+,.%%
CC()
CC()
{ {
%&'(#%(#%/)#%*+"#&,-*&+,.%%
mya
= 3;
mya
= 3;
myb
= 3.0;
&'(#%(#%0)#%*+"#&,-*&+,.%%
myb
= 3.0;
myc
= 3.0;
myc
= 3.0;
&'1%0%'2#%3(145%672%8%9%
cout<<"this
is C's
constructor!
"<<endl;
cout<<"this
is C's
constructor!
"<<endl;
} }
&'1%0%'2#%3(145%67:%8%9%
virtual
void
myprint();
virtual
void
myprint();
}; };
&'1%0%'2#%3(145%67*%8%9%
void
CC::myprint()
void
CC::myprint()
{ {
!
cout<<"
mya
:= "<<mya<<";
myb
:= "<<myb<<";
myc
:= "<<myc<<endl;
cout<<"
mya
:= "<<mya<<";
myb
:= "<<myb<<";
myc
:= "<<myc<<endl;
} }
What
is the
result
this
program
would
print
(5pts)
What
is the
result
this
program
would
print
? ?(5pts)
c) We still consider above C++ program, but make a little update. What if we
change the main() method as follows:
int main()
{
CC theC;
cout<<"the C has field mya = "<<((AA)theC).mya<<endl;
cout<<"the C has field myb = "<<((AA)theC).myb<<endl;
cout<<"the C has field myc = "<<((AA)theC).myc<<endl;
}
What is the result this program would print ? (5pts)
Ans:
this is A's constructor!
this is B's constructor!
this is C's constructor!
the C has field mya = 3
the C has field myb = 3
the C has field myc = 3
d) We still consider the C++ program, but make a little update further. What if we
change the main() method as follows:
int main()
{
AA* theC = new CC();
((AA*)theC)->myprint();
}
What is the result this program would print ? (5pts)
this is A's constructor!
this is B's constructor!
this is C's constructor!
mya := 3; myb := 3; myc := 3
Question 5 (10pts) : Following exception/concurrency question is based on
java programming language.
a) What will be printed based on the following program ? (3pts)
public class TC{ public static void main (String[]args) { int a = new TC().absorbeTheValue(); } int absorbeTheValue(){ try{ int a = 10/0; if (a > 0) return 4; } catch( ArithmeticException ae) { System.out.println("this is the first time exception"); try{ throw new Exception(); } catch(Exception e){ System.out.println("this is the second time catching exception"); throw new ArithmeticException(); } } finally{ try{ System.out.println("this is try-­‐catch inside finally"); } catch( Exception e ){} System.out.println("this is finally"); return 77; } } } Ans: this is the first time exception this is the second time catching exception this is try-­‐catch inside finally this is finally b) Please draw stack trace of following java program(calling f() from a main function): (3pts) public class Retry { static int i = 0; public void f() { try { g(); } !"#$%&'(&#)*'+#(,'-.#,*'-&#/0#0/%%/+123#4'5'#6*/3*'78##
catch(Exception e) { System.out.println("Caught exception, i = " + i); 69!%1-#-%'((#:&,*;#<!
e.printStackTrace(); ####(,',1-#12,#1#=#>?!
i++; ####69!%1-#5/1)#0@"#<!
f(); ########,*;#<#3@"?#A!
} ########-',-B@CD-&6,1/2#&"#<!
} ############E;(,&7F/9,F6*12,%2@GH'93B,#&D-&6,1/2I#1#=#G#J#1"?!
void g() throws Exception { ############1JJ?!
if (i < 1) { throw new Exception(); } ############0@"?!
else ########A!
System.out.println("g() is working now"); ####A!
} ####5/1)#3@"#,B*/+(#3CD-&6,1/2#<!
public static void main(String[] args) ########10#@1#K#L"#<#,B*/+#2&+#3CD-&6,1/2@"?#A!
{ ########&%(&!
Retry myRetry = new Retry(); ############E;(,&7F/9,F6*12,%2@G3@"#1(#+/*.123#2/+G"?!
myRetry.f(); ####A# } } !"##$%&"'()$*+&,$-.'/0123$
main() called
f() called
main()
f()
main()
g() called
search f() for
handler, exit f()
g()
f()
main()
exception thrown,
g() has no handler,
exit g()
f()
main()
main()
search main() for
handler, call
printStackTrace(),
exit main()
!"#$%#&'(')##*+,%#'%#-./,!0#12#3-!4,5)#'6,#'33#7,0+-52#%-0#(1210,5#.8#-0+,6#-./,!092#7,0+-5:#
;-*#'.-<0#5'0'#=1,352#1%#0+,#-./,!0:##>+'0#12##*'10?"#7,0+-5#=-6#0+,#3-!4,5#-./,!0:##>+'0#12#
c) In Java, when an object is locked, are all methods not visited by other object’s %-01=8?"#7,0+-5#=-6#0+,#3-!4,5#-./,!0:#>+'0#12#%-01=8@33?"#7,0+-5##=-6#0+,#3-!4,5#-./,!0:##
method? How about data fields in the object? What is wait() method for the locked >+'0#12#/-1%?"#7,0+-5#=-6#0+,#3-!4,5#-./,!0:###
object? What is notify() method for the locked object? What is notifyAll() method for # the locked object? What is join() method for the locked object? (4pts) @%2A##
B-)#-%38#0+,#-%,2#*10+#28%!+6-%1C,5#4,8*-65#!'%#%-0#.,#(1210,5#.8#-0+,6#
-./,!029#7,0+-5D###@33#5'0'#=1,352#!'%#.,#(1210,5D##
#
>'10?"#E'<2,2#!<66,%0#0+6,'5#<%013#'%-0+,6#0+6,'5#!'332#B-01=8#F##
B-01=8?"#*'4,2#0+,#+1G+,20HE61-6108#0+6,'5#!3-2,20#0-#0+,#=6-%0#-=#0+,#-./,!092#
1%0,6%'3#I<,<,F##
%-01=8@33?"#*'4,2#<E#'33#*'101%G#0+6,'52#2-#0+'0A#J#
'"#K+6,'52#%-%H5,0,671%1201!'338#!-7E,0,#=-6#'!!,22#0-#-./,!0#
."##L'8#%-0#.,#='16#?3-*HE61-6108#0+6,'52#7'8#%,(,6#G,0#'!!,22"#
K+,#/-1%#7,0+-5#'33-*2#-%,#0+6,'5#0-#*'10#=-6#0+,#!-7E3,01-%#-=#'%-0+,6D#$=#0#12#
'#K+6,'5#-./,!0#*+-2,#0+6,'5#12#!<66,%038#,M,!<01%G)#
0D/-1%?"F##
!'<2,2#0+,#!<66,%0#0+6,'5#0-#E'<2,#,M,!<01-%#<%013#0N2#0+6,'5#0,671%'0,2D#
O(,63-'52#-=#/-1%#'33-*#0+,#E6-G6'77,6#0-#2E,!1=8#'#*'101%G#E,61-5D#;-*,(,6)#
'2#*10+#23,,E)#/-1%#12#5,E,%5,%0#-%#0+,#OP#=-6#0171%G)#2-#8-<#2+-<35#%-0#'22<7,#
0+'0#/-1%#*133#*'10#,M'!038#'2#3-%G#'2#8-<#2E,!1=8D#
Download