source: src/AST/porting.md @ b0ec971

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

Changed Attribute field to params

Done for consistency with other field names.

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