source: src/AST/porting.md @ 0588d8c

ADTarm-ehast-experimentalcleanup-dtorsenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since 0588d8c was 246c245, checked in by Aaron Moss <a3moss@…>, 5 years ago

Merge branch 'master' of plg.uwaterloo.ca:software/cfa/cfa-cc

  • Property mode set to 100644
File size: 11.2 KB
Line 
1# Porting notes for new AST #
2
3## Pointer Types ##
4* raw pointer `T*` is used for construction, but not storage
5* `ast::ptr_base<T,R>` is a pointer to AST node `T` with reference type `R`
6  * specialization: strong pointer `ast::ptr<T>` is used for an ownership relationship
7  * specialization: weak pointer `ast::readonly<T>` is used for an observation relationship
8* added `ast::ptr_base<T,R>::as<S>()` with same semantics as `dynamic_cast<S*>(p)`
9* added `N * ast::ptr_base<N,R>::set_and_mutate( const N * n )`
10  * takes ownership of `n`, then returns a mutable version owned by this pointer
11  * Some debate on whether this is a good approach:
12    * makes an easy path to cloning, which we were trying to eliminate
13      * counter-point: these are all mutating clones rather than lifetime-preserving clones, and thus "necessary" (for some definition)
14    * existing uses:
15      * `VariableExpr::VariableExpr`, `UntypedExpr::createDeref`
16        * both involve grabbing a type from elsewhere and making an `lvalue` copy of it
17        * could potentially be replaced by a view class something like this:
18          ```
19          template<unsigned Quals>
20          class AddQualifiersType final : public Type {
21            readonly<Type> base;
22            // ...
23          };
24          ```
25          * requires all `qualifiers` use (and related helpers) to be virtual, non-zero overhead
26          * also subtle semantic change, where mutations to the source decl now change the viewing expression
27
28## Visitors ##
29* `Visitor` and `Mutator` are combined into a single `ast::Visitor` class
30  * Base nodes now override `const Node * accept( Visitor & v ) const = 0` with, e.g. `const Stmt * accept( Visitor & v ) const override = 0`
31* `PassVisitor` is replaced with `ast::Pass`
32
33## Structural Changes ##
34`CodeLocation` has been devolved from `BaseSyntaxNode` to `ast::ParseNode`
35* excludes `ast::Type` from carrying location information
36* `CodeLocation` is a mandatory constructor field for `ast::ParseNode`
37  * all subclass constructors must fill it; by convention, from their first argument
38
39`N->print(std::ostream&)` is a visitor now, port these methods to `ast::Print` class
40* **TODO** write this visitor
41* **TODO** write `std::ostream& operator<< ( std::ostream& out, const Node* node )` in `Node.hpp` in terms of `ast::Print`
42* `Declaration::printShort` should also be integrated
43
44`clone` is private to `Node` now
45* still needs to be overriden to return appropriate type
46  * e.g. `private: virtual Stmt * clone() const override = 0;`
47  * because friendship is not inherited, all implementations of clone need
48      /// Must be copied in ALL derived classes
49      template<typename node_t>
50      friend node_t * mutate(const node_t * node);
51
52All leaves of the `Node` inheritance tree are now declared `final`
53* e.g. `class CompoundStmt final : public Stmt`
54* allows compiler to optimize virtual calls to static calls if given static type
55
56Pulled `FuncSpecifiers`, `StorageClasses`, `CVQualifiers` out of `Type` into their own headers
57* Made `BFCommon` a `MakeBitfield` macro in its own header
58  * added default and field-init constructors to macro
59
60Prefer move semantics for containers passed to node constructors
61
62## Code Style ##
63
64### Files ###
65* Headers have a `.hpp` suffix
66* Source code has a `.cpp` suffix
67* All source has the project-standard leading and trailing comments
68* prefer `#pragma once` over `#ifdef` guards
69* namespaces that cover entire files don't get indented
70* The general node headers only `#include "Fwd.hpp"` if they can get away with it
71  * Anything that needs definitions goes in the .cpp file
72  * `Type.hpp` includes `Decl.hpp` so that it knows the `AggregateDecl` subclasses for `ReferenceToType::aggr()` overloads
73
74### Documentation ###
75* class, method, and field comments should use doxygen-style `///` prefix
76  * should be included on all classes
77  * should be included on any method declaration that doesn't have an obvious behaviour from either naming convention (e.g. constructor, print operator, implement visitor pattern) or an inline implementation
78* use explanatory comments with `//` wherever appropriate
79  * older comments should be maintained in porting process wherever possible
80
81### Naming ###
82* Preserve names from previous AST whenever reasonable, and get team consensus on any changes.
83* Strong justification required for private fields
84  * No `get_` prefix on getters (including for generated fields)
85    * exception is `DeclWithType::get_type()`
86* Notable changes:
87  * for concision and consistency with subclasses:
88    * `Declaration` => `ast::Decl`
89        * `DeclarationWithType` => `ast::DeclWithType`
90        * `Expression` => `ast::Expr`
91        * `Initializer` => `ast::Init`
92    * `Statement` => `ast::Stmt`
93        * any field names should follow a similar renaming
94  * because they don't really belong to `Type` (and for consistency with `Linkage::Spec`):
95    * `Type::StorageClasses` => `ast::Storage::Classes`
96          * `Type::Extern` etc. => `ast::Storage::Extern` etc.
97        * `Type::FuncSpecifiers` => `ast::Function::Specs`
98          * `Type::Inline` etc. => `ast::Function::Inline` etc.
99        * `Type::Qualifiers` => `ast::CV::Qualifiers`
100          * `Type::Const` etc. => `ast::CV::Const`
101          * couldn't break name-dependency loop without pulling `Qualifiers` out of `Type`
102        * `LinkageSpec::Spec` => `ast::Linkage::Spec`
103          * `LinkageSpec::Mangle` etc. => `ast::Linkage::Mangle` etc.
104          * `LinkageSpec::linkageUpdate` => `ast::Linkage::update`
105          * `LinkageSpec::linkageName` => `ast::Linkage::name`
106          * `LinkageSpec::isMangled(Spec)` etc. => `Spec.is_mangled` etc.
107          * `LinkageSpec::Intrinsic` etc. => `ast::Linkage::Intrinsic` etc.
108* Boolean constructor parameters get replaced with a dedicated flag enum:
109  * e.g. `bool isVarLen;` => `enum LengthFlag { FixedLen, VariableLen };` `LengthFlag isVarLen;`
110  * field can be *read* in the existing boolean contexts, but requires documentation to write
111  * suggest naming all flag enums `FooFlag` to hint at boolean nature
112
113## Specific Nodes ##
114`Decl`
115* `storageClasses` => `storage`
116* `declFromId()` => `fromId()`
117  * not 100% sure about the return type here...
118
119`DeclWithType`
120* When `SymTab::Validate::Pass2` is rewritten, update comment on `mangleName` with new name of pass
121* `get_scopedMangleName()` => `scopedMangleName()`
122* `get_type()` now returns `const Type*` so can't be inadvertently mutated
123  * still with `get_` name so it doesn't conflict with subclass field names
124
125`ObjectDecl`
126* changed constructor parameter order for better defaults
127  * allows `newObject` as just default settings
128
129`NamedTypeDecl`
130* `parameters` => `params`
131
132`TypeDecl`
133* moved `TypeDecl::Kind` to `ast::TypeVar::Kind`
134
135`AggregateDecl`
136* `parameters` => `params`
137
138`EnumDecl`
139* **TODO** rebuild `eval` for new AST (re: `valueOf` implementation)
140
141`Expr`
142* Merged `inferParams`/`resnSlots` into union, as suggested by comment in old version
143  * does imply get_/set_ API, and some care about moving backward
144* added constructor that sets result, for benefit of types that set it directly
145
146`ApplicationExpr`
147* `function` => `func`
148
149`UntypedExpr`
150* `function` => `func`
151* removed `begin_args()` in favour of `args.begin()`
152
153`MemberExpr`
154* **TODO** port setup of `result` in constructor
155
156`ConstantExpr`
157* inlined features of `Constant`, never used elsewhere, so removed `Constant`
158  * `Constant Constant::from_int(int)` etc. => `ConstantExpr * ConstantExpr::from_int(CodeLocation, int)`
159    * allocates new `ConstantExpr`, consistent with all existing uses
160
161`SizeofExpr`, `AlignofExpr`
162* `isType` deprecated in favour of boolean check on `type`
163  * all existing uses assume `type` set if true and don't use `expr`
164
165`AttrExpr`
166* did not port due to feature deprecation (e.g. `expr@attribute`)
167
168`LogicalExpr`
169* un-defaulted constructor parameter determining `&&` or `||`
170
171`CompoundLiteralExpr`
172* `initializer` => `init`
173
174`RangeExpr`
175* removed `set_low`, `set_high` due to disuse
176
177`TupleIndexExpr`
178* removed `set_tuple`, `set_index` due to disuse
179
180`GenericExpr`
181* `Association::isDefault` removed: `! type` is equivalent
182
183`StmtExpr`
184* `statements` => `stmts`
185
186`Init`
187* `bool maybeConstruct` => `enum ConstructFlag { DoConstruct, MaybeConstruct }`
188
189`Label`
190* `get_statement()` exclusively used for code location, replaced with `CodeLocation` field
191
192`CaseStmt`
193* `_isDefault` has been removed
194  * `isDefault` calculates value from `cond`
195  * default may not have a condition. I believe case (!default) requires a condition.
196
197`BranchStmt`
198* `Type` -> `Kind` and `type` -> `kind`
199* Constructors no longer throw SemanticErrorException:
200  * `label` constructor claims it is now considered a syntax error, replaced with assert.
201  * `computedTarget` constructor assumes `Goto`, other check would have SegFaulted.
202
203`TryStmt`
204* `block` -> `body` and `finallyBlock` -> `finally`
205
206`FinallyStmt`
207* `block` -> `body`
208
209`CompoundStmt`
210* **TODO** port copy operator
211  * Needs to be an almost-shallow clone, where the declarations are cloned only if needed
212  * **TODO** port `DeclReplacer`
213* Still a `std::list` for children, rather than `std::vector`
214  * allows more-efficient splicing for purposes of later code generation
215
216`Type`
217* `CV::Qualifiers` moved to end of constructor parameter list, defaulted to `{}`
218  * removed getter, setter in favour of public `qualifiers` field
219  * `ReferenceToType` puts a defaulted list of attributes after qualifiers
220* `forall` field split off into `ParameterizedType` subclass
221  * any type that needs it can inherit from `ParameterizedType`
222    * currently `FunctionType`, `ReferenceToType`
223* `get_qualifiers()` replaced with accessor `qualifiers()` and mutator `set_qualifiers()`
224  * `get_const()` etc. replaced with `is_const()` etc. variants
225* `referenceDepth()` now returns `unsigned` rather than `int`
226* A number of features only supported on aggregates pushed down to `ReferenceToType`:
227  * `attributes`: per docs [1] GCC only supports type attributes on aggregates and typedefs
228    * suggest adding a `TypeWithAttributes` wrapper type if this proves insufficient
229  * `getAggr()` => `aggr()`
230    * also now returns `const AggregateDecl *`
231* `genericSubstitution()` moved to own visitor in `AST/GenericSubstitution.hpp` **TODO** write
232
233`BasicType`
234* **TODO** move `kind`, `typeNames` into code generator
235
236`ReferenceToType`
237* deleted `get_baseParameters()` from children
238  * replace with `aggr() ? aggr()->params : nullptr`
239* `parameters` => `params`
240* hoisted `lookup` implementation into parent, made non-virtual
241  * also changed to return vector rather than filling; change back if any great win for reuse
242* `baseStruct` etc. renamed to `base`
243
244`PointerType`/`ArrayType`
245* `is_array()` => `isArray()`
246* `bool isVarLen;` => `enum LengthFlag { FixedLen, VariableLen }; LengthFlag isVarLen;`
247* `bool isStatic;` => `enum DimensionFlag { DynamicDim, StaticDim }; DimensionFlag isStatic;`
248
249`FunctionType`
250* `returnVals` => `returns`
251* `parameters` => `params`
252* `bool isVarArgs;` => `enum ArgumentFlag { FixedArgs, VariableArgs }; ArgumentFlag isVarArgs;`
253
254`TypeInstType`
255* `bool isFtype` => `TypeVar::Kind kind`
256
257`TypeofType`
258* `bool is_basetypeof` => `enum Kind { Typeof, Basetypeof } kind;`
259
260`TupleType`
261* removed `value_type` typedef due to likely error
262  * if readded, should be `const Type *`
263
264`AttrType`
265* did not port due to deprecation of feature
266  * feature is `type@thing` e.g. `int@MAX`
267
268[1] https://gcc.gnu.org/onlinedocs/gcc-9.1.0/gcc/Type-Attributes.html#Type-Attributes
269
Note: See TracBrowser for help on using the repository browser.