PeaBox Lab › PeaLang › Learn › Chapter 7 › Lesson 6

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:

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

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

6.19 Common diagnostic groups

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:

Draw the control-flow paths and annotate the known type at each point before changing the code.

6.22 Common mistakes

6.23 Guided practice

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

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

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.

← Previous Next →