source: src/AST/porting.md @ db62eef

ADTarm-ehast-experimentalenumforall-pointer-decayjacob/cs343-translationnew-astnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since db62eef was d1ee9ec, checked in by Andrew Beach <ajbeach@…>, 4 years ago

Added some notes about the copy functions to the porting document.

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