Study guides · Introductory

Syntax, semantics, and types: separate three kinds of correctness

Distinguish grammatical structure, execution meaning, and type constraints, then separate static analysis from runtime checks.

Ask Logeia about this articleTry the three questionsReview your answers

Updated

On this page
  1. Syntax defines legal structure
  2. Semantics assigns meaning to that structure
  3. Types constrain how values are used
  4. Keep application contracts visible
  5. Trace an external input boundary
  6. Trace one expression through four stages
  7. Locate the rejection boundary for each input
  8. Inference does not convert external data
  9. Choose the next reading from the question
  10. Ask Logeia about this articleCheck your understanding

Syntax defines legal structure

Syntax specifies how tokens and expressions can be arranged into a program. An expression with an unmatched parenthesis violates that structure. Parsing turns the input into a representation in which relationships such as a function call on the left side of an addition are explicit. Passing a parser does not establish that the program computes its intended result. Grammatical validity and behavioral correctness answer different questions.

Semantics assigns meaning to that structure

The same familiar notation can behave differently across languages. Dividing two integers might produce an integer in one language and a noninteger numeric value in another. Assignment, evaluation order, and exceptions also belong to the meaning of a program. Small experiments can help reveal a rule, but one successful execution is not a language specification. Check the documented guarantees before relying on behavior across implementations or versions.

Types constrain how values are used

Types classify values and restrict operations in ways that can detect some inconsistencies statically or dynamically. A checker may reject passing a string to a function that expects an integer. In ordinary Python execution, annotations alone do not enforce runtime validation, however. Data arriving from a network can violate the assumptions expressed by a type hint. Validate that boundary explicitly, then ensure that the internal type describes the values the validator actually accepts.

Keep application contracts visible

A return type of integer does not by itself prove that an inventory count is nonnegative, that a user is authorized, or that a network operation succeeded. More expressive type systems can encode some additional properties, but the guarantees depend on the language and on how the program is written. Combine parsing, type checking, runtime validation, and behavioral tests with a clear account of their responsibilities. A well-typed program can still implement the wrong business rule or rely on an external service that fails.

Trace an external input boundary

Annotating a value named age as an integer does not automatically convert or reject the JSON string "18" in ordinary Python execution. Decide whether conversion is permitted and what numeric range the input contract accepts. Implement that decision in a runtime validator, then pass a validated value into the typed internal logic. This separates the promise expressed to a checker from evidence that an external value actually meets the promise.

Trace one expression through four stages

Take the tiny expression 2+x*3 with x equal to four. Lexing produces an integer, plus, identifier, multiplication symbol, integer, and end marker. Parsing groups it as 2+(x*3) under the language's precedence rules. The root is addition and its right child is multiplication. Whitespace alone does not define that structure.

Evaluation reads four from the value environment, computes twelve, then fourteen. The tree alone is insufficient; evaluation also needs an environment and operation rules. Type checking instead starts from a type environment containing x:Int and concludes that the whole expression has type Int. The value four and the type Int are different information. Computing a type is not another name for computing the concrete result fourteen.

StageInput or assumptionResult in this example
Lexing2+x*3Numbers, operators, name, end marker
ParsingMultiplication precedes additionStructure 2+(x*3)
Type checkingx:IntExpression has type Int
Evaluationx=414

Locate the rejection boundary for each input

Changing the input to 2+ leaves a missing right operand and violates the grammar. Changing it to 2+y*3 can preserve syntax while failing name resolution if y is absent. In a separately defined typed-expression model, 2+true fails the integer-addition rule. The first executable tiny language has no Boolean syntax, however; do not confuse the conceptual type model with the implemented grammar.

With division, 1/0 can have integer operands yet fail during evaluation. Compatible types do not guarantee normal termination. Instead of labeling every case simply invalid, identify the missing grammatical, naming, typing, or value precondition. That distinction also helps design useful application errors and developer diagnostics without pretending that one check establishes all kinds of correctness.

Inference does not convert external data

Type inference collects constraints to determine omitted types under a defined rule set. It does not convert external strings into convenient numbers. Knowing x:Int in a type environment leaves the separate responsibility of validating JSON before relying on that assumption. The contract must decide whether numeric 18, textual "18", or true is acceptable.

An age contract accepting integers from zero through 130 needs a range check in addition to any conversion. In Python, deliberately decide whether bool is permitted rather than relying accidentally on its relationship to integers. Typing the validated internal value, rejecting external input, and displaying an error each serve different roles. Explain the boundary using a concrete accepted and rejected value after introducing the type concept.

Choose the next reading from the question

For text-to-tree work, continue through the lexing/parsing guide, lexer experiment, and recursive-descent parser. For tree-to-value rules, use the AST evaluator. For type constraints, combine the type-checking/inference guide with subtyping and variance. Closures use a separate executable example to study how a function retains access to an enclosing environment.

Record tokens, tree, type assumptions, and result or failure for the same input. When moving to constant folding, compare both successful results and failure behavior before and after transformation. A shorter tree is not sufficient evidence of equivalent meaning. The three distinctions in this overview become shared vocabulary for following each implementation stage rather than isolated definitions to memorize.

Reading and practice are recorded separately in this browser, for each language.

Learn this in order

Build your CS foundations · STEP 19

Choose a learning path