source: src/AST/porting.md

Last change on this file was 68fe946e, checked in by Andrew Beach <ajbeach@…>, 4 months ago

Updated DeclStats? for the new ast. Also fixed a bug in the old implementation (apparently it hasn't been used since gcc-builtins were added).

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