Compiler engineer: Frontends and Type Systems
Original technical interview scenarios on lexing, parsing, binding, type inference, semantic checking, lowering, diagnostics, and incremental compilation. Language-specific behavior is stated in the question.
These prompts are original practice. They are not questions from a named employer or a live hiring loop.
1.A lexer treats comment markers inside quoted strings as comments. What boundary is wrong?
Show answer and explanation
- Lexical state handling
- Longest-token preference
- Identifier scope resolution
- Token-buffer capacity
Answer: Lexical state handling
Token recognition must respect whether the scanner is inside a string.
2.A language chooses the longest valid token. Input has two adjacent greater-than characters. What must tokenization follow?
Show answer and explanation
- Shortest valid token
- Parser operator precedence
- Longest valid token
- Declaration lookup order
Answer: Longest valid token
Token boundaries follow the specified lexical rule.
3.A scanner reports byte offsets but the editor expects Unicode code-point offsets. What must be reconciled?
Show answer and explanation
- Tab width
- Identifier normalization
- Offset encoding
- Line-ending conversion
Answer: Offset encoding
Different offset units can point diagnostics to the wrong text.
4.A source character occupies three UTF-8 bytes. Advancing one byte for each displayed character causes what risk?
Show answer and explanation
- Token loss
- Changed identifier equivalence
- Incorrect literal range
- Incorrect source locations
Answer: Incorrect source locations
Byte and character positions are not interchangeable.
5.A lexer drops all whitespace, but indentation is syntactic in the language. What is missing?
Show answer and explanation
- Type constraints
- Declaration dependencies
- Structural tokens
- Unicode normalization
Answer: Structural tokens
Syntactically meaningful indentation must survive tokenization.
6.A numeric token is accepted before its suffix is checked. What should validation distinguish?
Show answer and explanation
- Token count
- One valid token accepted at every numeric type
- Suffix spelling alone
- Lexical and type validity
Answer: Lexical and type validity
Valid spelling does not establish every semantic rule.
7.A parser builds identical trees for a+b*c and (a+b)*c despite normal precedence. What is wrong?
Show answer and explanation
- Token splitting
- Function overload selection
- Identifier shadowing
- Operator grouping
Answer: Operator grouping
The parse tree must preserve the language's precedence and parentheses.
8.Under ordinary multiplication precedence, what is 2+3*4?
Show answer and explanation
- 9
- 14
- 24
- 20
Answer: 14
Multiplication gives twelve, then addition gives fourteen.
9.A subtraction operator is left-associative. What is 10-3-2?
Show answer and explanation
- 9
- 7
- 5
- 15
Answer: 5
The grouping is (10-3)-2, giving five.
10.An exponent operator is right-associative. What is 2^(3^2)?
Show answer and explanation
- 64
- 16
- 512
- 32
Answer: 512
3 squared is nine; two to the ninth is 512.
11.A recursive-descent parser directly implements left-recursive E→E+T. What problem can result?
Show answer and explanation
- Premature EOF
- Repeated recognition that always consumes input
- Unbounded recursion
- Incorrect operator precedence only
Answer: Unbounded recursion
The parser recurses without first consuming input.
12.A parser factors a grammar. What must remain preserved?
Show answer and explanation
- Language and interpretation
- Production names
- The number of syntax nodes in every parse
- The source's whitespace layout
Answer: Language and interpretation
Grammar changes should preserve intended recognition and semantics.
13.Two grammar alternatives share a long prefix. What may help predictive parsing?
Show answer and explanation
- More productions alone
- Choosing the first matching prefix without a rule
- Factoring or suitable lookahead
- Ignoring lookahead conflicts
Answer: Factoring or suitable lookahead
Parsing needs a valid way to choose among alternatives.
14.An error-recovery parser skips until a synchronization token. What must it avoid?
Show answer and explanation
- Retaining error spans
- Producing explicit recoverable syntax nodes
- Reporting the initial source error
- Recovery without progress
Answer: Recovery without progress
Recovery must make progress and preserve useful parsing state.
15.A missing delimiter creates twenty cascading errors. What improvement is useful?
Show answer and explanation
- Context-aware recovery
- Suppress every error
- Treat the missing token as proof all later tokens are valid
- Disable semantic checking
Answer: Context-aware recovery
Recovery can reduce secondary errors while preserving the primary problem.
16.A parser inserts a synthetic closing token. What should diagnostics retain?
Show answer and explanation
- An ordinary source token
- A fabricated source offset claiming the token was written
- The next identifier's binding
- Synthetic-token provenance
Answer: Synthetic-token provenance
Recovery artifacts should not be confused with actual input.
17.An AST omits parentheses after parsing. When is that sound?
Show answer and explanation
- Whenever punctuation is absent
- Only if every expression operator is associative
- When the tree preserves their grouping effect
- Whenever the AST has fewer nodes
Answer: When the tree preserves their grouping effect
An AST can encode grouping without retaining punctuation nodes.
18.A formatter needs comments discarded by the compiler AST. What representation may help?
Show answer and explanation
- A typed symbol table
- A semantic AST that permanently discarded comments
- Source-preserving syntax
- A control-flow graph
Answer: Source-preserving syntax
Source-preserving tools often need syntax omitted by semantic ASTs.
19.A parser accepts a name not yet declared. What later phase may reject it?
Show answer and explanation
- Tokenization
- Precedence resolution
- Constant range checking
- Name resolution
Answer: Name resolution
Parsing recognition and resolving identifiers are distinct tasks.
20.A nested block declares x over an outer x. What must lookup respect?
Show answer and explanation
- Lexical scope and shadowing
- Textual sorting
- The first declaration found anywhere in the file
- Runtime allocation order
Answer: Lexical scope and shadowing
Lookup follows the language's scoping rules.
21.A language permits forward function references. What frontend structure can support them?
Show answer and explanation
- A declaration pass
- Immediate code emission
- Rejecting all names declared after their first use
- Lookup by textual name length
Answer: A declaration pass
A declaration pass can make permitted names available before bodies are checked.
22.Two modules export the same unqualified name. What should resolution do?
Show answer and explanation
- First import wins silently
- Choose whichever module compiled first
- Defined ambiguity handling
- Prefer the larger function body
Answer: Defined ambiguity handling
Name lookup must follow defined rules rather than incidental ordering.
23.A symbol table keys names but ignores scope identity. What bug can appear?
Show answer and explanation
- Duplicate token spans
- Guaranteed correct separation of same-spelled bindings
- Unrelated declarations collide
- Ambiguous operator precedence
Answer: Unrelated declarations collide
The same spelling can denote distinct declarations in different scopes.
24.A renamed local variable changes program behavior without reflection. What property may have failed?
Show answer and explanation
- Text replacement count
- Binding preservation
- Layout-preserving pretty printing
- Literal-value preservation
Answer: Binding preservation
Renaming must preserve which declaration each use denotes.
25.A macro introduces tmp and captures the caller's tmp accidentally. What is needed?
Show answer and explanation
- Fresh register names
- A distinct generated spelling without binding guarantees
- More parser lookahead
- Hygienic binding treatment
Answer: Hygienic binding treatment
Macro expansion should respect the intended binding relationships.
26.A macro error points only into generated code. What can improve diagnostics?
Show answer and explanation
- Expansion origin tracking
- AST node count
- A generated temporary name without its expansion chain
- Overload ranking
Answer: Expansion origin tracking
Tracking expansion and call-site context helps users locate the source cause.
27.A type checker accepts every syntactically valid expression. What is missing?
Show answer and explanation
- Delimiter matching
- Semantic type constraints
- The longest-token rule as a complete semantic check
- Source-range consistency
Answer: Semantic type constraints
Syntax alone does not establish well-typed operations.
28.A supplied language forbids adding integers and strings. What should x:int plus y:string produce?
Show answer and explanation
- A type error
- An integer sum
- Implicit concatenation despite the supplied prohibition
- An unspecified runtime conversion
Answer: A type error
The stated typing rule rejects the incompatible operands.
29.A language implicitly widens int16 to int32 but never narrows implicitly. What requires an explicit operation?
Show answer and explanation
- int32 to int16 conversion
- Using an int16 variable
- Widening int16 to int32 under the supplied rule
- Returning a valid int32 constant
Answer: int32 to int16 conversion
The supplied rule permits widening but not implicit narrowing.
30.An implicit conversion may invoke user code. What must lowering preserve?
Show answer and explanation
- Only the final value type
- Evaluation semantics
- A conversion label without its observable user-code effects
- The declared parameter count
Answer: Evaluation semantics
A conversion can be observable, not merely a type annotation.
31.An overload set has two equally preferred candidates. What should the frontend do?
Show answer and explanation
- Choose the first declaration
- Report ambiguity under the rules
- Prefer the larger return type without a ranking rule
- Defer an arbitrary choice to runtime
Answer: Report ambiguity under the rules
Overload resolution must follow defined ranking and ambiguity rules.
32.A function's expected type influences argument inference. What style of checking may be useful?
Show answer and explanation
- Token-only parsing
- Bidirectional checking
- Unidirectional synthesis with no expected-type information
- Source-text substitution
Answer: Bidirectional checking
Information can flow from expected types as well as synthesized expression types.
33.Unification requires a type variable to equal List of itself, in a system without recursive types. What should occur?
Show answer and explanation
- An occurs-check failure
- Successful unification with T=int
- A valid finite substitution obtained by endless expansion
- Automatic recursive-type creation
Answer: An occurs-check failure
The supplied type system rejects an infinite recursive substitution.
34.A substitution maps A to B and B to int. What should applying it transitively to A yield?
Show answer and explanation
- A
- int
- B without further substitution
- bool
Answer: int
Following the substitutions reaches int.
35.A type solver repeatedly revisits constraints without changing state. What engineering property is missing?
Show answer and explanation
- More type names
- Revisiting unchanged constraints without convergence rules
- Solver progress
- A larger diagnostic limit
Answer: Solver progress
Constraint solving needs a defined convergence or failure strategy.
36.A generic function is instantiated at incompatible types. What should checking verify?
Show answer and explanation
- Function spelling
- Only the first instantiated use as proof every use is valid
- Instantiation constraints
- Declaration order alone
Answer: Instantiation constraints
Generic validity depends on its rules and actual type arguments.
37.A language uses nominal types. Two records have identical fields but different declared identities. Are they automatically equal types?
Show answer and explanation
- Yes; equal layout establishes nominal identity.
- Yes; matching fields removes distinct declaration identities.
- No; all nominal record types are incompatible with themselves.
- No; nominal identity matters.
Answer: No; nominal identity matters.
Nominal and structural equivalence use different criteria.
38.A language uses structural record typing. What is relevant to compatibility?
Show answer and explanation
- Required type structure
- Declaration spelling
- The order in which equivalent records were declared
- Module filename alone
Answer: Required type structure
Structural systems compare relevant shape and types rather than names alone.
39.A function returns int, but one reachable branch returns a string under strict rules. What is appropriate?
Show answer and explanation
- Select the first return type silently.
- Ignore a reachable branch because another returns int.
- Convert the string without a permitted conversion rule.
- Check return compatibility.
Answer: Check return compatibility.
Reachable branches must satisfy the language's return typing rules.
40.A definite-assignment analysis sees a local initialized on only one branch. What must it check before later use?
Show answer and explanation
- Definition on all paths
- One assignment anywhere
- The last assignment in source order regardless of control flow
- The local's declared name
Answer: Definition on all paths
A later read requires the property on all relevant paths.
41.Both branches initialize a variable before a join. What should a must-analysis combine?
Show answer and explanation
- Facts true on all paths
- Facts from either path
- Facts from the first branch without the second
- Facts from the shorter branch
Answer: Facts true on all paths
Must properties require agreement across incoming paths.
42.A branch is unreachable under the language's constant-condition rules. What should semantic checking follow?
Show answer and explanation
- The optimizer's preference
- An assumption unreachable code is exempt from every source check
- The parser's success alone
- Source checking rules
Answer: Source checking rules
Languages differ in which checks still apply to unreachable source.
43.A pattern match omits one constructor of a closed sum type. What can exhaustiveness analysis report?
Show answer and explanation
- A duplicate binding
- A missing case
- An automatically inserted default constructor
- A type alias cycle
Answer: A missing case
Closed alternatives support checking that all possible constructors are covered.
44.Two match arms overlap and the first always handles the second's pattern. What can be reported?
Show answer and explanation
- A type-generalization error
- A missing source delimiter
- A required additional constructor
- An unreachable or redundant arm
Answer: An unreachable or redundant arm
Pattern ordering can make later alternatives impossible to select.
45.A wildcard arm precedes all specific arms. What should analysis consider?
Show answer and explanation
- The wildcard's spelling
- Whether later arms can ever match
- The number of constructors without considering arm order
- Only the final arm's return type
Answer: Whether later arms can ever match
A catch-all earlier arm may subsume later patterns.
46.A nullability checker sees a value tested for nonnull then reassigned. What should happen to the refinement?
Show answer and explanation
- Keep it after reassignment.
- Treat every later value of that name as nonnull.
- Erase the assignment from semantic analysis.
- Invalidate the stale fact.
Answer: Invalidate the stale fact.
Refinements depend on facts that assignments can change.
47.A refinement relies on a mutable field across an unknown call. What should be assessed?
Show answer and explanation
- The call's arity
- A purity assumption inferred solely from a short function name
- The statement's indentation
- Possible state changes
Answer: Possible state changes
Unknown side effects may change the relevant state.
48.A frontend marks a call pure without justification. What risk arises downstream?
Show answer and explanation
- Only missed optimization
- Guaranteed safe removal of every call with an unused result
- A source-location mismatch alone
- Unsound reordering or elimination
Answer: Unsound reordering or elimination
Incorrect effect information can authorize invalid transformations.
49.A language specifies left-to-right argument evaluation. What must lowering preserve?
Show answer and explanation
- Operand sorting
- A target-dependent argument order
- Only final argument values regardless of effects
- Observable evaluation order
Answer: Observable evaluation order
Side effects in arguments can make evaluation order observable.
50.The language short-circuits logical and. What should lowering avoid?
Show answer and explanation
- Type-checking required operands
- Evaluating the right operand unconditionally
- Representing the condition as explicit control flow
- Tracking locations through lowering
Answer: Evaluating the right operand unconditionally
The right operand's runtime effects depend on the left operand.
51.A source language traps on division by zero. What must constant evaluation do for 4/0?
Show answer and explanation
- Required zero-division behavior
- IEEE infinity
- An arbitrary constant chosen to avoid executing a trap
- Unsigned saturation
Answer: Required zero-division behavior
Compile-time evaluation must respect source semantics and required diagnostics.
52.A supplied language uses 8-bit unsigned wrapping arithmetic. What is 250+10?
Show answer and explanation
- 4
- 255
- 260
- 0
Answer: 4
260 modulo 256 equals four.
53.A supplied language adds 250+10 using checked unsigned 8-bit arithmetic that traps on overflow. What must lowering preserve instead of silently wrapping to four?
Show answer and explanation
- Wrap to four unconditionally.
- Saturate to 255 regardless of the checked rule.
- Preserve overflow behavior.
- Treat overflow checking as debug metadata only.
Answer: Preserve overflow behavior.
Different source arithmetic semantics require different evaluation behavior.
54.A constant evaluator uses host-width integers for target-width operations. What must be enforced?
Show answer and explanation
- The host's width alone
- The literal's decimal spelling without target semantics
- Target arithmetic rules
- The build machine's endianness only
Answer: Target arithmetic rules
Host arithmetic is not automatically the target language's arithmetic.
55.A target integer is signed 8-bit two's complement. What is its maximum value?
Show answer and explanation
- 128
- 127
- 256
- 255
Answer: 127
Seven magnitude bits give a maximum of 2^7 minus one.
56.A target unsigned 16-bit integer has what maximum?
Show answer and explanation
- 65,535
- 32,767
- 65,536
- 131,071
Answer: 65,535
2^16 minus one equals 65,535.
57.A language allows arbitrary-precision literals before contextual conversion. What should parsing avoid?
Show answer and explanation
- Host-width truncation
- Retaining literal spelling
- Keeping an exact value until contextual conversion
- Deferring type-specific range checks
Answer: Host-width truncation
The frontend may need to represent values larger than host machine integers.
58.A literal is valid text but out of range for its required type. What phase must address this?
Show answer and explanation
- Identifier lookup
- Semantic range checking
- Delimiter balancing without evaluating numeric range
- Overload name collection
Answer: Semantic range checking
A valid token can still violate the required value range.
59.A frontend desugars a loop with continue. What must be preserved?
Show answer and explanation
- The continue destination
- The source block count
- The closest textual label rather than the specified target
- The original variable spelling only
Answer: The continue destination
Desugaring must maintain the source control-flow behavior.
60.A cleanup must run on both normal return and exception. What should lowering represent?
Show answer and explanation
- The normal return only
- All cleanup exits
- The last textual return without exceptional edges
- Only explicit source cleanup calls
Answer: All cleanup exits
Observable cleanup semantics need explicit correct lowering.
61.A closure captures a variable by reference. What must representation preserve?
Show answer and explanation
- Shared storage and lifetime
- Only the initial value
- A fresh independent copy for each read
- The variable's source spelling
Answer: Shared storage and lifetime
Reference capture differs from copying a value at creation time.
62.A closure outlives its stack frame. What must escape analysis consider?
Show answer and explanation
- Lexical scope alone
- Captured storage lifetime
- A guarantee the original stack storage always remains alive
- The closure's syntax length
Answer: Captured storage lifetime
Captured data must remain valid for all permitted uses.
63.A type alias is transparent under supplied rules. What should equivalence do?
Show answer and explanation
- Resolve the alias.
- Create a new nominal identity.
- Compare alias names rather than underlying types.
- Treat all aliases as unknown types.
Answer: Resolve the alias.
Transparent aliases denote the underlying type under those rules.
64.An opaque type hides representation across a module boundary. What must checking respect?
Show answer and explanation
- Representation hiding
- The hidden field layout
- The client's preferred representation assumptions
- The optimizer's convenience
Answer: Representation hiding
Clients cannot assume hidden representation properties without authority.
65.A compiler caches type results by filename only. What can invalidate correctness?
Show answer and explanation
- Changed semantic inputs
- An unchanged path alone
- A guarantee semantic results depend only on filenames
- The cache's output directory
Answer: Changed semantic inputs
Semantic results depend on more than a path label.
66.A dependency changes an exported type. What should incremental checking revisit?
Show answer and explanation
- Unrelated modules only
- The changed module's comments instead of interface users
- No dependent semantic result
- Affected dependents
Answer: Affected dependents
Dependent semantic results may be stale after interface changes.
67.A cache key ignores language-version flags. What risk arises?
Show answer and explanation
- Guaranteed reuse validity
- A source-spelling difference with identical semantics in every mode
- Stale semantic results
- Only slower cache lookup
Answer: Stale semantic results
Language options can alter parsing and typing rules.
68.An IDE requests partial results while code is incomplete. What design helps?
Show answer and explanation
- Assume every missing token is valid.
- Wait for a complete executable before returning any information.
- Recoverable partial syntax
- Suppress all known semantic facts during editing.
Answer: Recoverable partial syntax
Interactive tools need useful partial information without false certainty.
69.An error type is propagated after an initial failure. What is its purpose?
Show answer and explanation
- Prove successful typing
- Limit cascades while continuing analysis
- Replace every runtime type with a universal valid type
- Remove the original diagnostic
Answer: Limit cascades while continuing analysis
Error recovery can continue useful checking without treating errors as valid types.
70.A diagnostic says only 'bad type.' What improves it?
Show answer and explanation
- A larger numeric code
- The mismatch and its location
- The compiler version without the expected and actual types
- An internal memory address
Answer: The mismatch and its location
Actionable diagnostics explain the mismatch and where it arises.
71.A suggested fix changes semantics beyond the reported error. What should tooling avoid?
Show answer and explanation
- Showing source context
- Describing the proposed edit's limitations
- Offering a reviewable change
- Claiming semantic safety
Answer: Claiming semantic safety
Fix suggestions should not overstate semantic safety.
72.An error points at a generated temporary. What helps users?
Show answer and explanation
- Source provenance
- The temporary's register
- A machine offset without any expansion or source mapping
- The generated node count
Answer: Source provenance
Source mappings connect lowered constructs to user-written code.
73.A source span starts at byte 10 and ends at byte 16, end-exclusive. What is its length?
Show answer and explanation
- 26 bytes
- 5 bytes
- 6 bytes
- 7 bytes
Answer: 6 bytes
16 minus ten equals six under the stated interval convention.
74.A parser assumes every source buffer ends with a real newline. What should be tested?
Show answer and explanation
- Only newline-terminated inputs
- End-of-file without that newline
- Only files with extra trailing blank lines
- Only already successful parse trees
Answer: End-of-file without that newline
Boundary cases can reveal invalid scanner or parser assumptions.
75.A parser accepts a prefix and ignores remaining tokens. What check is missing?
Show answer and explanation
- Return-type inference
- A balanced delimiter count without remaining-token checks
- Full-input recognition
- Duplicate-name checking
Answer: Full-input recognition
Successful partial recognition does not establish that the entire input is valid.
76.An ambiguous grammar has multiple valid parse trees. What must the language implementation define?
Show answer and explanation
- Source-order accident
- A random tree selected independently for each compilation
- Defined disambiguation
- The shorter syntax tree by default
Answer: Defined disambiguation
Ambiguity needs a specified interpretation rather than accidental behavior.
77.A parser uses unlimited backtracking on adversarial input. What engineering risk arises?
Show answer and explanation
- Automatic linear complexity
- Guaranteed termination from recursive implementation alone
- Excessive resource use
- Only additional source metadata
Answer: Excessive resource use
Recognition strategy can have serious complexity consequences.
78.A memoizing parser caches by rule and position. What other context may matter if parsing is context-sensitive?
Show answer and explanation
- Only rule and offset
- The output filename instead of state affecting recognition
- The final symbol count
- Relevant parse context
Answer: Relevant parse context
Memoization is sound only when the key captures inputs that affect the result.
79.A name resolver mutates a shared scope table during parallel compilation. What must be ensured?
Show answer and explanation
- Average execution speed
- A guarantee unsynchronized maps cannot affect binding
- Race-free binding behavior
- File order alone
Answer: Race-free binding behavior
Concurrency must not change bindings or corrupt shared state.
80.An identifier's identity is represented only by a raw pointer into a movable buffer. What risk arises?
Show answer and explanation
- Guaranteed stable interning
- Invalidated references
- Automatic ownership transfer when the buffer moves
- Only slower name comparison
Answer: Invalidated references
Storage movement can invalidate pointer-based identities.
81.A string interner returns stable identifiers. What must equality preserve?
Show answer and explanation
- Allocation order
- The source line as the sole identity of every use
- Pointer ordering across unrelated buffers
- Identifier equivalence
Answer: Identifier equivalence
Interning should preserve the language's name-equivalence rules.
82.A language normalizes Unicode names. What must all frontend phases agree on?
Show answer and explanation
- Tab display width
- Name-equivalence rules
- Different normalization rules in lexing and lookup
- Only case in output filenames
Answer: Name-equivalence rules
Inconsistent normalization can make lookup disagree with token recognition.
83.A parser's token stream contains an invalid escape in a string. What should happen?
Show answer and explanation
- Delete the invalid character silently.
- Treat every malformed escape as an ordinary character.
- Defer the lexical issue to binary loading.
- A relevant diagnostic under lexical rules
Answer: A relevant diagnostic under lexical rules
Invalid escapes need handling according to the language specification.
84.A frontend accepts a construct only in language version 3. What should version 2 mode do?
Show answer and explanation
- Version-specific rules
- Accept all newer syntax silently.
- Switch the language mode without notifying the user.
- Use runtime version as the source grammar rule.
Answer: Version-specific rules
Language mode is part of the compilation contract.
85.A generic constraint depends on another type parameter. What should solving preserve?
Show answer and explanation
- Alphabetical ordering
- Only the first parameter's independent constraints
- The declaration's source length
- Constraint dependencies
Answer: Constraint dependencies
Interdependent constraints cannot be checked as unrelated facts.
86.A type inference result depends on hash-map iteration order. What should be investigated?
Show answer and explanation
- Only diagnostic formatting
- A presumption hash iteration defines the language's inference rules
- Unstable solver ordering
- The table's capacity alone
Answer: Unstable solver ordering
Incidental container order should not decide language semantics.
87.A language permits recursive functions but requires explicit recursive value declarations. What must the frontend distinguish?
Show answer and explanation
- Identifier spelling alone
- An assumption both constructs share one initialization rule
- The runtime's recursion depth
- Distinct binding rules
Answer: Distinct binding rules
Different source constructs can have different binding and initialization rules.
88.A compile-time function reads the host clock without language authorization. What concern arises?
Show answer and explanation
- Unauthorized nondeterminism
- Guaranteed reproducibility
- Automatic target portability from using the host clock
- A harmless diagnostic-only change
Answer: Unauthorized nondeterminism
Constant evaluation should obey the defined environment and effects.
89.A target uses big-endian layout but the frontend folds a byte reinterpretation using host little-endian layout. What is wrong?
Show answer and explanation
- Source encoding
- A correct target fold merely because it runs on the host
- Identifier normalization
- Wrong target layout
Answer: Wrong target layout
Target-dependent operations must use target layout.
90.A frontend attaches a nonnull guarantee to a possibly null pointer. What risk arises?
Show answer and explanation
- Only fewer optimization opportunities
- A runtime null check inserted automatically by the annotation
- A source formatting difference
- Unsound semantic guarantees
Answer: Unsound semantic guarantees
Semantic annotations must be justified by the source program and rules.
91.A diagnostic cache stores source offsets but not source version. What can happen?
Show answer and explanation
- Stale source highlighting
- Guaranteed current spans
- Automatic document-version reconstruction from the path
- Only slower diagnostics
Answer: Stale source highlighting
Offsets need association with the source revision they describe.
92.A refactoring renames a declaration but misses one shadowed use. What should validation check?
Show answer and explanation
- Text-match count
- Binding identity
- Replacing every occurrence of the same character sequence
- The file's byte length
Answer: Binding identity
Correct refactoring tracks declarations and uses semantically.
93.A parser recursion limit rejects a deeply nested but valid file. What should diagnostics make clear?
Show answer and explanation
- A fabricated language restriction
- A resource-limit diagnostic
- A division error in the user's runtime program
- An unresolved imported name
Answer: A resource-limit diagnostic
An implementation limit should not be misrepresented as a different semantic violation.
94.A compiler consumes untrusted source. What frontend property matters?
Show answer and explanation
- Fast valid-input parsing only
- Robust resource limits
- A guarantee correct syntax prevents every resource attack
- Only the longest supported identifier
Answer: Robust resource limits
Malformed and adversarial inputs require safe handling.
95.A type checker crashes on an unknown identifier. What should replace the crash?
Show answer and explanation
- An arbitrary valid type
- Silent executable generation after failed lookup
- Controlled error recovery
- An error attributed to register allocation
Answer: Controlled error recovery
Source errors should not become uncontrolled compiler failures.
96.A source-level test checks only error text but not highlighted span. What can it miss?
Show answer and explanation
- Whether the error occurred
- Wrong source highlighting
- The diagnostic's source attribution already proven by its text
- Only executable size
Answer: Wrong source highlighting
Diagnostic correctness includes useful source attribution.
97.A parser change preserves acceptance but changes AST associativity. What must be tested?
Show answer and explanation
- Accepted file count alone
- Token spelling without the expression tree
- Expression grouping
- The build duration
Answer: Expression grouping
Equivalent recognition alone does not prove equivalent interpretation.
98.A frontend lowering duplicates an expression with side effects. What can change?
Show answer and explanation
- Evaluation count
- Only source layout
- Only the spelling of generated temporary names
- The type name without evaluating effects
Answer: Evaluation count
Duplicated effects can change program meaning.
99.An AST verifier checks structure but not type invariants. What additional assurance is needed?
Show answer and explanation
- Node counts
- Additional syntax-only validation
- Serialization layout checks
- Type-invariant checks
Answer: Type-invariant checks
Different verification layers establish different properties.
100.A supplied language captures local variables by reference. Code sets x=3, creates f as a closure returning x, then assigns x=8 before calling f. The variable remains alive. Which result must equivalent lowering produce?
Show answer and explanation
- 3, copied when the closure was created
- 8, from the shared captured variable
- 0, from a fresh variable allocated at the call
- A type error because every captured variable must be immutable
Answer: 8, from the shared captured variable
Reference capture observes the same variable storage. The later assignment changes that storage to eight; snapshotting the creation-time value would implement different semantics.
101.A language gives pure let-bound functions polymorphic types and freshly instantiates each use. let
choose(v)=v. What type should checking assign to pair(choose(7),choose(false)), where 7:int and false:bool and pair preserves argument types?Show answer and explanation
- pair<int, int>
- pair<int, bool>
- pair<bool, bool>
- A type error from forcing both uses to share one type variable
Answer: pair<int, bool>
Each use gets a fresh instantiation of the identity function: int→int and bool→bool. Sharing one unresolved type variable across both uses would incorrectly make the two argument types conflict.