Programming Languages Final
Classify the following languages to their category: Haskell, Lisp, Prolog, C, C++, Perl, Ada, PHP, Python, Smalltalk, Eiffel, Apl, Javascript
C++ Eiffel, Smalltalk - Object oriented Javascript, perl, PHP - Scripting C, Ada - von Neumann prolog - logical Haskell, Lisp, APL - Functional
Explain circumstances under which two mathematically equivalent orderings of the same expression can lead to different results.
C++, use of static member variable side effects code improvement
Some compilers perform all semantic checks and intermediate code generation in action routines. Others use action routines to build a syntax tree and then perform semantic checks and intermediate code generation in separate traversals of the syntax tree. Discuss the tradeoffs between these two strategies
->does not have to construct entire parse tree because attributes of a production are evaluated as they are parsed; they are imbedded in righthand sides of productions ->if the action routine is responsible for much of the semantic analysis, they need contextual information to do their job; an LR parse thus requires access to inherited attributes outside the current production
How can a variable be live but not in scope? Give 2 examples.
1.) Global variable x is still live but not in scope if a local variable x is declared in the scope. 2.) C++: the private member variables of an object of class C are live but not in scope when execution is not inside a member function of C.
Outline the steps carried out by the driver in a shift-reduce parser.
1.) shift tokens from scanner into forest (stack) while keeping track of state until 2.) a right-hand side is recognized and is then 3.) reduced to a left-hand side by popping off the stack and pushing left-hand side back onto right stack contains a record of what parser has already seen, in contrast to top-down parse which keeps track of what it expects to see
What formal rules are needed to define a regular grammar, and how can a regular grammar be extended to a context-free grammar?
3 rules needed: Concatenation, alternation, Kleene closure (repetition) Regular expression to context-free grammar -> add recursion
heap fragmentation
(internal) blocks allocated are more than required resulting in gaps of wasted free memory on heap; (external) alloc blocks scattered through heap causing no room for large allocs despite free space
Difference between context-sensitive and context-free grammars
context-sensitive -> permits expansions based on context of construct like natural language context-free -> relies on potentially recursive rules free of context of the construct
Define and explain the role of: preconditions, invariants, and postconditions.
cover specific checks more succinctly than assertions; structured assertions invariant->true at before and after subroutine call precondition-> true before subroutine postcondition->true after
Explain the difference between a declaration and a definition.
declaration-> introduces name & scope but may omit implementation details definition-> describes object in enough detail for compiler to determine its implementation
What is deep binding and how is it implemented?
deep binding-> choice is made when reference is first created for when object is bound to its referencing environment
What is the primary argument in favor of dynamic scoping?
easy for an interpreter to lookup meaning of name using only a stack of declarations
Describe structured programming.
emphasizes: ->top-down design ->modularization of code ->structured types (records, sets, pointers, multi-dim arrays) ->descriptive names ->lots of comments
epsilon production
empty string on righthand side of a production
What is the handle of an expression, and what is its significance (why is it important)?
handle->left-most simple phrase It is the next node to be processed
What does it mean for a function to be idempotent?
idempotent function->will always return same value when called repeatedly with same arguments
displacement addressing
implicitly providing a predetermined offset to the value in the frame pointer as a part of ordinary load or store instructions
Side effect
influence of subsequent computation in ANY WAY other than by returning a value
LL(n)
left to right scanning; leftmost derivation; n look ahead
LR(n)
left to right scanning; rightmost derivation; n look ahead
nonterminal
left-hand side of production
What language feature prevents top-down parsing? How is this problem resolved (other than switching to bottom-up parsing)?
left-recursion & common prefixes; use disambiguating rule; mechanically remove
Unsafe optimization
may lead to incorrect code
Compile-time constant
named constants whose value is set at compile time by other known constants and built in functions
Explain the difference between subtype polymorphism and parametric polymorphism. Given an example of where each is used. Explain the difference between explicit and implicit parametric polymorphism.
parametric poly->takes type as a parameter; (explicit) generics, statically typed, impl compile time; allows for static type checking; (implicit) an extra type param subtype->code designed to work with subtypes of type T and can be extended (Java); a derived class that does not hide any publicly visible members of its base class is a subtype of that base class
How does a top-down parser proceed through the source code?
parse from the root down; predicts next step to expand current node
Define precedence and associativity, and give examples of common practices for each.
precedence-> certain operators group more tightly than others (ex. multiplication vs. addition; flat precedence in Pascal) associativity->specifies whether operators of equal precedence group left to right or right to left, usually left to right; example 9 - 3 - 2 = 4 NOT 8; Ada's exponentiation operator does not associate
What are some pros and cons of using macro expansion?
pro: cut down on repetitive code via textual substitution; hygienic macros encapsulate their arguments (clojure) cons: naming & binding mechanisms apart from the rest of the language
syntax analysis
process for discovering the syntactic structure of a program
prologue/epilogue
prologue->code executed at beginning of a call as part of stack maintainence epilogue->code executed at the end of the subroutine itself
attribute grammar
provide formal framework/grammar for decoration of a tree
Using pseudocode to simulate near-assembler level code, show the logic flow necessary to implement a counter-controlled loop.
r1 = first r2= step r3=last L1 —loop body r1= r1 + r2 L2 if r1 < r3 goto L1
Using pseudocode to simulate near-assembler level code, show the logic flow necessary to implement an if/then/else block.
r1=A r2=B if r1 <= r2 gotoL4 r1=C r2=D if r1>r2 goto L1 L4 r1= e r2= F if r1 = r2 goto L2 L1 goto L3 //then clause L2 // else clause
What is the role of the semantic analyzer?
role->enforce all static semantic rules and annotate the program with information needed by the intermediate code generator
Describe the behavior and purpose of an iterator.
routine that can enumerate the elements of a collection and may contain yield statements
Describe the phases of the compilation process
scanner -> char stream in; tokens out _ Lexical analysis parser -> tokens in; parse tree out _ Syntax analysis semantic analysis -> parse tree in; _ abstract syntax tree out _ Intermediate code generation Machine-independent code improvement target code generation -> target lang machine specific code improvement
Some languages distinguish between upper and lower-case letters in identifiers (so dog and DOG are distinct in some languages and not others). What are the pros and cons of each?
sensitivity permits code convention & is easier to check insensitivity adds flexibility (SQL) and is forgiving of typos
Name the 8 principal categories of language mechanisms to specify control flow.
sequencing->order statements are executed selection->choice at runtime iteration->repetition procedural abstraction -> subroutines recursion->expression defined in terms of itself concurrency->two or more program fragments executed at once exception handling/speculation->ability to branch to a handler if expected conditions are false nondeterminacy-> ordering/choice unspecified but will lead to correct results
Referencing environment
set of active bindings at a given moment in program execution
token
shortest strings w/ individual meaning
Fibonacci heap
similar to buddy, but sizes grow in fibonacci seq, which is slower than 2^k and results in lower internal fragmenation
keyword/reserved word
specials strings that are in identifier form but reserved for special purpose
What must be done if a nonlocal goto is encountered in a language that supports it?
Kill it with fire
recursive descent parser
LL, expands current node predictively
bottom-up parser
LR; usually hand written; starts from leaves up
Difference between declarative and imperative languages
Declarative- what to do Imperative - How to do
Within the declarative and imperative families, there are several subclasses to classify languages. Name 5 of them
Functional, logic, object oriented, von Neumann, scripting, markup
Do automated tools for finding storage bugs weaken the argument for automatic garbage collection? Justify your answer.
No, tools for finding storage bugs do not guarantee they will be used. Best-practices are ideal but not always practiced. Garbage collection ensures unused memory will be eventually deallocated.
Describe the steps necessary to run Java code
Source code -> Java Compiler -> Java bytecode -> bytecode interpreter OR bytecode -> JIT compiler -> machine language
Using pseudocode to simulate near-assembler level code, show the logic flow necessary to implement a switch statement.
T; &L1 &L2 //array of addresses &L3 L6 r1= (expression) if r1 < 1 goto L5 if r1 > 10 got L5 //L5 is else arm r1 -= 1 //subract off lower bound r1 = T[r1] goto *r1
Describe the difference between leftmost and rightmost derivation. What can we say about these derivations if the grammar is unambiguous?
Rightmost -> replace rightmost nonterminal with righthand side of some production Leftmost -> above except left Grammar is unambiguous if left and right derivations produce the SAME parse tree
Describe the steps necessary to translate C++ source code into a running program. Assume the compiler produces assembly code as an immediate step.
Source code -> preprocessor -> rm w/ space and expand compiler -> produce object code linker ->link object code with libraries output-> program
stack frame
an activation record on the stack for a subroutine containing: args, local vars, temporaries, bookkeeping info
forward reference
an attempt to use a name before its declaration; generally an error
What does it mean for an expression to be referentially transparent?
an expression can safely be replaced by a value because it evaluates to same result regardless of context, a feature of purely functional languages
Describe the difference between applicative and normal-order evaluation
applicative-> evaluate before subroutine call normal-order-> evaluate only when value is needed
conservative v. optimistic compilers
conservative optimization->only applies when optimization is guaranteed safe and efficient optimistic compiler->always uses speculative optimization
frame pointer
a register that points to a known location within the frame of the current subroutine
production
a rule in context-free grammar
How does type coercion reduce the amount of function overloading necessary? What are the main arguments for and against it?
a single function can accept more than a single type by automatic conversion by the compiler it to a type it can use for: improves code reuse and reduces need for explicit casts against: reduces type-errors that can be caught at compile time
S-attributed grammar,
all attributes are synthesized
inheritiance
allows new classes to be defined as extensions or refinements of existing classes
semantic function
arbitrarily complex functions defined by the language designer; example (sum)
Define and explain the role of assertions.
assertions->logical assertions regarding values of program data;
How is precedence of operators established in a grammar, and how does it manifest in the parse tree?
associativity -> grammar groups left to right at same hierarchy precedence -> grammar form hierarchies that group some operations more tightly than others
Describe the difference between best-fit and first-fit heap allocation and the pros and cons of each.
best-fit->search entire list; find smallest block large enough; efficient at reserving large blocks but slow performance first-fit->find first block large enough faster; faster performance but poor space conservation both will split subblock in half if it is significantly smaller than request
Given the code int n = 5; identify 5 different binding times that occur before program execution. (There are more than that, so if you come up with more, that's OK.)
binding times: -language design time -language implementation time -program writing time -compile time -link-time (for separate compilation) -load time -runtime decisions: -static binding before runtime -dynamic binding after runtime
What is short-circuit evaluation? How does it change the semantics of a boolean expression?
boolean evaluation is skipped at the first truth for OR or the first false for AND; code is generated by the compiler to jump out; can be used for null checks or out of bounds checks GOOD: can save time on unnecessary computations; BAD if side effects for full expression are desired
shift-reduce parser
bottom up, w driver described above
Terminal
can be on righthand side; language's tokens
scanner
char stream in, tokens out
Static semantics
check at compile time
Dynamic semantics
check at runtime
Why do compilers produce more efficient code than interpreters?
compilers make decisions earlier than interpreters and can thus take advantage of more optimizations
Describe the difference between static and dynamic links in the context of resolving scopes.
static link->a frame pointer that points to parent frame; keeps track of surrounding scopes dynamic link->reference to the stack frame of the caller
Distinguish between static, stack, and heap objects.
static object -> has absolute address retained throughout program execution stack object->allocated/deallocated in LIFO in conjunction w/ subroutine calls & returns heap object->alloc/dealloc at arbitrary times; a more expensive storage management algorithm is required
Explain the difference between static & dynamic semantics.
static semantic-> compiler enforces rules at compile time dynamic semantic->compiler generates code to enforce dynamic semantics at runtime
buddy system
subblocks are powers of 2; when a block is split, its free pair's address is saved and they are joined back at dealloc if possible
Describe the difference between inherited and synthesized attributes.
synthesized attributes-> attributes whose values are calculated on the lefthand side of a production inherited attributes->attributes whose values is calculated on the righthand side of a production
Why is the code A[index_fn(i)] = A[index_fn(i)] + 1; dangerous in the presence of side effects?
the function used to return an indexing value many contain a side effect and thus may not be the same on both sides
sentential form
the strings of the steps to arrive at derivation
parser
tokens in, parse tree out
predictive parser
top down; table driven; LL; works root down
alieases
two are more names that refer to the same object at the same point in the program; overloaded names
Speculative optimization
usually improves performance but may not
Explain the difference between a value model and reference model of variables.
value model->a named location is set to a value; ex. any int var can contain the value 2 reference model->a named reference to a value—Platonic: only one value
elaboration-time constant
variables that cannot be changed after initialization, persistent