Part II — Intermediate Development · Chapter 7 · Lesson 6 of 7 · 8 min read
Lesson 6: Flow-Aware Semantic Checks and Type-Checking Commands
Lesson level: Intermediate
Purpose: Use control-flow evidence and project-wide type-checking commands to detect invalid value paths before execution.
Learning objectives
By the end of this lesson, you should be able to:
- explain flow-aware semantic analysis;
- track types and initialization across branches;
- recognize unreachable and incomplete paths;
- narrow Option and Result values after state checks;
- reason about loop and early-return effects;
- distinguish source checking from type checking;
- run file-level and project-level semantic commands;
- triage diagnostics by root cause; and
- design type-checking gates for development and automation.
6.1 Types change with proven facts
Flow-aware analysis combines declared or inferred types with facts established by control flow. Inside a branch guarded by a presence check, the checker can treat an optional value as present. After an early return excludes an invalid case, the remaining path can use the refined contract.
This refinement is local to paths where the fact is guaranteed. It does not mutate the declared type or make the fact true on unrelated branches.
6.2 Branch-sensitive narrowing
Conceptually:
let employee = find_employee(id) if employee.is_none() { return "not found" } let name: String = employee.unwrap().name
The early return removes the absent path. On the continuing path, presence has been established. If the branch did not return or otherwise terminate, the narrowing would not necessarily remain valid afterward.
6.3 Result-state refinement
A success check permits access to the success value only on the success path; an error check permits access to the error only on the failure path. After branches merge, the checker retains only facts true on every incoming path.
Handle all variants explicitly or propagate the unresolved Result. Do not assume that logging an error automatically terminates the path.
6.4 Definite assignment
A variable must receive a compatible value on every path before it is read.
let decision: String if approved { decision = "allow" } else { decision = "deny" } print decision
If a reachable branch leaves decision unassigned, the final read is unsafe. Initialize a meaningful default or assign every path.
6.5 Joining branch types
At a merge point, a binding must have a compatible type across all reachable predecessors. If one branch assigns a String and another assigns an Int, the checker reports a conflict unless the declared domain intentionally permits both.
Prefer separate variables or a structured outcome over broadening a binding to hide inconsistent meanings.
6.6 Early returns and throws
Return and throw terminate the current path. Facts established by excluding those paths can refine later code.
if quantity < 0 { throw ValueError("quantity must be nonnegative") } let total = quantity * unit_price
The continuing path proves the checked condition is false, but semantic proof of a numeric range does not replace runtime validation at external boundaries.
6.7 Reachability
Statements after an unconditional return, throw, break within the same loop path, or continue within the same iteration may be unreachable. Unreachable code can hide stale logic, mistaken branch order, or a statement placed after the wrong terminator.
Remove dead code or restructure the control flow. Do not suppress reachability diagnostics without understanding why the path cannot execute.
6.8 Loops require conservative reasoning
A loop body may execute zero times, once, or repeatedly. A value assigned only inside a pre-test loop is not definitely assigned afterward unless the checker can prove at least one iteration.
Facts established inside one iteration may be invalidated by later mutation. Keep loop-carried types stable, make invariants explicit, and avoid relying on a refinement after a variable has changed.
6.9 break and continue
continue ends the current iteration, so required updates or assignments after it do not run. break exits the loop and contributes a path to code after the loop.
When analyzing a loop, inspect every break and continue path for initialization, resource accounting, and preserved invariants.
6.10 try, catch, and finally flow
A try block may complete normally or transfer control through an exception. Catch paths must establish compatible state before execution rejoins. Finally runs for cleanup but should not disguise the original outcome with unrelated control transfer.
Variables used after the construct must be safely assigned on every continuing try/catch path. Cleanup does not prove success.
6.11 Assertions and semantic facts
An assertion may document an internal invariant and can refine the continuing path when the checker recognizes its condition. It is not a substitute for validating expected external invalidity.
Use assertions for conditions that should be impossible if the program is correct; use validation and Result for ordinary bad input.
6.12 Mutation can invalidate narrowing
If a narrowed binding can be reassigned, passed to code that mutates shared state, or changed across an asynchronous suspension, the earlier proof may no longer hold. Recheck the value or copy the proven value into a stable local binding.
Prefer const bindings for refined values when reassignment is unnecessary.
6.13 Checking commands by purpose
Use the ordinary source checker for lexical, parsing, naming, and basic source diagnostics. Use the dedicated type-checking command for annotations, inference, compatibility, generic substitution, protocols, outcome handling, definite assignment, and flow-aware analysis.
Run the exact command names and options supplied by the installed v0.63 toolchain. Confirm them from command help rather than guessing historical syntax.
6.14 File-level checking
During focused editing, type-check the smallest file or module that exercises the change. This shortens feedback and makes new diagnostics easier to associate with the current edit.
File-level success does not prove project-wide compatibility when imports, exports, protocols, or shared callers are involved.
6.15 Project-wide checking
Run project-wide semantic analysis after changing exported signatures, protocols, generic contracts, shared domain types, or module boundaries. The project check should analyze cross-module imports and consumers under one consistent configuration.
Treat a single-page result as evidence only for the analyzed scope. Record excluded modules, optional integrations, or generated sources when they are not part of the check.
6.16 A disciplined local workflow
- Format the changed source.
- Run ordinary source checks.
- Run focused type checking.
- Fix the earliest root-cause diagnostic.
- Rerun focused checking.
- Run relevant behavior tests.
- Run project-wide type checking before review.
Keep formatting, source checking, semantic checking, and tests as separate signals.
6.17 Automation gates
A non-mutating pipeline should verify formatting, source validity, semantic validity, tests, and any interpreter/VM parity required by the project. Each stage should return a nonzero status on failure and preserve machine-readable or stable diagnostic output.
Do not let CI rewrite source or silently accept a new diagnostic baseline. Review suppressions, broad types, and temporary unknowns explicitly.
6.18 Diagnostic triage
- Read the first error in source order.
- Identify its stage and code, if provided.
- Write the expected and actual types.
- Trace the expectation to its declaration or control-flow fact.
- Trace the actual type to its producer.
- Inspect reachable branches, exits, and mutations.
- Fix the narrowest root cause.
- Rerun before addressing downstream messages.
6.19 Common diagnostic groups
- undefined or duplicate names;
- assignment, argument, or return incompatibility;
- possibly unassigned binding;
- incompatible branch join;
- unsafe Option or Result access;
- missing or invalid await;
- unsatisfied generic or protocol constraint;
- unreachable statement;
- incomplete return paths; and
- cross-module contract mismatch.
6.20 Suppressions and technical debt
Suppress a diagnostic only when the project has verified that it is a false positive or an intentional temporary compatibility decision. Record the reason, owner, scope, and removal condition.
A suppression is not proof of safety. Keep runtime validation, tests, and review evidence around the affected path.
6.21 Worked flow example
Consider a function that validates a request, looks up an optional employee, and returns a typed decision. The flow should establish:
- invalid request paths return a ValidationError;
- provider failure paths return a LookupError;
- successful absence returns a not-found decision;
- only the present path accesses Employee members; and
- every reachable path returns the declared Result type.
Draw the control-flow paths and annotate the known type at each point before changing the code.
6.22 Common mistakes
- Using a refinement outside its path. Facts are branch-specific.
- Reading a conditionally assigned variable. Assign every continuing path.
- Assuming a loop runs once. Pre-test loops may run zero times.
- Ignoring mutation after narrowing. Reassignment can invalidate facts.
- Logging and continuing after an error. The path still needs a valid state.
- Treating finally as success. Cleanup does not determine the outcome.
- Checking one file after changing an export. Run project-wide analysis.
- Fixing diagnostics out of order. Downstream errors may share one cause.
- Broadening types to silence flow errors. Repair inconsistent paths.
- Using suppressions without ownership. Track and retire them.
6.23 Guided practice
- Identify the refined type after an Option presence guard.
- Explain why a refinement disappears after branches merge.
- Find the unassigned path in a three-branch decision.
- Mark unreachable statements after return and throw.
- Analyze a loop that assigns a value only in its body.
- Explain how continue skips a required update.
- Trace Result success and error facts through a conditional.
- Choose file-level or project-level checking for an exported protocol change.
6.24 Hands-on lab: Build a flow-safe employee rules module
Scenario. Prepare the typed employee-rules components for the Chapter 7 checkpoint.
Requirements
- Validate a portable employee request into a typed internal value.
- Use Result for validation and provider failures.
- Use Option for a valid lookup with no employee.
- Narrow outcomes before accessing contained values.
- Ensure every decision variable is definitely assigned.
- Use early returns to simplify invalid paths.
- Include one bounded loop and analyze break and continue paths.
- Preserve cleanup across try/catch/finally paths.
- Introduce unsafe access, missing assignment, unreachable code, incompatible joins, and missing await defects.
- Run formatting, source checks, focused type checks, project-wide type checks, and behavior tests.
- Record each diagnostic’s root cause and correction.
Acceptance criteria. Every reachable path returns the declared type; no value is read before assignment; Option and Result access is guarded; loop invariants hold; cleanup is reliable; project-wide checks pass; and no suppression lacks an owner and removal condition.
6.25 Review questions
- What makes semantic checking flow-aware?
- Where is a branch refinement valid?
- How does an early return support narrowing?
- What does definite assignment require?
- Why are loop assignments analyzed conservatively?
- How can break and continue affect post-loop state?
- Why does finally not prove success?
- When should project-wide type checking run?
- Why should diagnostics be fixed in root-cause order?
- What evidence should accompany a temporary suppression?
6.26 Applied challenge
Take a typed module from an earlier lesson and draw its control-flow graph. Annotate each binding’s known type and assignment state at every branch, loop, return, throw, and merge. Correct at least three flow weaknesses, then define a local and CI type-checking workflow for the module.
Lesson summary
Flow-aware semantic analysis refines types from proven control-flow facts, checks definite assignment, detects incompatible joins and unreachable code, and treats loops and mutation conservatively. Reliable teams separate formatting, source checking, type checking, and tests; use focused checks during editing; run project-wide analysis for shared contracts; and resolve diagnostics by root cause.
Lesson status: Ready for review.
Next: Chapter 7 Checkpoint — Typed Employee-Rules Service.