1<!--===- docs/Semantics.md
2
3   Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4   See https://llvm.org/LICENSE.txt for license information.
5   SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
7-->
8
9# Semantic Analysis
10
11The semantic analysis pass determines if a syntactically correct Fortran
12program is is legal by enforcing the constraints of the language.
13
14The input is a parse tree with a `Program` node at the root;
15and a "cooked" character stream, a contiguous stream of characters
16containing a normalized form of the Fortran source.
17
18The semantic analysis pass takes a parse tree for a syntactically
19correct Fortran program and determines whether it is legal by enforcing
20the constraints of the language.
21
22If the program is not legal, the results of the semantic pass will be a list of
23errors associated with the program.
24
25If the program is legal, the semantic pass will produce a (possibly modified)
26parse tree for the semantically correct program with each name mapped to a symbol
27and each expression fully analyzed.
28
29All user errors are detected either prior to or during semantic analysis.
30After it completes successfully the program should compile with no error messages.
31There may still be warnings or informational messages.
32
33## Phases of Semantic Analysis
34
351. [Validate labels](#validate-labels) -
36   Check all constraints on labels and branches
372. [Rewrite DO loops](#rewrite-do-loops) -
38   Convert all occurrences of `LabelDoStmt` to `DoConstruct`.
393. [Name resolution](#name-resolution) -
40   Analyze names and declarations, build a tree of Scopes containing Symbols,
41   and fill in the `Name::symbol` data member in the parse tree
424. [Rewrite parse tree](#rewrite-parse-tree) -
43   Fix incorrect parses based on symbol information
445. [Expression analysis](#expression-analysis) -
45   Analyze all expressions in the parse tree and fill in `Expr::typedExpr` and
46   `Variable::typedExpr` with analyzed expressions; fix incorrect parses
47   based on the result of this analysis
486. [Statement semantics](#statement-semantics) -
49   Perform remaining semantic checks on the execution parts of subprograms
507. [Write module files](#write-module-files) -
51   If no errors have occurred, write out `.mod` files for modules and submodules
52
53If phase 1 or phase 2 encounter an error on any of the program units,
54compilation terminates. Otherwise, phases 3-6 are all performed even if
55errors occur.
56Module files are written (phase 7) only if there are no errors.
57
58### Validate labels
59
60Perform semantic checks related to labels and branches:
61- check that any labels that are referenced are defined and in scope
62- check branches into loop bodies
63- check that labeled `DO` loops are properly nested
64- check labels in data transfer statements
65
66### Rewrite DO loops
67
68This phase normalizes the parse tree by removing all unstructured `DO` loops
69and replacing them with `DO` constructs.
70
71### Name resolution
72
73The name resolution phase walks the parse tree and constructs the symbol table.
74
75The symbol table consists of a tree of `Scope` objects rooted at the global scope.
76The global scope is owned by the `SemanticsContext` object.
77It contains a `Scope` for each program unit in the compilation.
78
79Each `Scope` in the scope tree contains child scopes representing other scopes
80lexically nested in it.
81Each `Scope` also contains a map of `CharBlock` to `Symbol` representing names
82declared in that scope. (All names in the symbol table are represented as
83`CharBlock` objects, i.e. as substrings of the cooked character stream.)
84
85All `Symbol` objects are owned by the symbol table data structures.
86They should be accessed as `Symbol *` or `Symbol &` outside of the symbol
87table classes as they can't be created, copied, or moved.
88The `Symbol` class has functions and data common across all symbols, and a
89`details` field that contains more information specific to that type of symbol.
90Many symbols also have types, represented by `DeclTypeSpec`.
91Types are also owned by scopes.
92
93Name resolution happens on the parse tree in this order:
941. Process the specification of a program unit:
95   1. Create a new scope for the unit
96   2. Create a symbol for each contained subprogram containing just the name
97   3. Process the opening statement of the unit (`ModuleStmt`, `FunctionStmt`, etc.)
98   4. Process the specification part of the unit
992. Apply the same process recursively to nested subprograms
1003. Process the execution part of the program unit
1014. Process the execution parts of nested subprograms recursively
102
103After the completion of this phase, every `Name` corresponds to a `Symbol`
104unless an error occurred.
105
106### Rewrite parse tree
107
108The parser cannot build a completely correct parse tree without symbol information.
109This phase corrects mis-parses based on symbols:
110- Array element assignments may be parsed as statement functions: `a(i) = ...`
111- Namelist group names without `NML=` may be parsed as format expressions
112- A file unit number expression may be parsed as a character variable
113
114This phase also produces an internal error if it finds a `Name` that does not
115have its `symbol` data member filled in. This error is suppressed if other
116errors have occurred because in that case a `Name` corresponding to an erroneous
117symbol may not be resolved.
118
119### Expression analysis
120
121Expressions that occur in the specification part are analyzed during name
122resolution, for example, initial values, array bounds, type parameters.
123Any remaining expressions are analyzed in this phase.
124
125For each `Variable` and top-level `Expr` (i.e. one that is not nested below
126another `Expr` in the parse tree) the analyzed form of the expression is saved
127in the `typedExpr` data member. After this phase has completed, the analyzed
128expression can be accessed using `semantics::GetExpr()`.
129
130This phase also corrects mis-parses based on the result of expression analysis:
131- An expression like `a(b)` is parsed as a function reference but may need
132  to be rewritten to an array element reference (if `a` is an object entity)
133  or to a structure constructor (if `a` is a derive type)
134- An expression like `a(b:c)` is parsed as an array section but may need to be
135  rewritten as a substring if `a` is an object with type CHARACTER
136
137### Statement semantics
138
139Multiple independent checkers driven by the `SemanticsVisitor` framework
140perform the remaining semantic checks.
141By this phase, all names and expressions that can be successfully resolved
142have been. But there may be names without symbols or expressions without
143analyzed form if errors occurred earlier.
144
145### Write module files
146
147Separate compilation information is written out on successful compilation
148of modules and submodules. These are used as input to name resolution
149in program units that `USE` the modules.
150
151Module files are stripped down Fortran source for the module.
152Parts that aren't needed to compile dependent program units (e.g. action statements)
153are omitted.
154
155The module file for module `m` is named `m.mod` and the module file for
156submodule `s` of module `m` is named `m-s.mod`.
157