questions-post-midterm
pdf
keyboard_arrow_up
School
University of Waterloo *
*We aren’t endorsed by this school
Course
351
Subject
Computer Science
Date
Jan 9, 2024
Type
Pages
104
Uploaded by MajorPony3902
D E R E K + S T U D E N T S + S TA F F
E C E 3 5 1 Q U E S T I O N S
U N I V E R S I T Y O F W AT E R L O O
2
derek
+
students
+
staff
Copyright ©
2023
Derek + Students + Staff
Compiled November
12
,
2023
acknowledgements
:
•
ta
Reza Babaee collected many of these questions from past midterms
etc.
• Jon Eyolfson [
ta s2012
; Lab Instructor
w2013
&
s2013
]
• Students of
w2012
: David Choi, Michael Lin, Aman Muthrej, Atulan Zaman
• Student Parul Arora from
w2018
.
• Student Alex V. from
w2019
submitted several patches.
• Student Andrew Xia from
w2019
created the Optimization and Register Allocation sections and wrote
questions found therein.
Licensed under Creative Commons Attribution-ShareAlike (CC BY-SA) version
2
.
5
or greater.
http://creativecommons.org/licenses/by-sa/2.5/ca/
http://creativecommons.org/licenses/by-sa/3.0/
Contents
0
Introduction
5
0
.
1
Bonus points for contributing!
5
0
.
2
Soundness
5
0
.
3
(In)Completeness
5
0
.
4
Syllabus Questions
6
0
.
5
Self-Assessment Questions
9
I
Pre-Midterm
11
1
Grammar Derivations
13
1
.
1
Some Regular Languages
13
1
.
2
CFG for Simple Arithmetic Expressions, with Nesting
15
2
Simple Program Understanding
17
2
.
1
Some Simple List Examples
17
2
.
2
Four Variants of Linear Search
19
2
.
3
Introducing Polymorphism
25
3
Recursive Descent Parsing
27
3
.
1
Illustrative Examples
27
3
.
2
More Realistic Questions
30
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
4
derek
+
students
+
staff
4
Finite Automata & Regular Languages
31
4
.
1
Automata Execution
31
4
.
2
Design a Regular Language
33
4
.
3
Draw an NFA
35
4
.
4
NFA to DFA
35
4
.
5
DFA Minimization
36
4
.
6
Flavours of Non-Determinism
37
4
.
7
Really Difficult Automata Design Question
39
4
.
8
Unanswered Automata Design
40
4
.
9
Automata Design related to
W
41
5
Grammar Analysis & Design
43
5
.
1
Grammar Refactoring
43
5
.
2
LL(
1
) Analysis
46
5
.
3
Refactoring & LL(
1
) Proof Together
50
5
.
4
Precedence
51
5
.
5
Ambiguity
52
6
Grammar Stories
53
6
.
1
Mary, Mary, Quite Contrary
53
6
.
2
As You Like It
54
6
.
2
.
1
Rosalind’s Glorious Grammar
54
6
.
2
.
2
Celia’s Splendid Syntax
55
6
.
2
.
3
Epilogue
56
II
Post-Midterm
57
7
Advanced Program Understanding
59
7
.
1
Iteration Order
59
7
.
2
Object Identity
60
ece351 study questions
5
7
.
3
Visitor
61
7
.
3
.
1
Method for Answering These Questions
61
7
.
3
.
2
The Birds & The Bees
61
7
.
3
.
3
Computer Part Example
63
7
.
3
.
4
Simplified Lab Code
64
8
Optimization
67
8
.
1
Optimization by Intuition
67
8
.
2
Available Expressions Dataflow Analysis on Straight-line Code
69
8
.
3
Available Expressions Analysis on Code With Loops and Branches
71
9
Register Allocation
75
9
.
1
Register Allocation
75
10
Generational Garbage Collection
79
10
.
1
Question: x x and y or not
79
10
.
2
Assumptions
79
10
.
3
Code Listing
80
10
.
3
.
1
Object Diagrams
81
10
.
4
Question: z not not not
84
10
.
5
Question: p not p not and not
86
10
.
5
.
1
Thinking
86
10
.
5
.
2
Solution
86
11
Mark+Sweep Garbage Collection [NEW S
2019
]
87
11
.
1 1
Not
88
11
.
2
x Not Not
89
11
.
3
x
1
And y Or
92
6
derek
+
students
+
staff
III
Other Stuff
93
12
Short-Answer Questions
95
12
.
1
Computational Complexity
95
12
.
2
Automata
99
12
.
3
Grammars
100
A
Epilogue
101
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
0
Introduction
This document contains
ece351
questions from past midterms and
exams, as well as study questions created by students and
ta
s.
0
.
1
Bonus points for contributing!
You can get bonus points in the course for contributing new study
questions. The best way to submit new material is to fork this repo,
add the new material on your fork, and then make a merge request.
The addresses for this repo are:
•
https://git.uwaterloo.ca/ece351-notes/ece351-tex/
•
ist-git@git.uwaterloo.ca:ece351-notes/ece351-tex.git
The next best way to submit material is by Piazza post — remember
to use the
patch
tag.
0
.
2
Soundness
Every question in this set is relevant and worth knowing the answer
to. This document might contain unintentional errors or typos.
0
.
3
(In)Completeness
These questions might not cover every topic in the course. Pay atten-
tion to what happens in class!
8
derek
+
students
+
staff
0
.
4
Syllabus Questions
Exercise
0
.
4
.
1
All courses are UW are required to have an Outline/Syllabus. [T/F]
Solution
0
.
4
.
1
T
Exercise
0
.
4
.
2
The Outline specifies the marking scheme and deadlines. [T/F]
Solution
0
.
4
.
2
T
Exercise
0
.
4
.
3
When does the Outline need to be finalized by?
Solution
0
.
4
.
3
The end of the first week of class.
Exercise
0
.
4
.
4
Students can have some input on the Outline before it is finalized. [T/F]
Solution
0
.
4
.
4
T
Exercise
0
.
4
.
5
The dagger/cross annotated sections in the Lab Manual indicate sections:
a. that tell you what steps to take for that lab
b. that you can ignore
c. that describe concepts required to understand the lab, which might be tested on the exam
Solution
0
.
4
.
5
C
Exercise
0
.
4
.
6
Good debugging techniques include:
a. forming a hypothesis
b. using the debugger
c. having a nap and coming back later with a fresh mind
d. all of the above
Solution
0
.
4
.
6
D
Exercise
0
.
4
.
7
The labs in this course are cumulative. [T/F]
Solution
0
.
4
.
7
T
Exercise
0
.
4
.
8
List labs that have code that is used by future labs.
Solution
0
.
4
.
8
1
,
3
,
4
,
6
Exercise
0
.
4
.
9
List labs that have code that is
not
used by future labs.
Solution
0
.
4
.
9
2
,
5
,
7
,
8
,
9
ece351 study questions
9
Exercise
0
.
4
.
10
If you are going to skip a lab, it is better to skip a lab where the code is
not
re-used by
future labs. [T/F]
Solution
0
.
4
.
10
T
Exercise
0
.
4
.
11
Announcements for this course will be made by:
a. carrier pigeon
b. bulletin board in hallway
c. email
d. Piazza
Solution
0
.
4
.
11
D
Exercise
0
.
4
.
12
The Lab Manual, Course Notes, Outline, slides,
etc.
, will be distributed by:
a. floppy disk
b. shared network drive
c. email
d. hard copy
e. Git
Solution
0
.
4
.
12
E
Exercise
0
.
4
.
13
The Lab Manual, Course Notes, Outline, slides,
etc.
, will be updated throughout the term.
a. Nope, they are set in stone on the first day.
b. Yep, everything changes all the time.
c. The Outline is fixed at the end of the first week. The other documents will receive minor improvements
throughout the term.
Solution
0
.
4
.
13
C
Exercise
0
.
4
.
14
The weekly lab deadline used to be Sunday at
11
:
59pm
.
Why are we no longer using that deadline?
a. Religious reasons.
b. Students would not attend the lab sessions all week. They wouldn’t start the lab until Saturday. Then
they would complain that the course staff were not available to help them.
Solution
0
.
4
.
14
B
Exercise
0
.
4
.
15
The weekly lab deadline used to be Thursday at
11
:
59pm
.
Why are we proposing to change that deadline?
a. Legal reasons.
b. Students were complaining too much.
c. Students would not attend the lab sessions all week. They wouldn’t start the lab until Thursday
6pm
.
Then they would complain that the course staff were not available to help them.
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
10
derek
+
students
+
staff
Solution
0
.
4
.
15
B
Exercise
0
.
4
.
16
Git hiccups are easy to resolve via email/Piazza posts.
a. Yep, email solves everything!
b. No. If you are having a hiccup with Git that also means that you probably lack the technical skills to
accurately describe the problem, so nobody will be able to help you fix it based on your description of
the situation. You need to have someone look at your computer. Come to the scheduled lab times.
Solution
0
.
4
.
16
B
Exercise
0
.
4
.
17
Why do we start each class with a poem?
a. It’s fun.
b. The rhythym naturally calls the class to attention.
c. It prepares the mind to listen.
d. All of the above.
Solution
0
.
4
.
17
D
ece351 study questions
11
0
.
5
Self-Assessment Questions
Exercise
0
.
5
.
1
Do you read Piazza announcements?
a. Yes, I read everything on Piazza.
b. Yes, I have my filters set to highlight instructor announcements.
c. No, I don’t mind if my grades suffer because I’m not paying attention.
d. No, I don’t have the technical skills to configure my filters.
e. No, I do not use electronic media.
f. No, I’m just lazy.
Solution
0
.
5
.
1
A or B
Exercise
0
.
5
.
2
Self-assess your skills in the following matrix:
Exams
Strong
b1
a
Weak
c
b2
Weak
Strong
Programming
a
: You should have no problem in this course.
b1
: You might feel unnecessarily stressed about the labs, but you will get a decent grade in the end be-
cause of the exams and written assignments.
b2
: You will find the labs engaging but easy, and so will choose to push deeper into the material. You will
help your classmates (and be rewarded with bonus participation points for doing so). The danger is that
you feel overconfident throughout the term and then decide to not study for the exam —
please
do not
make that mistake. It’s a downer to have a give a low grade to a good programmer.
c
: You will find this course challenging. Help is available. Make use of it. Go to the scheduled lab times.
Find a peer mentor in class. Good time management skills will help you get the best possible result.
Solution
0
.
5
.
2
Work to improve your areas of weakness.
Exercise
0
.
5
.
3
Self-assess your skills in the following matrix:
Git
Strong
b1
a
Weak
c
b2
Weak
Strong
Time Management
a
: You should have no problem in this course.
b1
: You will have the technical skills to compensate for your poor time management. Force yourself to
improve your time management skills anyway.
b2
: You will start labs early and attend scheduled lab times, so you will have no trouble finding help
when you need it. You might experience a Git hiccup, but it won’t bother you much.
c
: You will panic because you will experience a Git hiccup that you cannot resolve at a time when nobody
is available to help you. Focus on improving your technical skills and your time management skills to
get yourself out of this quadrant.
Solution
0
.
5
.
3
Work to improve your areas of weakness.
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
Part I
Pre-Midterm
1
Grammar Derivations
1
.
1
Some Regular Languages
Exercise
1
.
1
.
1
Engineers need to be able to work in both major mea-
surement systems. Using the grammar below, derive the input strings
metric 3.875
and
imperial 3 7/8
.
Measurement
→
‘
metric
’
DecimalNumber
|
‘
imperial
’
FractionalNumber
DecimalNumber
→
Digits
‘
.
’
Digits
FractionalNumber
→
Digits Digits
‘
/
’
Digits
Digits
→
[
0
-
9
]
+
Solution
1
.
1
.
1
One derivation for each input:
Measurement
→
‘
metric
’
DecimalNumber
→
‘
metric
’
Digits
‘
.
’
Digits
→
‘
metric
’ ‘
3
’ ‘
.
’ ‘
875
’
Now the imperial input:
Measurement
→
‘
imperial
’
FractionalNumber
→
‘
imperial
’
Digits Digits
‘
/
’
Digits
→
‘
imperial
’ ‘
3
’ ‘
7
’ ‘
/
’ ‘
8
’
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
16
derek
+
students
+
staff
Exercise
1
.
1
.
2
A brief overview of some professions and what they
do. Try to derive the following sentences:
• Engineer calculates design
• Physician examines patient
• Judge decides case
• Engineer cuts patient
• Lawyer advocates design
ProfessionalSkills
→
Technical
|
Medical
|
Legal
Technical
→
(‘
Engineer
’ ‘
calculates
’
|
‘
Architect
’ ‘
draws
’) ‘
design
’
Medical
→
(‘
Physician
’ ‘
examines
’
|
‘
Surgeon
’ ‘
cuts
’) ‘
patient
’
Legal
→
(‘
Lawyer
’ ‘
advocates
’
|
‘
Judge
’ ‘
decides
’) ‘
case
’
Solution
1
.
1
.
2
Five derivations, one for each input:
Engineer calculates design
ProfessionalSkills
→
Technical
→
‘
Engineer
’ ‘
calculates
’ ‘
design
’
Physician examines patient
ProfessionalSkills
→
Medical
→
‘
Physician
’ ‘
examines
’ ‘
patient
’
Judge decides case
ProfessionalSkills
→
Legal
→
‘
Judge
’ ‘
decides
’ ‘
case
’
Engineer cuts patient
ProfessionalSkills
→
Technical
→
‘
Engineer
’ STUCK/REJECT
Lawyer advocates design
ProfessionalSkills
→
Legal
→
‘
Lawyer
’ ‘
advocates
’ STUCK/REJECT
ece351 study questions
17
1
.
2
CFG for Simple Arithmetic Expressions, with Nesting
Exercise
1
.
2
.
1
A simple arithmetic calculator language, with operator
precedence and nested expressions. Some input strings:
•
1
+
2
•
2
*
3
•
1
+
2
*
3
• (
1
+
2
) *
3
•
1
*
2
+
3
S
→
Expr
Expr
→
Term
‘
+
’
Expr
|
Term
Term
→
Factor
‘
*
’
Term
|
Factor
Factor
→
Int
|
‘
(
’
Expr
‘
)
’
Solution
1
.
2
.
1
A derivation for each input string. Use square brack-
ets to show how the grammar encodes operator precedence, if nec-
essary. These derivations attempt to show every step. In practice,
on exams, when just moving down the grammar to get to Ints, you
could skip some steps.
1
+
2
S
→
Expr
→
Term
‘
+
’
Expr
→
Factor
‘
+
’
Term
→
Int
‘
+
’
Factor
→
Int
‘
+
’
Int
→
‘
1
’ ‘
+
’ ‘
2
’
2
*
3
S
→
Expr
→
Term
→
Factor
‘
*
’
Expr
→
Int
‘
*
’
Term
→
2
‘
*
’
Factor
→
2
‘
*
’
Int
→
2
‘
*
’
3
1
+
2
*
3
S
→
Expr
→
Term
‘
+
’
Expr
→
Factor
‘
+
’ [
Term
]
→
Int
‘
+
’ [
Factor
‘
*
’
Term
]
→
1
‘
+
’ [
Int
‘
*
’
Term
]
→
1
‘
+
’ [
2
‘
*
’
Factor
]
→
1
‘
+
’ [
2
‘
*
’
Int
]
→
1
‘
+
’ [
2
‘
*
’
3
]
(
1
+
2
) *
3
S
→
Expr
→
Term
→
Factor
‘
*
’
Term
→
[‘
(
’
Expr
‘
)
’] ‘
*
’
Factor
→
[‘
(
’
Term
‘
+
’
Expr
‘
)
’] ‘
*
’
Int
→
[‘
(
’
Factor
‘
+
’
Term
‘
)
’] ‘
*
’
3
→
[‘
(
’
Int
‘
+
’
Factor
‘
)
’] ‘
*
’
3
→
[‘
(
’
1
‘
+
’
Int
‘
)
’] ‘
*
’
3
→
[‘
(
’
1
‘
+
’
2
‘
)
’] ‘
*
’
3
1
*
2
+
3
S
→
Expr
→
Term
‘
+
’
Expr
→
[
Factor
‘
*
’
Expr
] ‘
+
’
Expr
→
[
Int
‘
*
’
Term
] ‘
+
’
Term
→
[
1
‘
*
’
Factor
] ‘
+
’
Factor
→
[
1
‘
*
’
Int
] ‘
+
’
Int
→
[
1
‘
*
’
2
] ‘
+
’
3
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
2
Simple Program Understanding
2
.
1
Some Simple List Examples
Exercise
2
.
1
.
1
1
import
java.util.List;
2
import
java.util.LinkedList;
3
4
public class
MutableListExample {
5
public static void
main(String[] args) {
6
List list =
new
LinkedList();
7
List alias = list;
8
list.add("hello");
9
alias.add("world");
10
System.out.println(list);
// ???
11
}
12
}
Solution
2
.
1
.
1
PC: 10
main()
list
alias
Output:
[hello, world]
LinkedList1
Node1
Node2
String1:
hello
String2:
world
Figure
2
.
1
: Mutation and aliasing with
jdk
LinkedList
20
derek
+
students
+
staff
Exercise
2
.
1
.
2
1
import
org.parboiled.common.ImmutableList;
2
3
public class
ImmutableListBogusExample {
4
public static void
main(String[] args) {
5
ImmutableList list = ImmutableList.of();
6
ImmutableList alias = list;
7
list.append("hello");
8
alias.append("world");
9
System.out.println(list);
// ???
10
list = list.append("hello");
11
alias = alias.append("world");
12
System.out.println(list);
// ???
13
}
14
}
1
import
org.parboiled.common.ImmutableList;
2
3
public class
ImmutableListGoodExample {
4
public static void
main(String[] args) {
5
ImmutableList list = ImmutableList.of();
6
list = list.append("hello");
7
list = list.append("world");
8
System.out.println(list);
// ???
9
}
10
}
Solution
2
.
1
.
2
PC: 9
main()
list
alias
Output:
[]
ImmutableList1
ImmutableList2
ImmutableList3
String1:
hello
String2:
world
PC: 12
main()
list
alias
Output:
[hello]
ImmutableList1
ImmutableList2
ImmutableList3
ImmutableList4
ImmutableList5
String1:
hello
String2:
world
PC: 8
main()
list
Output:
[hello, world]
ImmutableList1
ImmutableList2
ImmutableList3
String1:
hello
String2:
world
Figure
2
.
2
: Mutation and aliasing with
Parboiled ImmutableList
ece351 study questions
21
2
.
2
Four Variants of Linear Search
Figure
2
.
4
lists four different implementations of linear search. The
input, output, and algorithm are the same for all:
•
Input:
a list of strings, where the first one is the token to search for
in the rest of the list.
•
Output:
–
Normal: prints “found it!” or “didn’t find it”
–
Errors: if the list is not provided
•
Algorithm:
linear search
–
Runtime:
O(n)
–
Space consumption:
O(n)
–
Termination: either the token is found or the end of the list is
reached.
So what’s differs between these four programs?
•
Static Structure:
–
Data Structures: arrays
vs.
linked lists
•
Dynamic Execution:
–
Control Structures / Call Graph: iteration
vs.
recursion
E
xercise
: draw an object diagram of the state of each program
when it finds a match given the input ‘Moe Larry Curly Moe’. So-
lutions given on subsequent pages in Figures
2
.
5
,
2
.
6
,
2
.
7
,
2
.
8
.
1
/
**
An immutable Node structure used for linked
2
*
lists in two of the Linear Search variants.
*
/
3
class
Node {
4
final
Node next;
5
final
String data;
6
Node(Node next, String data) {
7
this
.next = next;
8
this
.data = data;
9
}
10
}
Figure
2
.
3
: Node class used by some
variants of Linear Search
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
22
derek
+
students
+
staff
1
public class
LinearSearch_Array_Iterative {
2
public static void
main(String[] args) {
3
String toFind = args[0];
4
for
(
int
i = 1; i < args.length; i++) {
5
if
(toFind.equals(args[i])) {
6
System.out.println("found it!");
7
System.exit(0);
8
}
9
}
10
System.out.println("didn’t find it");
11
System.exit(1);
12
}
13
}
1
public class
LinearSearch_Array_Recursive {
2
public static void
main(String[] args) {
3
String toFind = args[0];
4
search(toFind, args, 1);
5
System.out.println("didn’t find it");
6
System.exit(1);
7
}
8
static void
search(String toFind, String[] a,
int
i) {
9
if
(toFind.equals(a[i])) {
10
System.out.println("found it!");
11
System.exit(0);
12
}
else
{
13
if
(i < a.length-1) search(toFind, a, i+1);
14
}
15
}
16
}
1
public class
LinearSearch_Objects_Iterative {
2
public static void
main(String[] args) {
3
String toFind = args[0];
4
// copy array to linked list
5
Node head =
null
;
6
for
(
int
i = args.length-1; i > 0; i--) {
7
head =
new
Node(head, args[i]);
8
}
9
// now search
10
Node n = head;
11
while
(n !=
null
) {
12
if
(toFind.equals(n.data)) {
13
System.out.println("found it!");
14
System.exit(0);
15
}
else
{
16
n = n.next;
17
}
18
}
19
// search is over: unsuccessfull
20
System.out.println("didn’t find it");
21
System.exit(1);
22
}
23
}
1
public class
LinearSearch_Objects_Recursive {
2
public static void
main(String[] args) {
3
String toFind = args[0];
4
// copy array to linked list
5
Node head =
null
;
6
for
(
int
i = args.length-1; i > 0; i--) {
7
head =
new
Node(head, args[i]);
8
}
9
// now search
10
search(toFind, head);
11
// search is over: unsuccessfull
12
System.out.println("didn’t find it");
13
System.exit(1);
14
}
15
static void
search(String toFind, Node n) {
16
if
(n ==
null
) {
return
; }
17
else
{
18
if
(toFind.equals(n.data)) {
19
System.out.println("found it!");
20
System.exit(0);
21
}
else
{
22
search(toFind, n.next);
23
}
24
}
25
}
26
}
Figure
2
.
4
: Four different implementa-
tions of linear search.
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
ece351 study questions
23
L
inear
S
earch
: A
rray
+I
terative
V
ariant
• Recall that the input string, provided on the command line for this
execution, is ‘Moe Larry Curly Moe’.
Exercise
2
.
2
.
1
1
public class
LinearSearch_Array_Iterative {
2
public static void
main(String[] args) {
3
String toFind = args[0];
4
for
(
int
i = 1; i < args.length; i++) {
5
if
(toFind.equals(args[i])) {
6
System.out.println("found it!");
7
System.exit(0);
8
}
9
}
10
System.out.println("didn’t find it");
11
System.exit(1);
12
}
13
}
Solution
2
.
2
.
1
PC: 6
main()
args
toFind
i = 3
array1
Moe
0
3
Larry
1
Curly
2
Figure
2
.
5
: Object diagram for iterative
array variant of linear search when it
finds ‘Moe’ in ‘Larry Curly Moe’.
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
24
derek
+
students
+
staff
L
inear
S
earch
: A
rray
+R
ecursive
V
ariant
• Recall that the input string, provided on the command line for this
execution, is ‘Moe Larry Curly Moe’.
• Here we see three stack frames corresponding to the
search()
method, one of which originates from
main()
, and the other two
of which are recursive calls where
search()
calls itself.
Exercise
2
.
2
.
2
1
public class
LinearSearch_Array_Recursive {
2
public static void
main(String[] args) {
3
String toFind = args[0];
4
search(toFind, args, 1);
5
System.out.println("didn’t find it");
6
System.exit(1);
7
}
8
static void
search(String toFind, String[] a,
int
i) {
9
if
(toFind.equals(a[i])) {
10
System.out.println("found it!");
11
System.exit(0);
12
}
else
{
13
if
(i < a.length-1) search(toFind, a, i+1);
14
}
15
}
16
}
Solution
2
.
2
.
2
PC: 10
main()
args
toFind
search()
toFind
a
i = 1
array1
Moe
search()
toFind
a
i = 2
search()
toFind
a
i = 3
0
3
Larry
1
Curly
2
Figure
2
.
6
: Object diagram for recursive
array variant of linear search when it
finds ‘Moe’ in ‘Larry Curly Moe’.
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
ece351 study questions
25
L
inear
S
earch
: O
bjects
+I
terative
V
ariant
• Recall that the input string, provided on the command line for this
execution, is ‘Moe Larry Curly Moe’.
• The linked list of Nodes needs to be constructed from the back
because it is immutable and its
next
pointer points forwards: there-
fore, we cannot construct a
Node
until we have already constructed
the other
Node
that comes after it in the list.
• The source code for
Node
is above in Figure
2
.
3
.
Exercise
2
.
2
.
3
1
public class
LinearSearch_Objects_Iterative {
2
public static void
main(String[] args) {
3
String toFind = args[0];
4
// copy array to linked list
5
Node head =
null
;
6
for
(
int
i = args.length-1; i > 0; i--) {
7
head =
new
Node(head, args[i]);
8
}
9
// now search
10
Node n = head;
11
while
(n !=
null
) {
12
if
(toFind.equals(n.data)) {
13
System.out.println("found it!");
14
System.exit(0);
15
}
else
{
16
n = n.next;
17
}
18
}
19
// search is over: unsuccessfull
20
System.out.println("didn’t find it");
21
System.exit(1);
22
}
23
}
Solution
2
.
2
.
3
PC: 13
main()
args
toFind
head
i
n
array1
Moe
Node1
Node3
0
3
Larry
1
Curly
2
Node2
Figure
2
.
7
: Object diagram for iterative
linked-list variant of linear search when
it finds ‘Moe’ in ‘Larry Curly Moe’.
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
26
derek
+
students
+
staff
L
inear
S
earch
: O
bjects
+R
ecursive
V
ariant
• Recall that the input string, provided on the command line for this
execution, is ‘Moe Larry Curly Moe’.
• Here we see three stack frames corresponding to the
search()
method, one of which originates from
main()
, and the other two
of which are recursive calls where
search()
calls itself.
• The linked list of Nodes needs to be constructed from the back
because it is immutable and its
next
pointer points forwards: there-
fore, we cannot construct a
Node
until we have already constructed
the other
Node
that comes after it in the list.
• The source code for
Node
is above in Figure
2
.
3
.
Exercise
2
.
2
.
4
1
public class
LinearSearch_Objects_Recursive {
2
public static void
main(String[] args) {
3
String toFind = args[0];
4
// copy array to linked list
5
Node head =
null
;
6
for
(
int
i = args.length-1; i > 0; i--) {
7
head =
new
Node(head, args[i]);
8
}
9
// now search
10
search(toFind, head);
11
// search is over: unsuccessfull
12
System.out.println("didn’t find it");
13
System.exit(1);
14
}
15
static void
search(String toFind, Node n) {
16
if
(n ==
null
) {
return
; }
17
else
{
18
if
(toFind.equals(n.data)) {
19
System.out.println("found it!");
20
System.exit(0);
21
}
else
{
22
search(toFind, n.next);
23
}
24
}
25
}
26
}
Solution
2
.
2
.
4
PC: 19
main()
args
toFind
head
i = 0
search()
toFind
n
array1
Moe
Node3
search()
toFind
n
search()
toFind
n
Node2
Node1
0
3
Larry
1
Curly
2
Figure
2
.
8
: Object diagram for recursive
linked-list variant of linear search when
it finds ‘Moe’ in ‘Larry Curly Moe’.
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
ece351 study questions
27
2
.
3
Introducing Polymorphism
Exercise
2
.
3
.
1
Consider the following code listing, which is a simpli-
fied version of the
ast
code in the labs for language
F
. Demonstrate
your understanding of this code by drawing a class diagram, an ob-
ject diagram for time point (PC=
29
and i=
2
), and by describing the
input, output, and polymorphic method call targets.
Solution
2
.
3
.
1
•
Input:
none
•
Output:
and
null and null
or
null or null
and
null and null
•
Polymorphic Call Targets Line
28
:
i
target
0
AndExpr.operator()
1
OrExpr.operator()
2
AndExpr.operator()
Class Diagram:
Expr
BinaryExpr
AndExpr
OrExpr
PC: 29
main()
args
b
a
i = 2
e
array1
AndExpr1
AndExpr2
0
2
OrExpr1
1
1
abstract class
Expr {
2
abstract
String operator();
3
}
4
abstract class
BinaryExpr
extends
Expr {
5
final
Expr left;
6
final
Expr right;
7
abstract
BinaryExpr newBinaryExpr(Expr l, Expr r);
8
public
String toString() {
return
left + operator() + right; }
9
}
10
final class
AndExpr
extends
BinaryExpr {
11
String operator() {
return
" and "; }
12
BinaryExpr newBinaryExpr(Expr l, Expr r) {
return new
AndExpr(l,r); }
13
}
14
final class
OrExpr
extends
BinaryExpr {
15
String operator() {
return
" or "; }
16
BinaryExpr newBinaryExpr(Expr l, Expr r) {
return new
OrExpr(l,r); }
17
}
18
final class
Main {
19
public static void
main(String[] args) {
20
BinaryExpr b =
new
AndExpr();
// why isn’t the type of e AndExpr?
21
Expr[] a =
new
Expr[3];
// an empty array of size 3
22
// what is the type of the object stored in each element of the array?
23
a[0] = b;
24
a[1] =
new
OrExpr();
25
a[2] = b.newBinaryExpr(
null
,
null
);
// monomorphic call site
26
for
(
int
i = 0; i < a.length; i++) {
27
Expr e = a[i];
28
System.out.println(e.operator());
// polymorphic call site
29
System.out.println(e.toString());
// mono or polymorphic?
30
}
31
}
32
}
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
3
Recursive Descent Parsing
We originally learned this technique
in
lab1
, and then practiced it again in
lab3
.
Recursive descent parsing
is a programming technique for writing
a parser by hand, given a grammar. A grammar is a
mathematical
specification
for a language. We can also consider it as a mathemat-
ical specification for a parser. Using the recursive descent parsing
technique, we can systematically derive the code for the parser (rec-
ognizer) from the grammar using the following rules:
These kinds of questions might ask you
to write a
recognizer
,
parser
, or
evaluator
:
recognizer:
string
→
boolean
parser:
string
→
ast
evaluator:
string
→
value
A recognizer might appear to return
void, following the convention in the
labs, where the lexer will throw an
exception if asked to consume a token
that isn’t there:
i.e.
, exception is reject,
and regular completion is accept.
Grammar Feature
7→
Code
non-terminal
7→
method
terminal
7→
Lexer.consume()
repetition (*, +)
7→
loop
alternation (
|
)
7→
if
For these kinds of questions, the answers are just pseudo-code. What
we are looking for is that you understand the technique — we aren’t
picky about syntactically perfect code. You can assume a lexer like
the one we have used in the labs.
3
.
1
Illustrative Examples
Exercise
3
.
1
.
1
A list of names:
List
→
Name
*
Name
→
ID
Solution
3
.
1
.
1
void
List() {
// a method for the non-terminal List
while
(!lexer.inspectEOF()) {
// a loop for the
*
Name();
// the rule for List uses Name, so we get a call here
}
lexer.consumeEOF();
}
void
Name() {
// a method for the non-terminal Name
lexer.consumeID();
}
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
30
derek
+
students
+
staff
Exercise
3
.
1
.
2
Engineers need to be able to work in both major mea-
surement systems:
Measurement
→
‘
metric
’
DecimalNumber
|
‘
imperial
’
FractionalNumber
DecimalNumber
→
Digits
‘
.
’
Digits
FractionalNumber
→
Digits Digits
‘
/
’
Digits
Digits
→
[
0
-
9
]
+
Solution
3
.
1
.
2
void
Measurement() {
// a method for the non-terminal
if
(lexer.inspect("metric")) {
// if for the | (bar)
lexer.consume("metric");
DecimalNumber();
}
else if
(lexer.inspect("imperial")) {
// or, in fancy talk: conditional for the alternation
lexer.consume("imperial");
FractionalNumber();
}
else
{
// reject: unknown case
throw new
RuntimeException(("measurement system unrecognized: " + lexer.next());
}
lexer.consumeEOF();
}
void
DecimalNumber() {
// a method for the non-terminal
lexer.consumeDigits();
lexer.consume(".");
lexer.consumeDigits();
}
void
FactionalNumber() {
// a method for the non-terminal
lexer.consumeDigits();
lexer.consumeDigits();
lexer.consume("/");
lexer.consumeDigits();
}
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
ece351 study questions
31
Exercise
3
.
1
.
3
Who does what:
Sentences in this language include:
Engineer calculates design
Physician examines patient
Judge decides case
ProfessionalSkills
→
Technical
|
Medical
|
Legal
Technical
→
(‘
Engineer
’ ‘
calculates
’
|
‘
Architect
’ ‘
draws
’) ‘
design
’
Medical
→
(‘
Physician
’ ‘
examines
’
|
‘
Surgeon
’ ‘
cuts
’) ‘
patient
’
Legal
→
(‘
Lawyer
’ ‘
advocates
’
|
‘
Judge
’ ‘
decides
’) ‘
case
’
Solution
3
.
1
.
3
void
ProfessionalSkills() {
// a method for the non-terminal
if
(lexer.inspect("Engineer") || lexer.inspect("Architect")) { Technical(); }
else if
(lexer.inspect("Physician") || lexer.inspect("Surgeon")) { Medical(); }
else if
(lexer.inspect("Lawyer") || lexer.inspect("Judge")) { Legal(); }
else
{ thrown
new
RuntimeException("unknown profession: " lexer.next()); }
lexer.consumeEOF();
}
void
Technical() {
// a method for the non-terminal
if
(lexer.inspect("Engineer")) {
lexer.consume("Engineer");
lexer.consume("caclulates");
}
else if
(lexer.inspect("Architect")) {
lexer.consume("Architect");
lexer.consume("draws");
}
lexer.consume("design");
}
void
Medical() {
// a method for the non-terminal
if
(lexer.inspect("Physician")) {
lexer.consume("Physician");
lexer.consume("examines");
}
else if
(lexer.inspect("Surgeon")) {
lexer.consume("Surgeon");
lexer.consume("cuts");
}
lexer.consume("patient");
}
void
Legal() {
// a method for the non-terminal
if
(lexer.inspect("Lawyer")) {
lexer.consume("Lawyer");
lexer.consume("advocates");
}
else if
(lexer.inspect("Judge")) {
lexer.consume("Judge");
lexer.consume("decides");
}
lexer.consume("case");
}
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
32
derek
+
students
+
staff
3
.
2
More Realistic Questions
Exercise
3
.
2
.
1
An
ll
(
1
) arithmetic calculator grammar with binary
operators, operator precedence, and expression nesting:
The grammar in the question is a left-
factored variant of this grammar:
S
→
Expr
Expr
→
Term
‘
+
’
Expr
|
Term
Term
→
Factor
‘
*
’
Expr
|
Factor
Factor
→
Int
|
‘
(
’
Expr
‘
)
’
S
→
Expr
Expr
→
Term TermTail
TermTail
→
‘
+
’
Expr
|
e
Term
→
Factor FactorTail
FactorTail
→
‘
*
’
Expr
|
e
Factor
→
Int
|
‘
(
’
Expr
‘
)
’
Solution
3
.
2
.
1
Recognizer:
void
S() { Expr(); }
void
Expr() { Term(); TermTail(); }
void
Term() { Factor(); FactorTail(); }
void
Factor() {
if
(lexer.inspect("(")) {
lexer.consume("(");
Expr();
lexer.consume(")");
}
else
{
lexer.consumeInt();
}
}
void
TermTail() {
if
(lexer.inspect("+")) {
lexer.consume("+");
Expr();
}
}
void
FactorTail() {
if
(lexer.inspect("
*
")) {
lexer.consume("
*
");
Expr();
}
}
Evaluator:
int
S() {
return
Expr(); }
int
Expr() {
return
Term() + TermTail(); }
int
Term() {
return
Factor()
*
FactorTail(); }
int
Factor() {
if
(lexer.inspect("(")) {
lexer.consume("(");
int
e = Expr();
lexer.consume(")");
return
e;
}
else
{
return
lexer.consumeInt();
}
}
int
TermTail() {
if
(lexer.inspect("+")) {
lexer.consume("+");
return
Expr();
}
else
{
return
0; }
// epslion: use identity element for addition
}
int
FactorTail() {
if
(lexer.inspect("
*
")) {
lexer.consume("
*
");
return
Expr();
}
else
{
return
1; }
// epsilon: use identity element for multiplication
}
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
4
Finite Automata & Regular Languages
4
.
1
Automata Execution
Execution abc:
in
states
a
1
→
2
b
2
→
1
c
1
→
2
out
accept
Execution ab:
in
states
a
1
→
2
b
2
→
1
out
reject
Execution acb:
in
states
a
1
→
2
c
2
→
X
b
X
→
X
out
reject
input tape
machine
states
storage
output tape
a
b
c
1
2
accept
b
a,c
Execution ac:
in
states
a
1
→
2
–
2
→
1
c
1
→
2
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
34
derek
+
students
+
staff
input tape
machine
states
storage
output tape
a
c
1
2
accept
epsilon
a,c
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
ece351 study questions
35
4
.
2
Design a Regular Language
Exercise
4
.
2
.
1
Consider a language where real numbers are defined
as follows: a real constant contains a decimal point or E notation, or
both. For example,
0
.
01
,
2
.
7834345
,
∼
1
.
2
E
12
, and
7
E
∼
5
,
35
. are real
constants. The symbol "
∼
" denotes unary minus and may appear
before the number or on the exponent. There is no
unary "+" opera-
tion. There must be at least one digit to the left of the decimal point,
but there might be no digits to the right of the decimal point. The
exponent following the "E" is a (possibly negative) integer. Write a
regular expression (RE) for such real constants. You may use any of
the EBNF extended notation.
Solution
4
.
2
.
1
Constraints on real constant:
• contains a decimal point, E notation
, or both
• unary minus may appear before the number or an exponent
• no unary plus
• at least one digit to the left of decimal point
• zero or more digits
to the right of the decimal point
• exponent following ‘E’ is an integer
Therefore, a regular expression that matches this definition is as
follows:
∼
?
[
0
-
9
]
+
(
(
.
[
0
-
9
]
*
(
E
∼
?
[
0
-
9
]
+
)
?
)
|
(
E
∼
?
[
0
-
9
]
+
)
)
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
36
derek
+
students
+
staff
Exercise
4
.
2
.
2
In a certain (fictional) programming language, assign-
ment statements are described as:
• An assignment statement may have an optional label at the start of
the statement.
• The assignment statement itself consists of an identifier, followed
by the assignment operator, followed by an arithmetic expression
and ending with the statement termination operator.
• A label consists of one or more letters (no digits), followed by a
colon (:).
• An identifier starts with a letter which may be followed by any
number of letters or digits.
• The assignment operator is the equal sign (=).
• Arithmetic expressions consist of one or more identifiers, sepa-
rated by arithmetic operators.
• The arithmetic operators are:
+
,
-
,
×
,
÷
.
• The statement termination operator is the semicolon (;).
Write a regular expression to recognize assignment statements for
this language.
Solution
4
.
2
.
2
L
=
a
|
b
|
c
|
...
|
z
D
=
0
|
1
|
2
|
3
|
4
|
5
|
6
|
7
|
8
|
9
(
LL
*
:
|
e
)
L
(
L
|
D
)
*
=
L
(
L
|
D
)
*
((+
| - | × |÷
)
L
(
L
|
D
)
*
)
*
;
Exercise
4
.
2
.
3
Write a regular expression that describes floating point
numbers. These examples should be accepted by your solution:
1
.
2
,
0
.
004
, .
5
,
0
, -
76
.
45
, -.
12
,
87
, +
2
.
2
, +.
3
Solution
4
.
2
.
3
(-|+)?[0-9]
*
\.?[0-9]
*
Note: do not require the backslash
before the period in student solutions
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
ece351 study questions
37
4
.
3
Draw an NFA
Exercise
4
.
3
.
1
Draw NFA for the following notations used in ex-
tended regular expressions:
a.
R
? that matches zero or one copy of R
b.
R
+
that matches one or more copies of R
Solution
4
.
3
.
1
Source: Question
4
at
from-students/omortaza
_
problem
_
set.pdf
Exercise
4
.
3
.
2
Draw an NFA for (a|b)
*
a(a|b)
3
Solution
4
.
3
.
2
Source: Question
4
at
from-students/sj2choi-dfa-nfa.
pdf
Exercise
4
.
3
.
3
Construct (draw) a Non-deterministic Finite Automa-
ton (NFA) to recognize the regular expression:
(((
a
|
b
)
bb
*
)
*
|
aa
*
)((
a
|
b
)
ab
)
*
Solution
4
.
3
.
3
Source: Question
2
.b at
ece251/ECE251MS00P.pdf
4
.
4
NFA to DFA
Exercise
4
.
4
.
1
Consider the following NFA, whose final state is
state
8
. Convert the NFA into a DFA, and draw the resulting DFA.
Indicate which state(s) of the DFA are final states. Dotted edges are
epsilon (
e
) edges.
1
2
5
3
a
6
a
b
4
b
7
b
8
a
b
Solution
4
.
4
.
1
X: 1, 2, 3, 5
Y: 3, 6, 8
a
Z: 4, 5, 2, 3
b
W: 2, 4, 5, 3, 7
b
a
b
a
b
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
38
derek
+
students
+
staff
4
.
5
DFA Minimization
Exercise
4
.
5
.
1
Minimize the number of states in the following DFA.
Draw the resulting optimized DFA. All states of the initial DFA are
final states. Dotted edges are epsilon (
e
) edges.
1
2
b
4
a
3
a
5
b
b
a
6
a,b
a,b
Solution
4
.
5
.
1
W: 5, 6
a,b
X: 1, 3
Y: 4
a
Z: 2
b
b
a
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
ece351 study questions
39
4
.
6
Flavours of Non-Determinism
Consider the following NFA that starts at state
1
and accepts at state
3
(but gets stuck at state
2
):
zero
1
2
x
3
x
Exercise
4
.
6
.
1
If we assume angelic non-determinism, and the ma-
chine receives input string ‘x’, which state will it transition to?
Solution
4
.
6
.
1
3
Exercise
4
.
6
.
2
If we assume demonic non-determinism, and the ma-
chine receives input string ‘x’, which state will it transition to?
Solution
4
.
6
.
2
2
Exercise
4
.
6
.
3
If we assume arbitrary non-determinism, and the
machine receives input string ‘x’, which state will it transition to?
Solution
4
.
6
.
3
either
2
or
3
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
40
derek
+
students
+
staff
Exercise
4
.
6
.
4
HTML is the standard language for describing web
pages. Can a regular expression for recognizing HTML be written?
Why or why not? Here is an example fragment of HTML:
<
html
>
<
head
><
title
>Web Page Title</
title
></
head
>
<
body
>
It’s a web page!
</
body
>
</
html
>
Solution
4
.
6
.
4
No, HTML is not
a regular language because it has
nested tags.
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
ece351 study questions
41
4
.
7
Really Difficult Automata Design Question
Exercise
4
.
7
.
1
Consider the usual string representation of binary in-
tegers. The most significant bit is on the left, and the least significant
bit is on the right. For example, ‘
10
’ is
2
, and ‘
100
’ is
4
. Leading zeros
are permitted,
e.g.
‘
0010
’ is also
2
. Write a regular expression that
accepts all binary integers that are divisible by
5
.
The general technique for writing
a
dfa
to check if a binary number
is divisible by
n
is available online,
e.g.
:
http://stackoverflow.
com/questions/21897554/
design-dfa-accepting-binary-strings-divisible-by-a
Solution
4
.
7
.
1
This question is too hard. It should have been phrased to write a
dfa
,
instead of a regex. If you know the technique it is not hard to make the
dfa
.
Set states to be the remainders. Define the transition function
δ
(
s
,
α
)
to be
δ
(
s
, 0
) = (
2
s
)
%5
and
δ
(
s
, 1
) = (
2
s
+
1
)
%5
. Solid lines are
1
-transitions
and dotted lines are
0
-transitions.
0
1
2
3
4
Different people have come up with different regexs that are equivalent to
this
dfa
. Converting a
dfa
to a regex is not hard in principle, but this one
is large in practice.
http://cs.stackexchange.com/questions/2016/how-to-convert-finite-automata-to-regular-expressions
Here is the short one:
[
0
+
1
(
11
+
0
) (
01
*
01
)*
1
]*
Here is the full derivation of the long one:
Q
0
=
0
Q
0
∪
1
Q
1
(
4
.
1
)
Q
1
=
0
Q
2
∪
1
Q
3
(
4
.
2
)
Q
2
=
0
Q
4
∪
1
Q
0
(
4
.
3
)
Q
3
=
0
Q
1
∪
1
Q
2
(
4
.
4
)
Q
4
=
1
Q
4
∪
0
Q
3
(
4
.
5
)
First simplify
4
.
5
,
Q
4
=
1
*
∪
0
Q
3
(
4
.
6
)
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
42
derek
+
students
+
staff
Apply
4
.
4
and
4
.
6
to
4
.
3
Q
2
=
0
Q
4
∪
1
Q
0
=
01
*
∪
00
Q
3
∪
1
Q
0
=
01
*
∪
000
Q
1
∪
001
Q
2
∪
1
Q
0
=
01
*
∪
(
001
)
*
∪
000
Q
1
∪
1
Q
0
(
4
.
7
)
Apply
4
.
7
and
4
.
4
to
4
.
2
Q
1
=
0
Q
2
∪
1
Q
3
=
0
Q
2
∪
10
Q
1
∪
11
Q
2
=
(
10
)
*
∪
(
0
∪
11
)
Q
2
=
(
10
)
*
∪
(
0
∪
11
)[
01
*
∪
(
001
)
*
∪
000
Q
1
∪
1
Q
0
]
=
(
10
)
*
∪
(
0
∪
11
)[
01
*
∪
(
001
)
*
∪
1
Q
0
]
∪
(
0
∪
11
)
000
Q
1
=
(
10
)
*
∪
[(
0
∪
11
)
000
]
*
∪
(
0
∪
11
)[
01
*
∪
(
001
)
*
∪
1
Q
0
]
(
4
.
8
)
Apply
4
.
8
to
4
.
1
Q
0
=
0
Q
0
∪
1
Q
1
=
0
*
∪
1
(
10
)
*
∪
1
[(
0
∪
11
)
000
]
*
∪
1
(
0
∪
11
)[
01
*
∪
(
001
)
*
∪
1
Q
0
]
=
0
*
∪
1
(
10
)
*
∪
1
[(
0
∪
11
)
000
]
*
∪
1
(
0
∪
11
)[
01
*
∪
(
001
)
*
]
∪
1
(
0
∪
11
)
1
Q
0
=
[
1
(
0
∪
11
)
1
]
*
∪
0
*
∪
1
(
10
)
*
∪
1
[(
0
∪
11
)
000
]
*
∪
1
(
0
∪
11
)[
01
*
∪
(
001
)
*
]
4
.
8
Unanswered Automata Design
Produce NFAs that recognize the following regular expressions.
Convert the NFAs to DFAs and minimize them.
Exercise
4
.
8
.
1
xy
*
(
z
|
cw
)
ab
?
Solution
4
.
8
.
1
TBD
Exercise
4
.
8
.
2
(
rmb
|
c
)
?
(
ns f
)
*
Solution
4
.
8
.
2
TBD
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
ece351 study questions
43
4
.
9
Automata Design related to
W
Recall the
W
language for Boolean waveforms from the labs. Imagine
that we extend this language for a three-valued logic: true, false,
and unknown. Here is a regular expression for this new language.
Complete each construction and transformation.
(U|F|T)
*
Exercise
4
.
9
.
1
Regex
→
NFA
Solution
4
.
9
.
1
Dotted, unlabelled edges are epsilon edges.
1
8
2
3
4
5
U
6
F
7
T
Exercise
4
.
9
.
2
NFA
→
DFA
Solution
4
.
9
.
2
A: 1,
2, 3,
4, 8
B: 5,
8, 1, 2,
3, 4
U
C: 6,
8, 1, 2,
3, 4
F
D: 7,
8, 1, 2,
3, 4
T
U
F
T
U
F
T
U
F
T
Exercise
4
.
9
.
3
DFA
→
minimized DFA
Solution
4
.
9
.
3
ABCD
U
F
T
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
5
Grammar Analysis & Design
5
.
1
Grammar Refactoring
C
onsider the following grammar
.
S
→
E
E
→
E - E
|
INT
Exercise
5
.
1
.
1
Show that this grammar is ambiguous.
Solution
5
.
1
.
1
Input string ‘
3
-
2
-
1
’ parses as either ‘(
3
-
2
)-
1
’ or ‘
3
-(
2
-
1
)’.
Exercise
5
.
1
.
2
Refactor the grammar to remove the ambiguity (and to
produce arithmetically correct results with the AST is evaluated).
Solution
5
.
1
.
2
S
→
E
E
→
E - INT
|
INT
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
46
derek
+
students
+
staff
Exercise
5
.
1
.
3
This is from an old
ece251
midterm.
We did not study
ll
(
1
) parsing tables
in
ece351
. It’s just a tabular representa-
tion of the predict sets.
The following grammar is not suitable for a top-down predictive
parser. Fix the problems by rewriting the grammar (with any
required
changes) and then construct the
ll
(
1
) parsing table for your new
grammar.
L
→
R
‘
a
’
L
→
Q
‘
ba
’
R
→
‘
aba
’
R
→
‘
caba
’
R
→
R
‘
bc
’
Q
→
‘
bbc
’
Q
→
‘
bc
’
Solution
5
.
1
.
3
There are a few issues with this grammar that we should resolve:
•
Left recursion
of the production
R
→
R
bc
• Unpredictability of
Q
given one look ahead token because of com-
mon prefix
Left Recursion:
R
→
‘
aba
’
R
→
‘
caba
’
R
→
R
‘
bc
’
Introduce additional non-terminal
R
0
:
R’
→
‘
bc
’
R’
|
e
and rewrite the productions for
R
:
R
→
‘
aba
’
R’
R
→
‘
caba
’
R’
Common Prefix:
Q
→
‘
bbc
’
Q
→
‘
bc
’
We can left factor
Q
to remove the common prefix
b
by introduc-
ing the non-terminal
Q
tail
:
Q
→
‘
b
’
Q
tail
Q
tail
→
‘
bc
’
|
‘
c
’
Our final grammar is:
L
→
R
‘
a
’
L
→
Q
‘
ba
’
R
→
‘
aba
’
R’
R
→
‘
caba
’
R’
R’
→
‘
bc
’
R’
R’
→
e
Q
→
‘
b
’
Q
tail
Q
tail
→
‘
bc
’
Q
tail
→
‘
c
’
Exercise
5
.
1
.
4
Refactor the following grammar to
ll
(
1
) form.
S
→
id ‘
(
’
A
‘
)
’
|
id ‘
[
’
A
‘
]
’
A
→
A
‘
,
’ id
|
id
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
ece351 study questions
47
Solution
5
.
1
.
4
S
→
id
T
T
→
‘
(
’
A
‘
)
’
|
‘
[
’
A
‘
]
’
A
→
id
U
U
→
‘
,
’ id
U
|
e
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
48
derek
+
students
+
staff
5
.
2
LL(
1
) Analysis
Exercise
5
.
2
.
1
Also from an old
ece251
midterm.
Consider the grammar given below, with S as the start symbol,
and
a
,
b
,
c
,
d
,
f
and
g
as terminals.
S
→
XYZ
$$
X
→
‘
a
’
|
Z
‘
b
’
|
e
Y
→
‘
c
’
|
‘
d
’
XY
|
e
Z
→
‘
f
’
|
‘
g
’
Compute the FIRST and FOLLOW sets for each non-terminal in
the grammar.
Solution
5
.
2
.
1
Recall that EPS, FIRST, FOLLOW, and PREDICT sets are defined
as follows:
EPS
(
α
)
≡
if
α
=
⇒
*
e
then
true
else
false
FIRST
(
α
)
≡ {
c
:
α
=
⇒
*
c
β
}
FOLLOW
(
A
)
≡ {
c
:
S
=
⇒
+
α
A
c
β
}
PREDICT
(
A
→
α
)
≡
FIRST
(
α
)
∪
(
if EPS
(
α
)
then FOLLOW
(
A
)
else
∅
)
Non-terminal
Equation
Solution
Comment
eps
(
S
)
=
0
=
0
contains a terminal ($$)
eps
(
X
)
=
1
=
1
derives
e
directly
eps
(
Y
)
=
1
=
1
derives
e
directly
eps
(
Z
)
=
0
=
0
derives terminals
Non-terminal
Equation
Solution
Comment
first
(
S
)
=
first
(
X
)
∪
first
(
Y
)
∪
first
(
Z
)
=
{
‘
a
0
, ‘
c
0
, ‘
d
0
, ‘
f
0
, ‘
g
0
}
X
and
Y
are nullable
first
(
X
)
=
{
‘
a
0
} ∪
first
(
Z
)
=
{
‘
a
0
, ‘
f
0
, ‘
g
0
}
two non-
e
options
first
(
Y
)
=
{
‘
c
0
, ‘
d
0
}
=
{
‘
c
0
, ‘
d
0
}
two non-
e
options
first
(
Z
)
=
{
‘
f
0
, ‘
g
0
}
=
{
‘
f
0
, ‘
g
0
}
two non-
e
options
Non-terminal
Equation
Solution
Comment
follow
(
S
)
=
∅
=
∅
follow
(
X
)
=
first
(
Y
)
∪
follow
(
Y
)
=
{
‘
c
0
, ‘
d
0
, ‘
f
0
, ‘
g
0
}
S
→
XYZ
$$;
Y
→
‘
d
0
XY
(
Y
is nullable)
follow
(
Y
)
=
first
(
Z
)
=
{
‘
f
0
, ‘
g
0
}
S
→
XYZ
$$
follow
(
Z
)
=
{
‘
b
0
, $$
}
=
{
‘
b
0
, $$
}
S
→
XYZ
$$;
X
→
Z
‘
b
0
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
ece351 study questions
49
Exercise
5
.
2
.
2
Assume the grammar shown below, with
expr
as the start sym-
bol, and that terminal
id
can be any single letter of the alphabet (
a
through
z
).
expr
→
‘
id
’ “
:=
”
expr
expr
→
term term_tail
term_tail
→
“
+
”
term term_tail
|
e
term
→
factor factor_tail
factor_tail
→
“
*
”
factor factor_tail
|
e
factor
→
“
(
”
expr
“
)
”
|
‘
id
’
In two or three sentences, explain why the grammar cannot be
parsed by an LL(
1
) parser.
Solution
5
.
2
.
2
The
problem
originates from the non-terminal
expr
. The
productions
expr
→
‘
id
’ “
:=
”
expr
expr
→
term term_tail
actually have common prefixes
(The latter production for
expr
may derive ‘
id
’ as its first terminal:
expr
→
term
. . .
term
→
factor
. . .
factor
→
‘
id
’), so an LL(
1
) parser cannot predict the production to take
for the non-terminal
expr
.
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
50
derek
+
students
+
staff
I
s the following grammar ll
(
1
)? Prove your answer by com-
puting the
eps
,
first
,
follow
and
predict
sets. Provide both the
equations and their solutions, as we studied in class.
Note:
You may start from the predict sets and work backwards,
computing only the first and follow sets that you need.
S
→
(AB|Cx)$$
A
→
y
*
B
→
Cq
C
→
pC|
e
Exercise
5
.
2
.
3
Convert to
bnf
Solution
5
.
2
.
3
G
→
AB$$
G
→
Cx$$
A
→
yA
A
→
e
B
→
Cq
C
→
pC
C
→
e
Exercise
5
.
2
.
4
eps
Solution
5
.
2
.
4
Nonterminal
Result
Reason
eps
(G)
=
0
$$ is a terminal
eps
(A)
=
1
goes to
e
directly
eps
(B)
=
0
q is a terminal
eps
(C)
=
1
goes to
e
directly
Exercise
5
.
2
.
5
first
Solution
5
.
2
.
5
Nonterminal
Equation
Solution
first
(G)
=
first
(A)
∪
first
(B)
∪
first
(C)
∪
{x}
= {p,q,x,y}
first
(A)
= {y}
= {y}
first
(B)
=
first
(C)
∪
{q}
= {p,q}
first
(C)
= {p}
= {p}
Exercise
5
.
2
.
6
follow
Solution
5
.
2
.
6
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
ece351 study questions
51
Nonterminal
Equation
Solution
follow
(G)
=
∅
=
∅
follow
(A)
=
first
(B)
= {p,q}
follow
(B)
= {$$}
= {$$}
follow
(C)
= {q,x}
= {q,x}
Exercise
5
.
2
.
7
predict
Solution
5
.
2
.
7
Production
Equation
Solution
predict
(G
→
AB$$)
=
first
( AB$$
) =
first
(A)
∪
first
(B)
= {p,q,y}
predict
(G
→
Cx$$)
=
first
(Cx) =
first
(C)
∪
{x}
= {p,x}
predict
(A
→
yA)
= {y}
= {y}
predict
(A
→
e
)
=
follow
(A)
= {p,q}
predict
(B
→
Cq)
=
first
(Cq) =
first
(C)
∪
{q}
= {p,q}
predict
(C
→
pC)
= {p}
= {p}
predict
(C
→
e
)
=
follow
(C)
= {q,x}
Exercise
5
.
2
.
8
Is this grammar
ll
(
1
)? Why or why not?
Solution
5
.
2
.
8
No. We can predict
A
,
B
, and
C
with one token of
lookahead, but not
G
: the two
G
productions both have ‘p’ in their
predict sets. Consider the input strings ‘pq’ and ‘px’: we need to
lookahead two characters
to the ‘q’ or the ‘x’ to determine which
G
production to use.
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
52
derek
+
students
+
staff
5
.
3
Refactoring & LL(
1
) Proof Together
Referring to people by their middle
name is also common in families of
British ancestry. In many Hispanic
countries it is common to name boys
‘Jesus’. The English abbreviation for
‘William’ is ‘Wm’, as in ‘Wm Shake-
speare’.
I
n some countries
, such as Bangladesh, there is a practice to give
sons the formal first name Mohammed, but then always refer to
them by a middle name. In these cases, the formal first name might
be abbreviated as ‘Md’ to indicate that it is not for common use.
Suppose that we have the following grammar for boys names:
S
→
Md Anwar Sadat
S
→
Md Hosni Mubarak
S
→
Md Siad Barre
S
→
Md Zia-ul-Haq
S
→
Md Ayub Khan
S
→
Md Nawaz Sharif
Exercise
5
.
3
.
1
Is this grammar LL(
1
)? Why? Why not?
Solution
5
.
3
.
1
No, this grammar is not LL(
1
) because of common prefixes
.
If we are expecting to derive S and we look ahead one token and see
‘Md’ then we will not know which rule we are in.
Exercise
5
.
3
.
2
Refactor to an equivalent grammar that is LL(
1
).
Solution
5
.
3
.
2
S
→
Md Tail
Tail
→
Anwar Sadat
Tail
→
Hosni Mubarak
Tail
→
Siad Barre
Tail
→
Zia-ul-Haq
Tail
→
Ayub Khan
Tail
→
Nawaz Sharif
Exercise
5
.
3
.
3
Prove this grammar is LL(
1
). Start with the Predict
sets, and compute other sets as necessary. Construct equations sym-
bolically before providing concrete answers.
Solution
5
.
3
.
3
Predict(S
→
Md Tail) = {Md}
Predict(Tail
→
Anwar Sadat) = First(Anwar Sadat) = {Anwar}
Predict(Tail
→
Hosni Mubarak = First(Hosni Mubarak) = {Hosni}
Predict(Tail
→
Siad Barre) = First(Siad Barre) = {Siad}
Predict(Tail
→
Zia-ul-Haq) = First(Zia-ul-Haq) = {Zia-ul-Haq}
Predict(Tail
→
Ayub Khan) = First(Ayub Khan) = {Ayub}
Predict(Tail
→
Nawaz Sharif) = First(Nawaz Sharif) = {Nawaz}
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
ece351 study questions
53
5
.
4
Precedence
Exercise
5
.
4
.
1
Consider the expression represented by the following
expression tree. Assume that A, B, C, D and E are binary operators.
Consider the following infix expression:
3
C
4
B
1
A
2
D
6
B
7
E
5
.
Tree [.A [.B [.C
3 4
]
1
] [.D
2
[.E [.B
6 7
]
5
] ] ]
Assume this expression generates the tree shown. Given that all
operators have different precedences, and that the operators are non-
associative, list the operators A, B, C, D and E in order from highest
to lowest precedence. If there is more than one possible answer list
them all.
Solution
5
.
4
.
1
Precedence:
• C has higher precedence than B
•
B
has higher precedence than A
• B has higher precedence than E
•
E
has higher precedence than D
• D has higher precedence than A
Highest to lowest precedence:
C B E D A
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
54
derek
+
students
+
staff
5
.
5
Ambiguity
C
onsider the following ambiguous grammar
:
E
→
E
‘
+
’
E
|
E
‘
*
’
E
|
int
Exercise
5
.
5
.
1
Give an input string with two different legal parse
trees in this grammar. Show the parse trees.
Solution
5
.
5
.
1
1
+
2
*
3
could parse two ways (as could
1
+
2
+
3
):
(
1
+
2
) *
3
1
+ (
2
*
3
)
*
+
3
1
2
+
1
*
2
3
Exercise
5
.
5
.
2
Refactor this grammar to have the normal arithmetic
precedence and to be right associative. Show the parse tree for your
input string above.
Solution
5
.
5
.
2
This solution has the precedence correct, but is not right associative, and is
ambiguous.
E
→
E ’+’ E
E
→
F
F
→
F ’*’ F
F
→
int
1
+
2
*
3
7→
1
+ (
2
*
3
)
1
+
2
+
3
7→
1
+ (
2
+
3
)
or
7→
(
1
+
2
) +
3
This solution is correct on precedence and associativity. It is not
ll
(
1
)
, due
to common prefixes, but being
ll
(
1
)
is not required here.
E
→
F ’+’ E
E
→
F
F
→
int
’*’ F
F
→
int
1
+
2
*
3
7→
1
+ (
2
*
3
)
1
+
2
+
3
7→
1
+ (
2
+
3
)
This solution is correct on precedence and associativity, and is also
ll
(
1
)
.
S
→
E $$
E
→
F P
P
→
+ E
|
e
F
→
int
Q
Q
→
* F
|
e
1
+
2
*
3
7→
1
+ (
2
*
3
)
1
+
2
+
3
7→
1
+ (
2
+
3
)
predict
(
P
→
e
)
=
follow
(
P
)
=
follow
(
E
)
=
{$$}
disjoint from {+}
predict
(
Q
→
e
)
=
follow
(
Q
)
=
follow
(
F
)
=
first
(P)
∪
follow
(
P
)
=
{+, $$}
disjoint from {*}
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
6
Grammar Stories
6
.
1
Mary, Mary, Quite Contrary
In some places, at some points in time, it has been common to give
girls the first name Mary. Suppose that we have the following list of
women’s names. (This question is a student-created variant of the
‘Mohammed’ question in the Course Notes.)
S
→
Mary Elizabeth James
S
→
Mary Todd Lincoln
S
→
Mary Queen Scott
S
→
Mary Lynn Monroe
S
→
Mary Tyler Moore
Exercise
6
.
1
.
1
Is this grammar LL(
1
)? Why? Why not?
Solution
6
.
1
.
1
No, this grammar is not LL(
1
) because of common
prefixes. If we are expecting to derive S and we look ahead one token
and see ‘Mary’ then we will not know which rule we are in.
Exercise
6
.
1
.
2
Refactor to an equivalent grammar that is LL(
1
).
Solution
6
.
1
.
2
S
→
Mary Tail
Tail
→
Elizabeth James
Tail
→
Todd Lincoln
Tail
→
Queen Scott
Tail
→
Lynn Monroe
Tail
→
Tyler Moore
Exercise
6
.
1
.
3
Prove this grammar is LL(
1
). Start with the Predict
sets, and compute other sets as necessary. Construct equations sym-
bolically before providing concrete answers.
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
56
derek
+
students
+
staff
Solution
6
.
1
.
3
Production
Equation
Solution
predict
(S
→
Mary Tail)
=
first
(Mary Tail)
= {Mary}
predict
(Tail
→
Elizabeth James)
=
first
(Elizabeth James)
= {Elizabeth}
predict
(Tail
→
Todd Lincoln)
=
first
(Todd Lincoln)
= {Todd}
predict
(Tail
→
Queen Scott)
=
first
(Queen Scott)
= {Queen}
predict
(Tail
→
Lynn Monroe)
=
first
(Lynn Monroe)
= {Lynn}
predict
(Tail
→
Tyler Moore)
=
first
(Tyler Moore)
= {Tyler}
The Predict sets for each non-terminal are all disjoint, so therefore
this grammar is LL(
1
).
6
.
2
As You Like It
Rosalind and her cousin Celia cannot agree on how to evaluate the
expression ‘
1
+
2
*
3
’. Rosalind says it evaluates to
7
, while Celia insists
that the answer is
9
. Give the grammar that each heroine has in her
head, as well as a derivation showing how the given grammar eval-
uates the expression of interest. The grammar should also work for
larger expressions with these two operators, but does not need to
support nested expressions.
6
.
2
.
1
Rosalind’s Glorious Grammar
Rosalind escapes to the Forest of Arden, to enjoy her thoughts away
from the annoyance of Duke Frederick’s anger. Sheltered by a sup-
portive tree, she quickly jots in her notebook:
S
→
Sum
Sum
→
Sum + Product
Sum
→
Product
Product
→
Product * Int
Product
→
Int
She is pleased with the precedence in this, her first grammar of the
day: it will indeed bind multiplication tighter than addition. She
does a derivation to satisfy herself, and draws the parse tree:
+
*
1
2
3
S
→
Sum
→
Sum + Product
→
[Product] + [Product * Int]
→
[Int] + [Int *
3
]
→
[
1
] + [
2
*
3
]
But then she realizes that her grammar is not LL(
1
), and so while
it is elegant and correct, it will be difficult to implement. She sees
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
ece351 study questions
57
that this grammar is left-recursive, which cannot be LL(
1
). So she
left-factors it, as she learned in school:
S
→
Sum
Sum
→
Product STail
STail
→
+ Sum
|
e
Product
→
Int PTail
PTail
→
* Product
|
e
She does a derivation, and draws the parse tree, just to get a better
sense of what left-factoring does to her grammar. She writes the
epsilons (
e
) in her derivation, just for clarity, even though one would
not ordinarily do so.
+
*
1
2
3
S
→
Sum
→
Product STail
→
[Int PTail] [+ Sum]
→
[
1
e
] [+ [Product STail]]
→
[
1
] [+ [[Int PTail]
e
]]
→
[
1
] [+ [
2
[* Product]]]
→
[
1
] [+ [
2
[*
3
]]]
6
.
2
.
2
Celia’s Splendid Syntax
Celia is no stranger to higher thinking, and her beautiful penmanship
attracts the amorous attentions of Oliver. In a moment when Oliver
is distracted by giving his younger brother Orlando a hard time, she
scribes:
S
→
Product
Product
→
Sum * Product
Product
→
Sum
Sum
→
Int + Sum
Sum
→
Int
Meanwhile, a lioness attacks Oliver. Orlando, proving that blood is
thicker than water, comes to his brother’s rescue, despite Oliver’s
earlier heckling. While the boys are busy getting themselves in to and
out of trouble, Celia is happy to derive her thoughts:
+
1
2
*
3
S
→
Product
→
Sum * Product
→
[Int + Sum] * [Sum]
→
[
1
+ Int] * [Int]
→
[
1
+
2
] * [
3
]
Like her cousin (great minds think alike), Celia realizes that while her
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
58
derek
+
students
+
staff
grammar expresses her thoughts about arithmetic precedence to the
world, it is not LL(
1
) — but for a different reason: her syntax suffers
from common prefixes. Not one to be outdone, she deftly refactors:
S
→
Product
Product
→
Sum PTail
PTail
→
* Product
|
e
Sum
→
Int STail
STail
→
+ Sum
|
e
And then derives and draws:
+
*
1
2
3
S
→
Product
→
Sum PTail
→
[Int STail] [* Product]
→
[
1
[+ Sum]] [* [Sum PTail]]
→
[
1
[+ [Int STail]]] [* [[Int STail]
e
]]
→
[
1
[+ [
2
e
]]] [* [[Int STail]
e
]]
→
[
1
[+
2
]] [* [[
3
e
]
e
]]
→
[
1
[+
2
]] [*
3
]
6
.
2
.
3
Epilogue
In the end, Frederick repents his wicked ways, restoring peace to
the duchy. Our heroines decide that, while they fancy Orlando and
Oliver respectively, for now they are wedded to their ideas. The
brothers eagerly enroll in
ece351
in hopes of wooing their sweet-
hearts.
https://en.wikipedia.org/wiki/As
_
You
_
Like
_
It
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
Part II
Post-Midterm
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
7
Advanced Program Understanding
7
.
1
Iteration Order
Exercise
7
.
1
.
1
list.add(3);
list.add(1);
list.add(2);
System.out.println(list);
Solution
7
.
1
.
1
List preserves insertion order:
3
,
1
,
2
Exercise
7
.
1
.
2
tset.add(3);
tset.add(1);
tset.add(2);
System.out.println(tset);
Solution
7
.
1
.
2
TreeSet uses the natural ordering:
1
,
2
,
3
Exercise
7
.
1
.
3
hset.add(3);
hset.add(1);
hset.add(2);
System.out.println(hset);
Solution
7
.
1
.
3
HashSet has
arbitrary
iteration order (non-deterministic).
There are six possible legal outputs.
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
62
derek
+
students
+
staff
7
.
2
Object Identity
Exercise
7
.
2
.
1
hset.add(new VarExpr("Y"));
hset.add(new VarExpr("X"));
hset.add(new VarExpr("X"));
System.out.println(hset);
Solution
7
.
2
.
1
HashSet uses equals() to determine if objects are du-
plicates. Output:
X, Y or Y, X
Exercise
7
.
2
.
2
lhset.add(new VarExpr("Y"));
lhset.add(new VarExpr("X"));
lhset.add(new VarExpr("X"));
System.out.println(lhset);
Solution
7
.
2
.
2
LinkedHashSet also uses equals() to determine if
objects are duplicates, but preserves insertion order. Output:
Y, X
Exercise
7
.
2
.
3
iset.add(new VarExpr("Y"));
iset.add(new VarExpr("X"));
iset.add(new VarExpr("X"));
System.out.println(iset);
Solution
7
.
2
.
3
IdentityHashSet uses object memory address to detect
duplicates. Output:
six possibilities, variations of Y, X, X
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
ece351 study questions
63
7
.
3
Visitor
7
.
3
.
1
Method for Answering These Questions
a. Identify the two class hierarchies:
•
Data: e.g.
, the
ast
classes
•
Operations: e.g.
, the visitors (that act on the Data)
b. Start your object diagram:
• Draw the heap as it looks in the
main
method.
• Draw the
statics
frame (if there is one).
• Draw the
main
stack frame.
• Connect the
main
frame and the
statics
frame to the heap objects.
c. Find the line of code where program execution will be paused at
for us to draw the object diagram. In
ece222
terms, where the
Program Counter
(
pc
) will be. This should be marked somehow —
perhaps with a comment that says
HERE
.
d. Look at the
main
method. Figure out which line in the main
method will eventually lead to the
pc
line. For this you will need
to think holistically: there should be enough clues around the
program for you to figure it out. This is the most challenging part.
e. Draw the next stack frame on your object diagram — what is
main
calling? Repeat until you get to the frame with the
pc
line.
7
.
3
.
2
The Birds & The Bees
Contributed by students in w
2018
.
Solution in PythonTutor.com at:
https://goo.gl/LdNUk5
Draw the object diagram when execution reaches this line:
System.out.println(toString() + " pollinated by " + pol.toString()); // HERE
This sample code has Visitor on a
simple, single object structure (a flower
object). So there is no traversal. When
we visit a complex recursive structure
like an AST, the Visitor also needs to
have some traversal strategy.
For this simple example, the heap
has almost no structure. With an AST,
we would see more structure in the
heap. But this simple example shows
us the stack nicely, and the stack+heap
connections. (With AST traversal code,
a fuller example might have more on
the stack.)
1
class
Flower{
2
public void
accept(Visitor v){
3
v.visit(
this
);
4
}
5
public void
pollinate(Pollinator pol){
6
System.out.println(toString() + " pollinated by " + pol.toString());
// HERE
7
}
8
public void
eat(Eater eater){
9
System.out.println(toString() + " eaten by " + eater.toString());
10
}
11
}
12
class
Tulip
extends
Flower{
13
@Override
14
public
String toString(){
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
64
derek
+
students
+
staff
15
return
"Tulip";
16
}
17
}
18
class
Sunflower
extends
Flower{
19
@Override
20
public
String toString(){
21
return
"Sunflower";
22
}
23
}
24
abstract class
Visitor {
25
public abstract void
visit(Flower f);
26
27
}
28
abstract class
Bug
extends
Visitor{}
29
abstract class
Pollinator
extends
Bug{}
30
abstract class
Eater
extends
Bug{}
31
class
Bee
extends
Pollinator{
32
@Override
33
public void
visit(Flower f){
34
f.pollinate(
this
);
35
}
36
@Override
37
public
String toString() {
38
return
"Bee";
39
}
40
}
41
class
Worm
extends
Eater{
42
@Override
43
public void
visit(Flower f){
44
f.eat(
this
);
45
}
46
@Override
47
public
String toString() {
48
return
"Worm";
49
}
50
}
51
public class
Simulate {
52
public static void
main(String[] args){
53
Tulip tulip =
new
Tulip();
54
Sunflower sunflower =
new
Sunflower();
55
56
Bee bee =
new
Bee();
57
Worm worm =
new
Worm();
58
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
ece351 study questions
65
59
tulip.accept(bee);
60
sunflower.accept(worm);
61
}
62
}
7
.
3
.
3
Computer Part Example
Contributed by students in w
2018
.
Adapted from
https://www.
tutorialspoint.com/design
_
pattern/
visitor
_
pattern.htm
Draw the object diagram when execution reaches this line:
System.out.println("Displaying Keyboard.");
Solution in PythonTutor.com at:
https://goo.gl/bHUL9m
1
interface
ComputerPart {
2
public void
accept(ComputerPartVisitor computerPartVisitor);
3
}
4
class
Keyboard
implements
ComputerPart {
5
@Override
6
public void
accept(ComputerPartVisitor computerPartVisitor) {
7
computerPartVisitor.visit(
this
);
8
}
9
}
10
class
Monitor
implements
ComputerPart {
11
@Override
12
public void
accept(ComputerPartVisitor computerPartVisitor) {
13
computerPartVisitor.visit(
this
);
14
}
15
}
16
class
Mouse
implements
ComputerPart {
17
@Override
18
public void
accept(ComputerPartVisitor computerPartVisitor) {
19
computerPartVisitor.visit(
this
);
20
}
21
}
22
class
Computer
implements
ComputerPart {
23
ComputerPart[] parts;
24
public
Computer(){
25
parts =
new
ComputerPart[] {
new
Mouse(),
new
Keyboard(),
new
Monitor()};
26
}
27
@Override
28
public void
accept(ComputerPartVisitor computerPartVisitor) {
29
for
(
int
i = 0; i < parts.length; i++) {
30
parts[i].accept(computerPartVisitor);
31
}
32
computerPartVisitor.visit(
this
);
33
}
34
}
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
66
derek
+
students
+
staff
35
interface
ComputerPartVisitor {
36
public void
visit(Computer computer);
37
public void
visit(Mouse mouse);
38
public void
visit(Keyboard keyboard);
39
public void
visit(Monitor monitor);
40
}
41
class
ComputerPartDisplayVisitor
implements
ComputerPartVisitor {
42
@Override
43
public void
visit(Computer computer) {
44
System.out.println("Displaying Computer.");
45
}
46
@Override
47
public void
visit(Mouse mouse) {
48
System.out.println("Displaying Mouse.");
49
}
50
@Override
51
public void
visit(Keyboard keyboard) {
52
System.out.println("Displaying Keyboard.");
// OBJECT DIAGRAM HERE
53
}
54
@Override
55
public void
visit(Monitor monitor) {
56
System.out.println("Displaying Monitor.");
57
}
58
}
59
public class
VisitorPatternDemo {
60
public static void
main(String[] args) {
61
ComputerPart computer =
new
Computer();
62
computer.accept(
new
ComputerPartDisplayVisitor());
63
}
64
}
7
.
3
.
4
Simplified Lab Code
Contributed by students in w
2018
.
Solution in PythonTutor.com at:
https://goo.gl/mZabP4
Draw the object diagram when execution reaches this line:
System.out.println("BinExpr visited");
1
class
Expr{}
2
class
VarExpr
extends
Expr{
3
String id;
4
public
VarExpr(String s){
5
this
.id = s;
6
}
7
public
Expr accept(Visitor v){
8
return
v.visitVar(
this
);
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
ece351 study questions
67
9
}
10
}
11
class
BinExpr
extends
Expr{
12
Expr l;
13
Expr r;
14
public
BinExpr(Expr l, Expr r){
15
this
.l = l;
16
this
.r = r;
17
}
18
public
Expr accept(Visitor v){
19
return
v.visitBin(
this
);
20
}
21
}
22
class
Visitor{
23
public
Expr traverseBinExpr(BinExpr b){
24
b.l = traverseExpr(b.l);
25
b.r = traverseExpr(b.r);
26
return
b.accept(
this
);
27
}
28
public
Expr traverseExpr(Expr e){
29
if
(e
instanceof
BinExpr)
return
traverseBinExpr((BinExpr)e);
30
else if
(e
instanceof
VarExpr)
return
((VarExpr)e).accept(
this
);
31
else return null
;
32
}
33
public
Expr visitVar(VarExpr v){
34
System.out.println("VarExpr visited");
35
return
v;
36
}
37
public
Expr visitBin(BinExpr b){
38
System.out.println("BinExpr visited");
// HERE
39
return
b;
40
}
41
}
42
public class
MainClass{
43
public static void
main(String[] args){
44
// can replace this AST with something more complex if necessary
45
Expr v1 =
new
VarExpr("a");
46
Expr v2 =
new
VarExpr("b");
47
Expr b1 =
new
BinExpr(v1,v2);
48
49
Visitor v =
new
Visitor();
50
v.traverseExpr(b1);
51
}
52
}
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
8
Optimization
8
.
1
Optimization by Intuition
For the following code snippets, perform Optimization by Intuition
by re-writing the statements in
3
Address Code
3
AC, perform com-
mon subexpression elimination, copy propagation, and dead code
elimination.
Exercise
8
.
1
.
1
a = (x + y) + (k + n);
b = (x + y) * (k + n);
Solution
8
.
1
.
1
Original
Three-Address Form
After CSE
After Copy Prop.
After Dead Code Elim.
a = (x + y) + (k + n);
b = (x + y)
*
(k + n);
t = x + y;
u = k + n;
a = t + u;
v = x + y;
w = k + n;
b = v
*
w;
t = x + y;
u = k + n;
a = t + u;
v = t;
w = u;
b = v
*
w;
t = x + y;
u = k + n;
a = t + u;
v = t;
w = u;
b = t
*
u;
t = x + y;
u = k + n;
a = t + u;
b = t
*
u;
Exercise
8
.
1
.
2
a = x + y * z;
b = z * x + y;
Solution
8
.
1
.
2
This was a trick question to see if you remembered
your operator precedence. This code snippet cannot be optimized.
Original
Three-Address Form
After CSE
After Copy Prop.
After Dead Code Elim.
a = x + y
*
z;
b = z
*
x + y;
t = y
*
z;
a = x + t;
u = z
*
x;
b = u + y;
t = y
*
z;
a = x + t;
u = z
*
x;
b = u + y;
t = y
*
z;
a = x + t;
u = z
*
x;
b = u + y;
t = y
*
z;
a = x + t;
u = z
*
x;
b = u + y;
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
70
derek
+
students
+
staff
Exercise
8
.
1
.
3
a = x + y * z + k - n;
b = x - y * z - n + k
Solution
8
.
1
.
3
You will need two rounds of common subexpression
elimination to fully optimize this code snippet.
Maybe this solution
doesn’t use the arithmetically correct order of operations when converting to
3
AC.
Original
Three-Address Form
After CSE
After Copy Prop.
After Dead Code Elim.
a = x + y
*
z + k - n;
b = x - y
*
z - n + k;
t = y
*
z;
u = k - n;
v = t + u;
a = x + v;
h = y
*
z;
i = -n + k;
j = h + i;
b = x - j;
t = y
*
z;
u = k - n;
v = t + u;
a = x + v;
h = t;
i = u;
j = h + i;
b = x - j;
t = y
*
z;
u = k - n;
v = t + u;
a = x + v;
h = t;
i = u;
j = t + u;
b = x - j;
t = y
*
z;
u = k - n;
v = t + u;
a = x + v;
j = t + u;
b = x - j;
After
2
nd CSE
After
2
nd Copy Prop.
After
2
nd Dead Code Elim.
t = y
*
z;
u = k - n;
v = t + u;
a = x + v;
j = v;
b = x - j;
t = y
*
z;
u = k - n;
v = t + u;
a = x + v;
j = v;
b = x - v;
t = y
*
z;
u = k - n;
v = t + u;
a = x + v;
b = x - v;
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
ece351 study questions
71
8
.
2
Available Expressions Dataflow Analysis on Straight-line Code
For the following straightline code snippets, perform available ex-
pressions dataflow analysis to determine if common subexpression
elimination can be performed. Recall that a dataflow analysis is de-
fined by a set of equation templates involving four sets:
•
In:
set of expressions available at beginning
•
Out:
set of expressions available at the end
•
Gen:
set of expressions computed (generated) in the block
•
Kill:
set of expressions killed by computations in the block
The equation templates for Available Expressions are:
In
s
=
\
∀
p
∈
predecessors(
s
)
Out
p
Out
s
=
Gen
s
∪
(
In
s
-
Kill
s
)
Exercise
8
.
2
.
1
1
. t = y * z;
2
. u = x + y;
3
. a = y * z;
4
. v = x + y;
5
. b = t * u;
Solution
8
.
2
.
1
In
1
=
∅
1
has no predecessors
Gen
1
=
{
y*z
}
the expression y*z is generated
Kill
1
=
{
t*u
}
expressions that depend on t
Out
1
=
Gen
1
∪
(
In
1
-
Kill
1
) =
{
y*z
}
the expression comes from the
Gen
set
In
2
=
Out
1
=
{
y*z
}
1
is the only predecessor of
2
Gen
2
=
{
x+y
}
the expression t+z
Kill
2
=
{
t*u
}
expressions that depend on u
Out
2
=
Gen
2
∪
(
In
2
-
Kill
2
) =
{
x+y, y*z
}
In
3
=
Out
2
=
{
x+y, y*z
}
2
is the only predecessor of
3
Gen
3
=
{
y*z
}
the expression y*z
Kill
3
=
∅
no expressions depend on a
Out
3
=
Gen
3
∪
(
In
3
-
Kill
3
) =
{
y*z, x+y
}
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
72
derek
+
students
+
staff
In
4
=
Out
3
=
{
y*z, x+y
}
3
is the only predecessor of
4
Gen
4
=
{
x+y
}
the expression x+y
Kill
4
=
∅
no expressions depend on v
Out
4
=
Gen
4
∪
(
In
4
-
Kill
4
) =
{
x+y, y*z
}
In
5
=
Out
4
=
{
x+y, y*z
}
4
is the only predecessor of
5
Gen
5
=
{
t*u
}
the expression t*u
Kill
5
=
∅
no expressions depend on b
Out
5
=
Gen
5
∪
(
In
5
-
Kill
5
) =
{
t*u, x+y, y*z
}
C
ommon
S
ubexpression
E
limination
We shall now examine each statement and see if the expression
it evaluations/generates is already available:
i.e.
, if
In
∩
Gen
is non-
empty.
In
1
∩
Gen
1
=
∅
∩ {
y*z;
}
=
∅
In
2
∩
Gen
2
=
{
y*z
} ∩ {
x+y
}
=
∅
In
3
∩
Gen
3
=
{
x+y, y*z
} ∩ {
y*z
}
=
{
y*z
}
In
4
∩
Gen
4
=
{
y*z, x+y
} ∩ {
x+y;
}
=
{
x+y
}
In
5
∩
Gen
5
=
{
x+y, a=y*z
} ∩ {
t*u
}
=
∅
We discover that there is no need to regenerate
a=y
*
z
in Statement
3
since
y
*
z
is already incoming to Statement
3
(it was generated in
Statement
1
). Hence, we can change Statement
3
to read
a=t
. There is
also no need to regenerate
v=x+y
in Statement
4
since
x+y
is already
generated in Statement
2
.
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
ece351 study questions
73
8
.
3
Available Expressions Analysis on Code With Loops and Branches
Exercise
8
.
3
.
1
For the following program with loops and branches,
perform available expression analysis to determine if common subex-
pression elimination can be performed. Solve for the
greatest fixed-
point
.
Solution
8
.
3
.
1
Similar to the course notes, we shall begin by con-
structing the
Gen
and
Kill
sets as these sets do not depend on the
ordering of the blocks (
i.e.
, do not depend on the control-flow of the
program).
Gen
1
=
{
B+2, C+D
}
Kill
1
=
{
C+D, A+C, A+D
}
Depends on C or A
Gen
2
=
{
C+D, A+C
}
Kill
2
=
{
B+2, E+D
}
Depends on E or B
Gen
3
=
{
D+1, C+D
}
Kill
3
=
{
B+2, E+D
}
Depends on E or B
Gen
4
=
∅
Kill
4
=
{
C+D, D+1, A+D, E+D
}
Depends on E or D
Gen
5
=
{
D+1, E+D
}
Kill
5
=
{
B+2, A+C, A+D
}
Depends on B or A
It may also be helpful to keep track of all the generated statements
when we solve using the greatest fixed point.
Gen
all
=
{
B+2, C+D, A+C, D+1, A+D, E+D
}
Based off the block diagram, we can also derive equations for the
In
sets.
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
74
derek
+
students
+
staff
In
1
=
∅
In
2
=
Out
1
∩
Out
5
In
3
=
Out
1
In
4
=
Out
2
In
5
=
Out
2
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
ece351 study questions
75
S
olving for greatest fixed
-
point
,
initializing with full
sets
.
Set
Initial
Step
1
Step
3
Step
5
Out
1
⇒ {
all
}
⇒
Gen
1
∪
(
In
0
1
-
Kill
1
)
⇒
Gen
1
∪
(
In
2
1
-
Kill
1
)
⇒
Gen
1
∪
(
In
4
1
-
Kill
1
)
=
{
B+2, C+D
}
=
{
B+2, C+D (same)
}
=
{
B+2, C+D (same)
}
Out
2
⇒ {
all
}
⇒
Gen
2
∪
(
In
0
2
-
Kill
2
)
⇒
Gen
2
∪
(
In
2
2
-
Kill
2
)
⇒
Gen
2
∪
(
In
4
2
-
Kill
2
)
=
{
C+D, A+C
} ∪ {
C+D, A+C, D+1, A+D
}
=
{
C+D, A+C
} ∪ {
C+D
}
In
4
2
=
In
2
2
=
{
C+D, A+C, D+1, A+D
}
=
{
C+D, A+C
}
=
same
Out
3
⇒ {
all
}
⇒
Gen
3
∪
(
In
0
3
-
Kill
3
)
⇒
Gen
3
∪
(
In
2
3
-
Kill
3
)
⇒
Gen
3
∪
(
In
4
3
-
Kill
3
)
=
{
D+1, C+D
} ∪ {
C+D, A+C, D+1, A+D
}
=
{
D+1, C+D
} ∪ {
C+D
}
In
4
3
=
In
2
3
=
{
D+1, C+D, A+C, A+D
}
=
{
D+1, C+D
}
=
same
Out
4
⇒ {
all
}
⇒
Gen
4
∪
(
In
0
4
-
Kill
4
)
⇒
Gen
4
∪
(
In
2
4
-
Kill
4
)
⇒
Gen
4
∪
(
In
4
4
-
Kill
4
)
=
∅
∪ {
B+2, A+C
}
=
∅
∪ {
A+C
}
=
∅
∪ {
A+C
}
=
{
B+2, A+C
}
=
{
A+C
}
=
same
Out
5
⇒ {
all
}
⇒
Gen
5
∪
(
In
0
5
-
Kill
5
)
⇒
Gen
5
∪
(
In
2
5
-
Kill
5
)
⇒
Gen
5
∪
(
In
4
5
-
Kill
5
)
=
{
D+1, E+D
} ∪ {
C+D, D+1, E+D
}
=
{
D+1, E+D
} ∪ {
C+D, D+1
}
=
{
D+1, E+D
} ∪ {
C+D
}
=
{
D+1, E+D, C+D
}
=
same
=
same
Set
Initial
Step
2
Step
4
Step
6
In
1
⇒
∅
⇒
same
⇒
same
⇒
same
In
2
⇒ {
all
}
⇒
Out
1
1
∩
Out
1
5
⇒
Out
3
1
∩
Out
3
5
⇒
Out
5
1
∩
Out
5
5
=
{
B+2, C+D
} ∩ {
D+1, E+D, C+D
}
=
{
B+2, C+D
} ∩ {
D+1, E+D, C+D
}
=
Out
3
1
∩
Out
3
5
=
{
C+D
}
=
same
=
same
In
3
⇒ {
all
}
⇒
Out
1
1
⇒
Out
3
1
⇒
Out
5
1
=
{
B+2, C+D
}
=
same
=
same
In
4
⇒ {
all
}
⇒
Out
1
2
⇒
Out
3
2
⇒
Out
5
2
=
{
C+D, A+C, D+1, A+D
}
=
{
C+D, A+C
}
=
same
In
5
⇒ {
all
}
⇒
Out
1
2
⇒
Out
3
2
⇒
Out
5
2
=
{
C+D, A+C, D+1, A+D
}
=
{
C+D, A+C
}
=
same
Now that we have iterated to the point where our sets are un-
changing, we can perform common subexpression elimination by
examining the intersection of the
In
and
Gen
sets.
When this problem was first created,
the solution was painstakingly hand-
written, which reminded the author
of this particular Simpsons reference:
"Very few cartoons are broadcast live,
it’s a terrible strain on the animantor’s
wrists" - from The Simpsons S
8
E
14
In
1
∩
Gen
1
=
∅
∩ {
B+2, C+D
}
=
∅
In
2
∩
Gen
2
=
{
C+D
} ∩ {
C+D, A+C
}
=
{
C+D
}
In
3
∩
Gen
3
=
{
B+2, C+D
} ∩ {
D+1, C+D
}
=
{
C+D
}
In
4
∩
Gen
4
=
{
C+D, A+C
} ∩
∅
=
∅
In
5
∩
Gen
5
=
{
C+D, A+C
} ∩ {
D+1, E+D
}
=
∅
So unsurprisingly, we do not need to recalculate
C+D
for blocks
2
and
3
.
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
9
Register Allocation
9
.
1
Register Allocation
Exercise
9
.
1
.
1
Using the graphing technique learned in class, create an inter-
ference graph and colour it to determine how many registers are
required for the following code snippet.
Hint
1
: There are two variables that
have two disjoint lifetimes. Think about
when to "end" one lifetime and when to
"start" another.
Hint
2
: You should end up creating
two disjoint graphs.
live-in: c, e
a = mem[e+
4
];
b = mem[c+
8
];
b = a + b;
h = mem[b];
g = mem[h];
f = mem[h+
4
];
c = f + g;
d = c +
4
;
e = c + d;
live-out: d, e, g
Solution
9
.
1
.
1
a
b
c
d
e
f
g
h
live-in
c, e
|
|
a
:= mem[e+
4
]
\
|
/
b
:= mem[c+
8
]
|
\
/
b
:= a + b
/
|
h
:= mem[b]
/
\
g
:= mem[h]
\
|
f
:= mem[h+
4
]
\
|
/
c
:= f + g
\
/
|
d
:= c +
4
|
\
|
e
:= c + d
/
|
\
|
live-out
d, e, g
|
|
|
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
78
derek
+
students
+
staff
The conclusion we can draw is that we should only need three
registers.
Exercise
9
.
1
.
2
Using the graph technique learned in class, create an interference
graph and colour it to determine how many registers for the follow-
ing code snippet.
Hint
: Once again, there are variables
with multiple lifetimes - in fact, one
variable in this question has three
lifetimes
live-in: m, n, s
p = n + s;
q = mem[p];
r = mem[m];
t = q + r;
m = t +
4
;
q = mem[r];
s = m + q;
m = q +
4
;
live-out: m, s
Solution
9
.
1
.
2
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
ece351 study questions
79
m
n
p
q
r
s
t
live-in
m, n, s
|
|
|
p
:= n + s
|
/
\
/
q
:= mem[p]
|
/
\
r
:= mem[m]
/
|
\
t
:= q + r
/
|
\
m
:= t +
4
\
|
/
q
:= mem[r]
|
\
/
s
:= m + q
/
|
\
m
:= q +
4
\
/
|
live-out
m, s
|
|
The conclusion we can draw is that we should only need three
registers.
Exercise
9
.
1
.
3
Bonus "Fun" Question for more graph colouring practice.
The follow-
ing is a (not to scale) map of Deutsche Bahn’s Intercity train network.
In every city Andrew visits, he sends a postcard to one of his friends
at home. However, if he sent a postcard from City A to Friend A, he
can’t send another postcard to Friend A from a city that is directly
connected to City A. Why he does that is a mystery.
For example, if Andrew sends a postcard to Maddie in Freiburg,
then he won’t send another postcard to Maddie from either Karl-
sruhe or Basel. Instead, he might send a postcard to Jim in both Basel
or Karlsruhe, or he might send to Jim in Basel and to Muskan in
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
80
derek
+
students
+
staff
Karlsruhe. What is the minimum number of friends Andrew needs to
ensure that his mysterious rule is not violated?
Solution
9
.
1
.
3
Andrew needs at least three friends. (The actual colouring is left as
an exercise).
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
10
Generational Garbage Collection
10
.
1
Question: x x and y or not
Given:
• the code listing below;
• the input
x x and y or not
• a generational garbage collector with a nursery of size
5
Draw an object diagram for each ‘interesting’ point in the program
execution. ‘Interesting’ points are when each
ast
object is created
and simplified. Timepoints can be identified with a combination of
argument index number and
pc
. Discuss GC or other interesting
aspects.
10
.
2
Assumptions
PC indicates the timepoint after the line has executed.
P
lacement of long
-
lived objects
. We know, from our human
understanding of the program, that the the arguments, parser stack,
and static
ConstantExpr
objects are long-lived. So let’s just put them in
to old space.
O
bject
S
izes
. First we need to figure out how large everything is.
This table should just list the concrete/final classes — not the abstract
classes (abstract classes cannot be directly instantiated). Let’s suppose
the size of our object headers is
1
(in reality it would be larger, but
we’ll work with
1
for now).
Class
Size
=
Total
AndExpr
2
+ header
=
3
OrExpr
2
+ header
=
3
NotExpr
1
+ header
=
2
ConstantExpr
1
+ header
=
2
VarExpr
1
+ header
=
2
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
82
derek
+
students
+
staff
10
.
3
Code Listing
1
package
ece
351
.f.rpn;
2
3
import
java.util.Arrays;
4
import
java.util.Stack;
5
6
7
/
**
A parser with integrated simplifier for an F-like language using RPN.
*
/
8
public final class
FRPN {
9
10
public final static void
main(
final
String[] args) {
11
final
Expr result = parse(args);
12
13
// print outputs
14
System.out.println("rpn: " + Arrays.toString(args));
15
System.out.println("simplified infix: " + result.toString());
16
System.out.println("---");
17
}
18
19
public final static
Expr parse(
final
String[] args) {
20
// our stack for evaluating RPN
21
final
Stack<Expr> stack =
new
Stack<Expr>();
22
// parse Boolean expressions in RPN off the command line
23
for
(
int
i =
0
; i < args.length; i++) {
24
final
String a = args[i];
25
if
(a.equals("
1
")) {
26
stack.push(ConstantExpr.TrueExpr);
27
}
else if
(a.equals("
0
")) {
28
stack.push(ConstantExpr.FalseExpr);
29
}
else if
(a.equals("and")) {
30
final
AndExpr e =
new
AndExpr(stack.pop(), stack.pop());
31
stack.push( e.simplify() );
32
}
else if
(a.equals("or")) {
33
final
OrExpr e =
new
OrExpr(stack.pop(), stack.pop());
34
stack.push( e.simplify() );
35
}
else if
(a.equals("not")) {
36
final
NotExpr e =
new
NotExpr(stack.pop());
37
stack.push( e.simplify() );
38
}
else
{
39
stack.push(
new
VarExpr(a));
40
}
41
}
42
43
// the result of the parse is the expr on the top of the stack
44
// just like Parboiled
45
return
stack.pop();
46
}
47
48
49
}
50
51
abstract class
Expr {
52
abstract
Expr simplify();
53
}
54
abstract class
BinaryExpr
extends
Expr {
55
final
Expr left;
56
final
Expr right;
57
BinaryExpr(Expr l, Expr r) {left = l; right = r;}
58
public
String toString() {
return
"(" + left + operator() + right + ")";}
59
Expr simplify() {
69
abstract
String operator();
70
public abstract
ConstantExpr getAbsorbingElement();
71
public abstract
ConstantExpr getIdentityElement();
72
public boolean
equals(
final
Object obj) {
73
if
(obj ==
null
)
return false
;
74
if
(getClass().equals(obj.getClass())) {
75
final
BinaryExpr b = (BinaryExpr) obj;
76
return
left.equals(b.left) && right.equals(b.right);
77
}
else return false
;
78
}
79
}
80
final class
AndExpr
extends
BinaryExpr {
81
AndExpr(Expr r, Expr l) {
super
(l,r);}
82
public
String operator() {
return
" and "; }
83
public
ConstantExpr getAbsorbingElement() {
return
ConstantExpr.FalseExpr;}
84
public
ConstantExpr getIdentityElement() {
return
ConstantExpr.TrueExpr;}
85
}
86
final class
OrExpr
extends
BinaryExpr {
87
OrExpr(Expr r, Expr l) {
super
(l,r);}
88
public
String operator() {
return
" and "; }
89
public
ConstantExpr getAbsorbingElement() {
return
ConstantExpr.TrueExpr;}
90
public
ConstantExpr getIdentityElement() {
return
ConstantExpr.FalseExpr;}
91
}
92
final class
NotExpr
extends
Expr {
93
final
Expr e;
94
NotExpr(Expr e) {
this
.e = e;}
95
public
String toString() {
return
"(not " + e.toString() + ")";}
96
Expr simplify() {
97
// eliminate double negative
98
if
(e
instanceof
NotExpr) {
99
final
NotExpr oppositionalChild = (NotExpr)e;
100
return
oppositionalChild.e.simplify();
101
}
else return this
;
102
}
103
public boolean
equals(
final
Object obj) {
104
if
(obj
instanceof
NotExpr) {
105
final
NotExpr n = (NotExpr) obj;
106
return
e.equals(n.e);
107
}
else return false
;
108
}
109
}
110
final class
ConstantExpr
extends
Expr {
111
static
ConstantExpr FalseExpr =
new
ConstantExpr(
false
);
112
static
ConstantExpr TrueExpr =
new
ConstantExpr(
true
);
113
final
Boolean val;
114
ConstantExpr(
final
Boolean val) {
this
.val = val;}
115
public
String toString() {
return
val.toString();}
116
Expr simplify() {
return this
;}
117
public boolean
equals(
final
Object obj) {
118
if
(obj
instanceof
ConstantExpr) {
119
final
ConstantExpr c = (ConstantExpr) obj;
120
return
val.equals(c.val);
121
}
else return false
;
122
}
123
}
124
final class
VarExpr
extends
Expr {
125
final
String var;
126
VarExpr(
final
String var) {
this
.var = var;}
127
public
String toString() {
return
var;}
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
ece351 study questions
83
10
.
3
.
1
Object Diagrams
On the exam
you will be asked to
draw the object diagram for a specific
time point (not for all interesting time
points). You will be provided with a
template for the diagram (shown here
in black), and you draw in the
ast
objects (shown here in blue).
How to think about these questions?
a.
Know how to construct the
ast
for
the input: be able to read
rpn
.
b.
Know which parts of the input
ast
will be simplified — this is where
garbage is created (
i.e.
, understand
which simplifications from Lab
4
are
performed by this code).
c.
Figure out the timing of when the
Nursery gets collected, and whether
those collections result in objects
being promoted to old space or
reclaimed.
d.
The interesting time points always
occur when the
pc
is in the loop of
the
parse
method. The call stack is
not particularly interesting for this
program (it will always look the
same, and be part of the template
you will be given).
e.
Be able to identify all of the objects
that are garbage or get reclaimed. In
this example,
AndExpr0
is garbage
and gets reclaimed.
VarExpr0_x
is
garbage, but never gets reclaimed
because we won’t collect old space
in these questions (
i.e.
, we will never
hit the size limit of old space —
which is what triggers a collection).
There is an object diagram for each interesting time point. Time
points in this program are identified by the index of the input ar-
gument array that is currently being processed, and by the
pc
. This
input has six arguments and nine interesting time points: six for
when
ast
objects are created, and three for when they are simplified.
c
.
b
.
a
. = Cumulative Bytes Allocated
Arg
pc
Notes
c
.
b
.
a
.
0
32
Created
VarExpr0_x
(in Nursery)
2
1
32
Created
VarExpr1_x
(in Nursery)
4
2
23
Created
AndExpr0
in Nursery. But there wasn’t
enough space, so first we had to do a Nursery
collection, which resulted in both
VarExpr
objects
being promoted to Old Space.
7
2
24
Simplified
AndExpr0
, and pushed (a pointer to)
the result (
VarExpr1_x
) on to the parser stack.
7
3
32
Created
VarExpr2_y
(in Nursery — there was
enough space)
9
4
26
Created
OrExpr0
in Nursery. But there wasn’t
enough space, so we had to collect the nursery
first, which resulted in reclaiming
AndExpr0
.
12
4
27
Simplifed
OrExpr0
and pushed (a pointer to) the
result (just
OrExpr0
) on to the parser stack.
12
5
29
Created
NotExpr0
in the Nursery (there was
enough space).
14
5
30
Simplifed
NotExpr0
and pushed (a pointer to)
the result (just
NotExpr0
) on to the parser stack.
14
Old Space
Nursery (size=5)
PC: 32
statics
ConstantExpr.False
ConstantExpr.True
main()
args
result
ConstantExpr0
val = False
ConstantExpr1
val = True
parse()
args
i = 0
a
stack
e
Array0
x
x
and
y
or
not
slot3
slot2
slot1
slot0
Parser Stack
VarExpr0
var = x
Old Space
Nursery (size=5)
PC: 32
statics
ConstantExpr.False
ConstantExpr.True
main()
args
result
ConstantExpr0
val = False
ConstantExpr1
val = True
parse()
args
i = 1
a
stack
e
Array0
x
x
and
y
or
not
slot3
slot2
slot1
slot0
Parser Stack
VarExpr0
var = x
VarExpr1
var = x
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
84
derek
+
students
+
staff
Old Space
Nursery (size=5)
PC: 23
statics
ConstantExpr.False
ConstantExpr.True
main()
args
result
ConstantExpr0
val = False
ConstantExpr1
val = True
parse()
args
i = 2
a
stack
e
Array0
x
x
and
y
or
not
slot3
slot2
slot1
slot0
Parser Stack
AndExpr0
left
right
VarExpr0
var = x
VarExpr1
var = x
Old Space
Nursery (size=5)
PC: 24
statics
ConstantExpr.False
ConstantExpr.True
main()
args
result
ConstantExpr0
val = False
ConstantExpr1
val = True
parse()
args
i = 2
a
stack
e
Array0
x
x
and
y
or
not
slot3
slot2
slot1
slot0
Parser Stack
AndExpr0
left
right
VarExpr1
var = x
VarExpr0
var = x
Old Space
Nursery (size=5)
PC: 32
statics
ConstantExpr.False
ConstantExpr.True
main()
args
result
ConstantExpr0
val = False
ConstantExpr1
val = True
parse()
args
i = 3
a
stack
e
Array0
x
x
and
y
or
not
slot3
slot2
slot1
slot0
Parser Stack
VarExpr1
var = x
VarExpr2
var = y
VarExpr0
var = x
AndExpr0
left
right
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
ece351 study questions
85
Old Space
Nursery (size=5)
PC: 26
statics
ConstantExpr.False
ConstantExpr.True
main()
args
result
ConstantExpr0
val = False
ConstantExpr1
val = True
parse()
args
i = 4
a
stack
e
Array0
x
x
and
y
or
not
slot3
slot2
slot1
slot0
Parser Stack
OrExpr0
left
right
VarExpr0
var = x
VarExpr1
var = x
VarExpr2
var = y
Old Space
Nursery (size=5)
PC: 27
statics
ConstantExpr.False
ConstantExpr.True
main()
args
result
ConstantExpr0
val = False
ConstantExpr1
val = True
parse()
args
i = 4
a
stack
e
Array0
x
x
and
y
or
not
slot3
slot2
slot1
slot0
Parser Stack
OrExpr0
left
right
VarExpr0
var = x
VarExpr1
var = x
VarExpr2
var = y
Old Space
Nursery (size=5)
PC: 29
statics
ConstantExpr.False
ConstantExpr.True
main()
args
result
ConstantExpr0
val = False
ConstantExpr1
val = True
parse()
args
i = 5
a
stack
e
Array0
x
x
and
y
or
not
slot3
slot2
slot1
slot0
Parser Stack
NotExpr0
e
VarExpr0
var = x
VarExpr1
var = x
VarExpr2
var = y
OrExpr0
left
right
Old Space
Nursery (size=5)
PC: 30
statics
ConstantExpr.False
ConstantExpr.True
main()
args
result
ConstantExpr0
val = False
ConstantExpr1
val = True
parse()
args
i = 5
a
stack
e
Array0
x
x
and
y
or
not
slot3
slot2
slot1
slot0
Parser Stack
NotExpr0
e
VarExpr0
var = x
VarExpr1
var = x
VarExpr2
var = y
OrExpr0
left
right
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
86
derek
+
students
+
staff
10
.
4
Question: z not not not
Consider the
F
rpn
program
z not not not
. We know from our knowl-
edge of how
F
simplifies that the first two
not
s will become garbage:
it’s a double negative. That part is easy. It requires a bit more think-
ing to figure out if they will be in the Nursery or in Old Space at the
time they become garbage. Let’s see:
Old Space
Nursery (size=5)
PC: 32
statics
ConstantExpr.False
ConstantExpr.True
main()
args
result
ConstantExpr0
val = False
ConstantExpr1
val = True
parse()
args
i = 0
a
stack
e
Array0
z
not
not
not
slot3
slot2
slot1
slot0
Parser Stack
VarExpr0
var = z
Old Space
Nursery (size=5)
PC: 29
statics
ConstantExpr.False
ConstantExpr.True
main()
args
result
ConstantExpr0
val = False
ConstantExpr1
val = True
parse()
args
i = 1
a
stack
e
Array0
z
not
not
not
slot3
slot2
slot1
slot0
Parser Stack
NotExpr0
e
VarExpr0
var = z
Old Space
Nursery (size=5)
PC: 30
statics
ConstantExpr.False
ConstantExpr.True
main()
args
result
ConstantExpr0
val = False
ConstantExpr1
val = True
parse()
args
i = 1
a
stack
e
Array0
z
not
not
not
slot3
slot2
slot1
slot0
Parser Stack
NotExpr0
e
VarExpr0
var = z
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
ece351 study questions
87
Once we complete the next step of
execution, we as humans can see that
NotExpr1
and
NotExpr0
are garbage, but
they won’t get reclaimed any time soon.
Also, they would need to be reclaimed
by separate collections, since
NotExpr0
is
now in old space, whereas
NotExpr1
is
still in the nursery.
When we go to allocate
NotExpr1
, we find that the nursery doesn’t
have enough space: it already contains
NotExpr0
(size=
2
) and
VarExpr0_z
(size=
2
); with a total capacity of
5
, there isn’t space to allocate
NotExpr1
(size=
2
). So we collect the nursery. But
NotExpr0
and
VarExpr0_z
aren’t
garbage now, so we promote them to old space.
Old Space
Nursery (size=5)
PC: 29
statics
ConstantExpr.False
ConstantExpr.True
main()
args
result
ConstantExpr0
val = False
ConstantExpr1
val = True
parse()
args
i = 2
a
stack
e
Array0
z
not
not
not
slot3
slot2
slot1
slot0
Parser Stack
NotExpr1
e
VarExpr0
var = z
NotExpr0
e
Old Space
Nursery (size=5)
PC: 30
statics
ConstantExpr.False
ConstantExpr.True
main()
args
result
ConstantExpr0
val = False
ConstantExpr1
val = True
parse()
args
i = 2
a
stack
e
Array0
z
not
not
not
slot3
slot2
slot1
slot0
Parser Stack
NotExpr1
e
VarExpr0
var = z
NotExpr0
e
Old Space
Nursery (size=5)
PC: 29
statics
ConstantExpr.False
ConstantExpr.True
main()
args
result
ConstantExpr0
val = False
ConstantExpr1
val = True
parse()
args
i = 3
a
stack
e
Array0
z
not
not
not
slot3
slot2
slot1
slot0
Parser Stack
NotExpr2
e
VarExpr0
var = z
NotExpr0
e
NotExpr1
e
Old Space
Nursery (size=5)
PC: 30
statics
ConstantExpr.False
ConstantExpr.True
main()
args
result
ConstantExpr0
val = False
ConstantExpr1
val = True
parse()
args
i = 3
a
stack
e
Array0
z
not
not
not
slot3
slot2
slot1
slot0
Parser Stack
NotExpr2
e
VarExpr0
var = z
NotExpr0
e
NotExpr1
e
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
88
derek
+
students
+
staff
10
.
5
Question: p not p not and not
Draw the object diagram for the following:
This is what an exam question might look
like. It would take too much time to have
you draw every interesing time point, so
you will need to be able to think ahead
without drawing everything.
• Input:
p not p not and not
• Nursery Size:
11
• Argument Index:
5
• PC:
30
10
.
5
.
1
Thinking
Above we drew the diagrams for every interesting time point. That’s
ast
for the full input:
NotExpr2
AndExpr0
NotExpr1
NotExpr0
VarExpr1p
VarExpr0p
time consuming. Can we skip forward to a specific point in time?
Yes. Let’s do it. First, we think about the input: what will it simplify
to? In this case, just
p
. So everything else becomes garbage. The
question is where do these objects end up, and when do they get
collected (or not). Let’s think a bit:
Args:
p
not
p
not
and
not
Index:
0
1
2
3
4
5
Size:
2
2
2
2
3
2
Cumulative:
2
4
6
8
11
13
Object Name:
VarExpr0_p
NotExpr0
VarExpr1_p
NotExpr1
AndExpr0
NotExpr2
• Allocation up to and including
AndExpr0
will fit in the nursery.
• Simplification of
AndExpr0
makes some objects
unreachable
(
i.e.
, makes them garbage):
VarExpr0_p
,
NotExpr0
,
AndExpr0
.
• Allocation of
NotExpr2
causes collection of the nursery (because it won’t fit: the nursery is now
completely full). So the unreachable objects listed above get collected.
• Simplification of
NotExpr2
creates more garbage: now
NotExpr1
and
NotExpr2
are also unreach-
able. But recall that
NotExpr1
has been promoted to Old Space when the nursery was previ-
ously collected.
10
.
5
.
2
Solution
The blue parts of this object diagram are
what you ultimately draw. Let’s come up
with a grading scheme ...
•
2
marks for drawing the
ast
of the
original input (separate diagram)
•
1
mark for correct heap pointers
(which will be a subset of the
ast
pointers you already identified)
•
1
mark for the state of the parser
stack
•
3
marks for correctly identifying
objects that become garbage and are
collected (which can be identified by
their absence on your final diagram)
•
3
marks for correctly placing objects
that are garbage but not collected
(
i.e.
, are in the Nursery or in Old
Space on your final diagram)
•
=
10
marks total
Old Space
Nursery (size=11)
PC: 30
statics
ConstantExpr.False
ConstantExpr.True
main()
args
result
ConstantExpr0
val = False
ConstantExpr1
val = True
parse()
args
i = 5
a
stack
e
Array0
p
not
p
not
and
not
slot3
slot2
slot1
slot0
Parser Stack
NotExpr2
e
VarExpr1
var = p
NotExpr1
e
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
11
Mark+Sweep Garbage Collection [NEW S
2019
]
• NEW for S
2019
!
• Based on source code listing in skeleton ece
351
/exam
• Using SimplifyVisitor
• Key issue here is showing physical placement of objects in the
heap. In our previous object diagrams we were not concerned
with the physical placement — we showed objects wherever it was
visually convenient to do so.
• These questions are equally applicable for Semi-Space Copying
Collector. Expect to be asked to illustrate the same program in
both GC techniques. The diagrams here are just Mark+Sweep.
Given these Mark+Sweep diagrams, it shouldn’t be hard for you to
draw the Semi-Space diagrams on your own.
• An exam question would typically ask you for just one time point.
Here you are often provided with illustrations of multiple time
points for studying purposes.
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
90
derek
+
students
+
staff
11
.
1
1
Not
package
ece351.exam;
public class
V1N {
public static void
main(
final
String[] args) {
// C1. construct an expr
// C2. simplify it
final
Expr simplified = SimplifyVisitor.doit(
new
NotExpr(ConstantExpr.TrueExpr));
// C3. construct the expected result
final
Expr expected = ConstantExpr.FalseExpr;
// C4. compare simplified with expected
System.out.println(expected.equals(simplified));
}
}
Heap (size=8)
PC: C3
statics
ConstantExpr.False
ConstantExpr.True
V1N main()
args
simplified
expected
ConstantExpr0
val = False
ConstantExpr1
val = True
Array0
NotExpr1
e
SimplifyVisitor1
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
ece351 study questions
91
11
.
2
x Not Not
package
ece351.exam;
public class
VxNN {
public static void
main(
final
String[] args) {
// C1. construct an expr
final
Expr original =
new
NotExpr(
new
NotExpr(
new
VarExpr("x")));
// C2. simplify it
final
Expr simplified = SimplifyVisitor.doit(original);
// C3. construct the expected result
final
Expr expected =
new
VarExpr("x");
// C4. compare simplified with expected
System.out.println(expected.equals(simplified));
}
}
Heap (size=16)
PC: C2
statics
ConstantExpr.False
ConstantExpr.True
VxNN main()
args
original
simplified
expected
ConstantExpr0
val = False
ConstantExpr1
val = True
Array0
NotExpr2
e
NotExpr1
e
VarExpr1
var = x
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
92
derek
+
students
+
staff
These diagrams illustrate the case where
PostOrderVisitor.traverseExpr()
handles the
NotExpr
case like so:
1
}
else if
(e
instanceof
NotExpr) {
2
final
NotExpr n = (NotExpr)e;
3
final
Expr child2 = traverseExpr(n.e);
4
final
Expr result =
new
NotExpr(child2);
5
return
result.accept(
this
);
How do the diagrams change if we change line
4
like so:
4
final
Expr result = child2.equals(n.e) ? n :
new
NotExpr(child2);
Heap (size=16)
PC: C3
statics
ConstantExpr.False
ConstantExpr.True
VxNN main()
args
original
simplified
expected
ConstantExpr0
val = False
ConstantExpr1
val = True
Array0
NotExpr2
e
VarExpr1
var = x
NotExpr1
e
SimplifyVisitor1
NotExpr3
e
NotExpr4
e
Heap (size=16)
PC: C4
statics
ConstantExpr.False
ConstantExpr.True
VxNN main()
args
original
simplified
expected
ConstantExpr0
val = False
ConstantExpr1
val = True
Array0
VarExpr1
var = x
NotExpr2
e
VarExpr2
var = x
NotExpr1
e
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
ece351 study questions
93
If we bump the heap size up to
18
so the collection isn’t necessary,
then we can just allocate the expected VarExpr
2
at the end:
Heap (size=18)
PC: C4
statics
ConstantExpr.False
ConstantExpr.True
VxNN main()
args
original
simplified
expected
ConstantExpr0
val = False
ConstantExpr1
val = True
Array0
NotExpr2
e
VarExpr1
var = x
VarExpr2
var = x
NotExpr1
e
SimplifyVisitor1
NotExpr3
e
NotExpr4
e
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
94
derek
+
students
+
staff
11
.
3
x
1
And y Or
public class
Vx1AyO {
public static void
main(
final
String[] args) {
// C1. construct an expr
// C2. simplify it
final
Expr simplified = SimplifyVisitor.doit(
new
OrExpr(
new
AndExpr(
new
VarExpr("x"), ConstantExpr.TrueExpr),
new
VarExpr("y")));
// C3. construct the expected result
final
Expr expected =
new
OrExpr(
new
VarExpr("x"),
new
VarExpr("y"));
// C4. compare simplified with expected
System.out.println(expected.equals(simplified));
}
}
Heap (size=22)
PC: C3
statics
ConstantExpr.False
ConstantExpr.True
Vx1AyO main()
args
simplified
expected
ConstantExpr0
val = False
ConstantExpr1
val = True
Array0
OrExpr2
left
right
VarExpr1
var = x
AndExpr1
left
right
VarExpr2
var = y
OrExpr1
left
right
SimplifyVisitor
AndExpr2
left
right
Heap (size=22)
PC: C4
statics
ConstantExpr.False
ConstantExpr.True
Vx1AyO main()
args
simplified
expected
ConstantExpr0
val = False
ConstantExpr1
val = True
Array0
OrExpr3
left
right
OrExpr2
left
right
VarExpr1
var = x
VarExpr3
var = x
EmptySlot1
VarExpr2
var = y
VarExpr4
var = y
EmptySlot2
EmptySlot3
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
Part III
Other Stuff
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
12
Short-Answer Questions
12
.
1
Computational Complexity
Exercise
12
.
1
.
1
What is one fundamental difference between Turing
Machines and real, practical computers? Give an example of how this
difference affects compilers?
Solution
12
.
1
.
1
Infinite Tape vs. Finite Memory. This manifests it-
self in the form of the register allocation problem. There is only a
finite number of registers available at one time to the program. If
the program can’t fit the required variables in the limited number
of registers, variables must spill into main memory, which is much
slower.
Exercise
12
.
1
.
2
Name four well-known examples of NP-complete
problems.
Solution
12
.
1
.
2
• travelling salesman
• backpack/knapsack
• Hamiltonian path-finding
• Boolean satisfiability
• subgraph isomorphism
• clique problem
• vertex cover problem
• register allocation
• graph colouring
Exercise
12
.
1
.
3
What does ’linear time’ look like in big-O notation?
Solution
12
.
1
.
3
O(n)
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
98
derek
+
students
+
staff
Exercise
12
.
1
.
4
What is the name for
O
(
1
)
?
Solution
12
.
1
.
4
constant time
Exercise
12
.
1
.
5
Name a famous undecidable problem and explain
why it is important for compilers.
Solution
12
.
1
.
5
Halting problem. Shows us the limits of what com-
pilers can understand about programs.
Exercise
12
.
1
.
6
Name three engineering design alternatives when
faced with an NP-complete problem.
Solution
12
.
1
.
6
• Implement a custom solution by hand.
• Use a SAT solver.
• Use a polynomial approximation.
Exercise
12
.
1
.
7
Are non-deterministic pushdown automata more
powerful than deterministic pushdown automata?
Solution
12
.
1
.
7
Yes.
Exercise
12
.
1
.
8
Are non-deterministic Turing Machines more power-
ful than deterministic Turing Machines?
Solution
12
.
1
.
8
No.
Exercise
12
.
1
.
9
Simplify
O
(
7
n
2
+
n
+
100
)
.
Solution
12
.
1
.
9
O
(
n
2
)
Exercise
12
.
1
.
10
Draw a Venn diagram illustrating set difference.
Solution
12
.
1
.
10
not found. . .
Exercise
12
.
1
.
11
T
E
X (upon which L
A
T
E
X is built) is a Turing Complete
language for formatting documents. What two features must it have
to be Turing Complete?
Solution
12
.
1
.
11
conditionals (ifs) and repetition (loops or recursion)
Do not penalize students who addition-
ally say infinite storage, which is not
technically part of the language — the
storage amount is part of the machine
the language runs on.
Exercise
12
.
1
.
12
Name another common language for formatting
documents that is not Turing Complete.
Solution
12
.
1
.
12
HTML or PDF
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
ece351 study questions
99
Exercise
12
.
1
.
13
PostScript is a language commonly used to describe
pages for printers. It is Turing Complete. What bad thing might
happen when we send a PostScript file to a printer that could not
happen if PostScript were not Turing Complete?
Solution
12
.
1
.
13
The printer could get stuck in an infinite loop.
Exercise
12
.
1
.
14
What is the halting problem?
Solution
12
.
1
.
14
To prove that some Turing machine (
i.e.
, program)
halts on all possible inputs.
Exercise
12
.
1
.
15
Who defined the halting problem?
Solution
12
.
1
.
15
Alan Turing
A student might mis-read Craig Ka-
plan’s web page on the halting problem
to think that Kurt Gödel defined the
halting problem. Gödel invented the
mathematical technique that Turing
used in his proof, but Gödel’s proof
was about first-order logic, not about
computation.
Exercise
12
.
1
.
16
What is the formal definition of
easy
in this course?
Give the term and a sentence explaining it.
Solution
12
.
1
.
16
Polynomial computational (time) complexity (
e.g.
,
O
(
n
)
,
O
(
n
2
)
).
Exercise
12
.
1
.
17
What is the formal definition of
hard
in this course?
Give the term and a sentence explaining it.
Solution
12
.
1
.
17
NP complete. Exponential computational (time)
complexity.
O
(
2
n
)
Exercise
12
.
1
.
18
What is the formal definition of
impossible
in this
course? Give the term and a sentence explaining it.
Solution
12
.
1
.
18
Undecidable. Cannot be computed by a Turing
machine.
Exercise
12
.
1
.
19
Do these terms describing difficulty have anything
to do with how much effort the programmer must expend solving
problems? What resource are these terms talking about?
Solution
12
.
1
.
19
No, nothing to do with how much effort the pro-
grammer must expend to write the code. It’s about the number of steps
the machine must take to solve the problem.
Exercise
12
.
1
.
20
What does NP stand for?
Solution
12
.
1
.
20
Non-deterministic Polynomial
Exercise
12
.
1
.
21
How long does it take to solve an NP-complete
problem on a single-core deterministic computer?
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
100
derek
+
students
+
staff
Solution
12
.
1
.
21
Exponential time
O
(
2
n
)
Exercise
12
.
1
.
22
Name a strategy for computing answers to an NP-
complete problem.
Solution
12
.
1
.
22
Use a known polynomial heuristic.
Exercise
12
.
1
.
23
Name a second strategy for computing answers to
an NP-complete problem.
Solution
12
.
1
.
23
Use a SAT solver.
Exercise
12
.
1
.
24
Name third strategy for computing answers to an
NP-complete problem.
Solution
12
.
1
.
24
Write an exhaustive search algorithm by hand.
Exercise
12
.
1
.
25
What is the Boolean SATisfiability problem?
Solution
12
.
1
.
25
Given a Boolean formula, find values for the vari-
ables that make the formula true (
i.e.
, find a row in the truth table
that evaluates to (true).
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
ece351 study questions
101
12
.
2
Automata
Exercise
12
.
2
.
1
List two differences between NFAs and DFAs.
Solution
12
.
2
.
1
a. DFAs cannot have edges labelled
e
, NFAs can,
b. DFAs must have different labels
on all edges leaving a given
state while NFAs can have several edges leaving the same state
with the same label
.
Exercise
12
.
2
.
2
What kind of machine is required to recognize a
regular language?
Solution
12
.
2
.
2
Finite automata (finite state machine)
Exercise
12
.
2
.
3
How long does it take for a finite state machine to
run?
Solution
12
.
2
.
3
O
(
n
)
/ linear time
Exercise
12
.
2
.
4
Are NFAs more powerful than DFAs? Why?
Solution
12
.
2
.
4
No. They can be converted to each other.
Exercise
12
.
2
.
5
Are
ece327
finite state machines more powerful than
ece351
finite state machines?
Solution
12
.
2
.
5
No. They can be converted to each other.
Exercise
12
.
2
.
6
Are
ece327
finite state machines more convenient for
people to use to describe hardware circuits?
Solution
12
.
2
.
6
Yes.
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
102
derek
+
students
+
staff
12
.
3
Grammars
Exercise
12
.
3
.
1
What kind of machine is required to recognize a
LL(
1
) language?
Solution
12
.
3
.
1
Pushdown automata
Exercise
12
.
3
.
2
What grammar class is required for the language
{
a
n
b
n
|
n
>
0
}
?
Solution
12
.
3
.
2
CFG
LL(
1
) is also a correct answer, since this grammar falls in the LL(
1
)
subset
of CFGs.
Exercise
12
.
3
.
3
What grammar class is required for the language
{
a
n
b
n
c
n
|
n
>
0
}
?
Solution
12
.
3
.
3
Context-sensitive (or PEG, but we won’t learn that
until after the midterm)
Exercise
12
.
3
.
4
How do we show that a grammar is ambiguous?
Solution
12
.
3
.
4
Show an input string that has multiple parse trees
with the given grammar
Exercise
12
.
3
.
5
How do we show that a grammar is unambiguous?
Solution
12
.
3
.
5
Mathematically beyond the scope of ECE
351
. We just
say that we cannot think of an input string with multiple parses. As
long as nobody else in class can think of such an input string then
you are in luck.
Exercise
12
.
3
.
6
What is something that can be expressed in a CFG
that cannot be expressed in a PEG?
Solution
12
.
3
.
6
ambiguity
Exercise
12
.
3
.
7
How many concepts of grammar equivalence have we
considered in
ece351
? What are they?
Solution
12
.
3
.
7
a.
Strong Equivalence:
accepts same language, makes exactly the same parse trees.
b.
Weak Equivalence:
accepts same language, but might make different parse trees.
Exercise
12
.
3
.
8
When we refactor a grammar, in what way is the
refactored grammar equivalent to the original grammar?
Solution
12
.
3
.
8
The refactored grammar is typically
weakly equiva-
lent
to the original grammar:
i.e.
, it accepts the same language, but
constructs different parse trees.
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
A
Epilogue
H
eroic student creates pages and pages of practice prob
-
lems
, and then also says:
Engineering is the art of regurgitating practice problems until you’ve
memorized the pattern, and hence here are some practice problems
that I came up with for Chapter
6
(Optimization) since there seems to
be none in the study docs.
The answers may be wrong, use at your own risk,
etc.
.
P
rof response
: First, let me thank you for creating more study
questions. That’s great.
Second, let me address the Engineering culture comment. Yeah,
that’s kind of true in practice. Let’s talk about it. This is not the in-
tellectual culture in CS (this distinction is much bigger than UW, but
does exist here). In CS/Math culture, students would be expected to
think on an exam. To see something new and figure it out. To study
on their own without being given lots of solutions. There are, I think,
several reasons for this.
1
. In some areas of engineering, it is not possible to come to an-
swers just by reasoning from first principles: empirical knowledge
of past practice must also be employed. Engineers build things that
work in the real world, in cases where the theory is not fully known
(e.g., fluid dynamics), and where we have imperfect information. We
do this by accumulating experience of what has worked in the past
in similar circumstances. In the context of compilers, knowing how
a program transformation will actually affect program performance
is very empirical: cache lines, register allocation, etc, etc. Math/CS
doesn’t deal with the real world. They can always reason from first
principles for their problems, because they can only solve problems
that can be handled in this way. Engineers can handle a wider range
of problems (like, sometimes we reason from first principles too).
2
. Engineering students have a very high workload, so they have
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
104
derek
+
students
+
staff
less time (or feel like they have less time) to think deeply about
things. Crummy reality. But in part because of this engineering
students put a lot of pressure on profs to supply solutions, which
sometimes gives profs the feeling that the students want to be spoon
fed and won’t think for themselves. I have that thought a lot less than
some other profs, but it is a thing on this side of the desk.
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
Recommended textbooks for you
COMPREHENSIVE MICROSOFT OFFICE 365 EXCE
Computer Science
ISBN:9780357392676
Author:FREUND, Steven
Publisher:CENGAGE L
Programming Logic & Design Comprehensive
Computer Science
ISBN:9781337669405
Author:FARRELL
Publisher:Cengage

Operations Research : Applications and Algorithms
Computer Science
ISBN:9780534380588
Author:Wayne L. Winston
Publisher:Brooks Cole

C++ for Engineers and Scientists
Computer Science
ISBN:9781133187844
Author:Bronson, Gary J.
Publisher:Course Technology Ptr

EBK JAVA PROGRAMMING
Computer Science
ISBN:9781337671385
Author:FARRELL
Publisher:CENGAGE LEARNING - CONSIGNMENT

C++ Programming: From Problem Analysis to Program...
Computer Science
ISBN:9781337102087
Author:D. S. Malik
Publisher:Cengage Learning
Recommended textbooks for you
- COMPREHENSIVE MICROSOFT OFFICE 365 EXCEComputer ScienceISBN:9780357392676Author:FREUND, StevenPublisher:CENGAGE LProgramming Logic & Design ComprehensiveComputer ScienceISBN:9781337669405Author:FARRELLPublisher:CengageOperations Research : Applications and AlgorithmsComputer ScienceISBN:9780534380588Author:Wayne L. WinstonPublisher:Brooks Cole
- C++ for Engineers and ScientistsComputer ScienceISBN:9781133187844Author:Bronson, Gary J.Publisher:Course Technology PtrEBK JAVA PROGRAMMINGComputer ScienceISBN:9781337671385Author:FARRELLPublisher:CENGAGE LEARNING - CONSIGNMENTC++ Programming: From Problem Analysis to Program...Computer ScienceISBN:9781337102087Author:D. S. MalikPublisher:Cengage Learning
COMPREHENSIVE MICROSOFT OFFICE 365 EXCE
Computer Science
ISBN:9780357392676
Author:FREUND, Steven
Publisher:CENGAGE L
Programming Logic & Design Comprehensive
Computer Science
ISBN:9781337669405
Author:FARRELL
Publisher:Cengage

Operations Research : Applications and Algorithms
Computer Science
ISBN:9780534380588
Author:Wayne L. Winston
Publisher:Brooks Cole

C++ for Engineers and Scientists
Computer Science
ISBN:9781133187844
Author:Bronson, Gary J.
Publisher:Course Technology Ptr

EBK JAVA PROGRAMMING
Computer Science
ISBN:9781337671385
Author:FARRELL
Publisher:CENGAGE LEARNING - CONSIGNMENT

C++ Programming: From Problem Analysis to Program...
Computer Science
ISBN:9781337102087
Author:D. S. Malik
Publisher:Cengage Learning