source: src/AST/Convert.cpp @ 3e54399

ADTast-experimentalenumpthread-emulationqualifiedEnum
Last change on this file since 3e54399 was 3e54399, checked in by JiadaL <j82liang@…>, 2 years ago

The compiler now will add a cast to base type for the usage of type enum; but it will fail because of violating some restrictions for the auto-gen functions. Need to investiage more

  • Property mode set to 100644
File size: 81.1 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2019 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
7// Convert.cpp -- Convert between the new and old syntax trees.
8//
9// Author           : Thierry Delisle
10// Created On       : Thu May 09 15::37::05 2019
11// Last Modified By : Peter A. Buhr
12// Last Modified On : Wed Feb  2 13:19:22 2022
13// Update Count     : 41
14//
15
16#include "Convert.hpp"
17
18#include <deque>
19#include <unordered_map>
20
21#include "AST/Attribute.hpp"
22#include "AST/Copy.hpp"
23#include "AST/Decl.hpp"
24#include "AST/Expr.hpp"
25#include "AST/Init.hpp"
26#include "AST/Stmt.hpp"
27#include "AST/TranslationUnit.hpp"
28#include "AST/TypeSubstitution.hpp"
29
30#include "SymTab/Autogen.h"
31#include "SynTree/Attribute.h"
32#include "SynTree/Declaration.h"
33#include "SynTree/TypeSubstitution.h"
34
35#include "Validate/FindSpecialDecls.h"
36
37//================================================================================================
38// Utilities
39template<template <class...> class C>
40struct to {
41        template<typename T>
42        static auto from( T && v ) -> C< typename T::value_type > {
43                C< typename T::value_type > l;
44                std::move(std::begin(v), std::end(v), std::back_inserter(l));
45                return l;
46        }
47};
48
49//================================================================================================
50namespace ast {
51
52// This is to preserve the FindSpecialDecls hack. It does not (and perhaps should not)
53// allow us to use the same stratagy in the new ast.
54// xxx - since convert back pass works, this concern seems to be unnecessary.
55
56// these need to be accessed in new FixInit now
57ast::ptr<ast::Type> sizeType = nullptr;
58const ast::FunctionDecl * dereferenceOperator = nullptr;
59const ast::StructDecl   * dtorStruct = nullptr;
60const ast::FunctionDecl * dtorStructDestroy = nullptr;
61
62}
63
64//================================================================================================
65class ConverterNewToOld : public ast::Visitor {
66        BaseSyntaxNode * node = nullptr;
67        using Cache = std::unordered_map< const ast::Node *, BaseSyntaxNode * >;
68        Cache cache;
69
70        // Statements can no longer be shared.
71        // however, since StmtExprResult is now implemented, need to still maintain
72        // readonly references.
73        Cache readonlyCache;
74
75        template<typename T>
76        struct Getter {
77                ConverterNewToOld & visitor;
78
79                template<typename U, enum ast::Node::ref_type R>
80                T * accept1( const ast::ptr_base<U, R> & ptr ) {
81                        if ( ! ptr ) return nullptr;
82                        ptr->accept( visitor );
83                        T * ret = strict_dynamic_cast< T * >( visitor.node );
84                        visitor.node = nullptr;
85                        return ret;
86                }
87
88                template<typename U>
89                std::list< T * > acceptL( const U & container ) {
90                        std::list< T * > ret;
91                        for ( auto ptr : container ) {
92                                ret.emplace_back( accept1( ptr ) );
93                        }
94                        return ret;
95                }
96        };
97
98    template<typename T>
99    Getter<T> get() {
100        return Getter<T>{ *this };
101    }
102
103        Label makeLabel(Statement * labelled, const ast::Label& label) {
104                // This probably will leak memory, but only until we get rid of the old tree.
105                if ( nullptr == labelled && label.location.isSet() ) {
106                        labelled = new NullStmt();
107                        labelled->location = label.location;
108                }
109                return Label(
110                        label.name,
111                        labelled,
112                        get<Attribute>().acceptL(label.attributes)
113                );
114        }
115
116        template<template <class...> class C>
117        std::list<Label> makeLabelL(Statement * labelled, const C<ast::Label>& labels) {
118                std::list<Label> ret;
119                for (auto label : labels) {
120                        ret.push_back( makeLabel(labelled, label) );
121                }
122                return ret;
123        }
124
125        /// get new qualifiers from old type
126        Type::Qualifiers cv( const ast::Type * ty ) { return { ty->qualifiers.val }; }
127
128        /// returns true and sets `node` if in cache
129        bool inCache( const ast::Node * node ) {
130                auto it = cache.find( node );
131                if ( it == cache.end() ) return false;
132                this->node = it->second;
133                return true;
134        }
135
136public:
137        Declaration * decl( const ast::Decl * declNode ) {
138                return get<Declaration>().accept1( ast::ptr<ast::Decl>( declNode ) );
139        }
140
141private:
142        void declPostamble( Declaration * decl, const ast::Decl * node ) {
143                decl->location = node->location;
144                // name comes from constructor
145                // linkage comes from constructor
146                decl->extension = node->extension;
147                decl->uniqueId = node->uniqueId;
148                // storageClasses comes from constructor
149                this->node = decl;
150        }
151
152        const ast::DeclWithType * declWithTypePostamble (
153                        DeclarationWithType * decl, const ast::DeclWithType * node ) {
154                cache.emplace( node, decl );
155                decl->mangleName = node->mangleName;
156                decl->scopeLevel = node->scopeLevel;
157                decl->asmName = get<Expression>().accept1( node->asmName );
158                // attributes comes from constructor
159                decl->isDeleted = node->isDeleted;
160                // fs comes from constructor
161                declPostamble( decl, node );
162                return nullptr;
163        }
164
165        const ast::DeclWithType * visit( const ast::ObjectDecl * node ) override final {       
166                if ( inCache( node ) ) {
167                        return nullptr;
168                }
169                auto bfwd = get<Expression>().accept1( node->bitfieldWidth );
170                auto type = get<Type>().accept1( node->type );
171                auto attr = get<Attribute>().acceptL( node->attributes );
172
173                auto decl = new ObjectDecl(
174                        node->name,
175                        Type::StorageClasses( node->storage.val ),
176                        LinkageSpec::Spec( node->linkage.val ),
177                        bfwd,
178                        type->clone(),
179                        nullptr, // prevent infinite loop
180                        attr,
181                        Type::FuncSpecifiers( node->funcSpec.val )
182                );
183
184                // handles the case where node->init references itself
185                // xxx - does it really happen?
186                declWithTypePostamble(decl, node);
187                auto init = get<Initializer>().accept1( node->init );
188                decl->init = init;
189
190                this->node = decl;
191                return nullptr;
192        }
193
194        const ast::DeclWithType * visit( const ast::FunctionDecl * node ) override final {
195                if ( inCache( node ) ) return nullptr;
196
197                // function decl contains real variables that the type must use.
198                // the structural change means function type in and out of decl
199                // must be handled **differently** on convert back to old.
200                auto ftype = new FunctionType(
201                        cv(node->type),
202                        (bool)node->type->isVarArgs
203                );
204                ftype->returnVals = get<DeclarationWithType>().acceptL(node->returns);
205                ftype->parameters = get<DeclarationWithType>().acceptL(node->params);
206
207                ftype->forall = get<TypeDecl>().acceptL( node->type_params );
208                if (!node->assertions.empty()) {
209                        assert(!ftype->forall.empty());
210                        // find somewhere to place assertions back, for convenience it is the last slot
211                        ftype->forall.back()->assertions = get<DeclarationWithType>().acceptL(node->assertions);
212                }
213
214                visitType(node->type, ftype);
215
216                auto decl = new FunctionDecl(
217                        node->name,
218                        Type::StorageClasses( node->storage.val ),
219                        LinkageSpec::Spec( node->linkage.val ),
220                        ftype,
221                        //get<FunctionType>().accept1( node->type ),
222                        {},
223                        get<Attribute>().acceptL( node->attributes ),
224                        Type::FuncSpecifiers( node->funcSpec.val )
225                );
226                cache.emplace( node, decl );
227                decl->statements = get<CompoundStmt>().accept1( node->stmts );
228                decl->withExprs = get<Expression>().acceptL( node->withExprs );
229                if ( ast::dereferenceOperator == node ) {
230                        Validate::dereferenceOperator = decl;
231                }
232                if ( ast::dtorStructDestroy == node ) {
233                        Validate::dtorStructDestroy = decl;
234                }
235                return declWithTypePostamble( decl, node );
236        }
237
238        const ast::Decl * namedTypePostamble( NamedTypeDecl * decl, const ast::NamedTypeDecl * node ) {
239                // base comes from constructor
240                decl->assertions = get<DeclarationWithType>().acceptL( node->assertions );
241                declPostamble( decl, node );
242                return nullptr;
243        }
244
245        const ast::Decl * visit( const ast::TypeDecl * node ) override final {
246                if ( inCache( node ) ) return nullptr;
247                auto decl = new TypeDecl(
248                        node->name,
249                        Type::StorageClasses( node->storage.val ),
250                        get<Type>().accept1( node->base ),
251                        (TypeDecl::Kind)(unsigned)node->kind,
252                        node->sized,
253                        get<Type>().accept1( node->init )
254                );
255                cache.emplace( node, decl );
256                return namedTypePostamble( decl, node );
257        }
258
259        const ast::Decl * visit( const ast::TypedefDecl * node ) override final {
260                auto decl = new TypedefDecl(
261                        node->name,
262                        node->location,
263                        Type::StorageClasses( node->storage.val ),
264            get<Type>().accept1( node->base ),
265                        LinkageSpec::Spec( node->linkage.val )
266                );
267                return namedTypePostamble( decl, node );
268        }
269
270        const ast::Decl * aggregatePostamble( AggregateDecl * decl, const ast::AggregateDecl * node ) {
271                cache.emplace( node, decl );
272                decl->members = get<Declaration>().acceptL( node->members );
273                decl->parameters = get<TypeDecl>().acceptL( node->params );
274                decl->body = node->body;
275                // attributes come from constructor
276                decl->parent = get<AggregateDecl>().accept1( node->parent );
277                declPostamble( decl, node );
278                return nullptr; // ??
279        }
280
281        const ast::Decl * visit( const ast::StructDecl * node ) override final {
282                if ( inCache( node ) ) return nullptr;
283                auto decl = new StructDecl(
284                        node->name,
285                        (AggregateDecl::Aggregate)node->kind,
286                        get<Attribute>().acceptL( node->attributes ),
287                        LinkageSpec::Spec( node->linkage.val )
288                );
289
290                if ( ast::dtorStruct == node ) {
291                        Validate::dtorStruct = decl;
292                }
293
294                return aggregatePostamble( decl, node );
295        }
296
297        const ast::Decl * visit( const ast::UnionDecl * node ) override final {
298                if ( inCache( node ) ) return nullptr;
299                auto decl = new UnionDecl(
300                        node->name,
301                        get<Attribute>().acceptL( node->attributes ),
302                        LinkageSpec::Spec( node->linkage.val )
303                );
304                return aggregatePostamble( decl, node );
305        }
306
307        const ast::Decl * visit( const ast::EnumDecl * node ) override final {
308                if ( inCache( node ) ) return nullptr;
309                auto decl = new EnumDecl(
310                        node->name,
311                        get<Attribute>().acceptL( node->attributes ),
312                        LinkageSpec::Spec( node->linkage.val ),
313                        get<Type>().accept1(node->base)
314                );
315                return aggregatePostamble( decl, node ); // Node info, including members, processed in aggregatePostamble
316        }
317
318        const ast::Decl * visit( const ast::TraitDecl * node ) override final {
319                if ( inCache( node ) ) return nullptr;
320                auto decl = new TraitDecl(
321                        node->name,
322                        {},
323                        LinkageSpec::Spec( node->linkage.val )
324                );
325                return aggregatePostamble( decl, node );
326        }
327
328        const ast::AsmDecl * visit( const ast::AsmDecl * node ) override final {
329                auto decl = new AsmDecl( get<AsmStmt>().accept1( node->stmt ) );
330                declPostamble( decl, node );
331                return nullptr;
332        }
333
334        const ast::DirectiveDecl * visit( const ast::DirectiveDecl * node ) override final {
335                auto decl = new DirectiveDecl( get<DirectiveStmt>().accept1( node->stmt ) );
336                declPostamble( decl, node );
337                return nullptr;
338        }
339
340        const ast::StaticAssertDecl * visit( const ast::StaticAssertDecl * node ) override final {
341                auto decl = new StaticAssertDecl(
342                        get<Expression>().accept1( node->cond ),
343                        get<ConstantExpr>().accept1( node->msg )
344                );
345                declPostamble( decl, node );
346                return nullptr;
347        }
348
349        const ast::Stmt * stmtPostamble( Statement * stmt, const ast::Stmt * node ) {
350                // force statements in old tree to be unique.
351                // cache.emplace( node, stmt );
352                readonlyCache.emplace( node, stmt );
353                stmt->location = node->location;
354                stmt->labels = makeLabelL( stmt, node->labels );
355                this->node = stmt;
356                return nullptr;
357        }
358
359        const ast::CompoundStmt * visit( const ast::CompoundStmt * node ) override final {
360                if ( inCache( node ) ) return nullptr;
361                auto stmt = new CompoundStmt( get<Statement>().acceptL( node->kids ) );
362                stmtPostamble( stmt, node );
363                return nullptr;
364        }
365
366        const ast::Stmt * visit( const ast::ExprStmt * node ) override final {
367                if ( inCache( node ) ) return nullptr;
368                auto stmt = new ExprStmt( nullptr );
369                stmt->expr = get<Expression>().accept1( node->expr );
370                return stmtPostamble( stmt, node );
371        }
372
373        const ast::Stmt * visit( const ast::AsmStmt * node ) override final {
374                if ( inCache( node ) ) return nullptr;
375                auto stmt = new AsmStmt(
376                        node->isVolatile,
377                        get<Expression>().accept1( node->instruction ),
378                        get<Expression>().acceptL( node->output ),
379                        get<Expression>().acceptL( node->input ),
380                        get<ConstantExpr>().acceptL( node->clobber ),
381                        makeLabelL( nullptr, node->gotoLabels ) // What are these labelling?
382                );
383                return stmtPostamble( stmt, node );
384        }
385
386        const ast::Stmt * visit( const ast::DirectiveStmt * node ) override final {
387                if ( inCache( node ) ) return nullptr;
388                auto stmt = new DirectiveStmt( node->directive );
389                return stmtPostamble( stmt, node );
390        }
391
392        const ast::Stmt * visit( const ast::IfStmt * node ) override final {
393                if ( inCache( node ) ) return nullptr;
394                auto stmt = new IfStmt(
395                        get<Expression>().accept1( node->cond ),
396                        get<Statement>().accept1( node->then ),
397                        get<Statement>().accept1( node->else_ ),
398                        get<Statement>().acceptL( node->inits )
399                );
400                return stmtPostamble( stmt, node );
401        }
402
403        const ast::Stmt * visit( const ast::SwitchStmt * node ) override final {
404                if ( inCache( node ) ) return nullptr;
405                auto stmt = new SwitchStmt(
406                        get<Expression>().accept1( node->cond ),
407                        get<Statement>().acceptL( node->stmts )
408                );
409                return stmtPostamble( stmt, node );
410        }
411
412        const ast::Stmt * visit( const ast::CaseStmt * node ) override final {
413                if ( inCache( node ) ) return nullptr;
414                auto stmt = new CaseStmt(
415                        get<Expression>().accept1( node->cond ),
416                        get<Statement>().acceptL( node->stmts ),
417                        node->isDefault()
418                );
419                return stmtPostamble( stmt, node );
420        }
421
422        const ast::Stmt * visit( const ast::WhileDoStmt * node ) override final {
423                if ( inCache( node ) ) return nullptr;
424                auto inits = get<Statement>().acceptL( node->inits );
425                auto stmt = new WhileDoStmt(
426                        get<Expression>().accept1( node->cond ),
427                        get<Statement>().accept1( node->body ),
428                        get<Statement>().accept1( node->else_ ),
429                        inits,
430                        node->isDoWhile
431                );
432                return stmtPostamble( stmt, node );
433        }
434
435        const ast::Stmt * visit( const ast::ForStmt * node ) override final {
436                if ( inCache( node ) ) return nullptr;
437                auto stmt = new ForStmt(
438                        get<Statement>().acceptL( node->inits ),
439                        get<Expression>().accept1( node->cond ),
440                        get<Expression>().accept1( node->inc ),
441                        get<Statement>().accept1( node->body ),
442                        get<Statement>().accept1( node->else_ )
443                );
444                return stmtPostamble( stmt, node );
445        }
446
447        const ast::Stmt * visit( const ast::BranchStmt * node ) override final {
448                if ( inCache( node ) ) return nullptr;
449                BranchStmt * stmt;
450                if (node->computedTarget) {
451                        stmt = new BranchStmt( get<Expression>().accept1( node->computedTarget ),
452                                BranchStmt::Goto );
453                } else {
454                        BranchStmt::Type type;
455                        switch (node->kind) {
456                        #define CASE(n) \
457                        case ast::BranchStmt::n: \
458                                type = BranchStmt::n; \
459                                break
460                        CASE(Goto);
461                        CASE(Break);
462                        CASE(Continue);
463                        CASE(FallThrough);
464                        CASE(FallThroughDefault);
465                        #undef CASE
466                        default:
467                                assertf(false, "Invalid ast::BranchStmt::Kind: %d\n", node->kind);
468                        }
469
470                        // The labels here are also weird.
471                        stmt = new BranchStmt( makeLabel( nullptr, node->originalTarget ), type );
472                        stmt->target = makeLabel( stmt, node->target );
473                }
474                return stmtPostamble( stmt, node );
475        }
476
477        const ast::Stmt * visit( const ast::ReturnStmt * node ) override final {
478                if ( inCache( node ) ) return nullptr;
479                auto stmt = new ReturnStmt( get<Expression>().accept1( node->expr ) );
480                return stmtPostamble( stmt, node );
481        }
482
483        const ast::Stmt * visit( const ast::ThrowStmt * node ) override final {
484                if ( inCache( node ) ) return nullptr;
485                ThrowStmt::Kind kind;
486                switch (node->kind) {
487                case ast::ExceptionKind::Terminate:
488                        kind = ThrowStmt::Terminate;
489                        break;
490                case ast::ExceptionKind::Resume:
491                        kind = ThrowStmt::Resume;
492                        break;
493                default:
494                        assertf(false, "Invalid ast::ThrowStmt::Kind: %d\n", node->kind);
495                }
496                auto stmt = new ThrowStmt(
497                        kind,
498                        get<Expression>().accept1( node->expr ),
499                        get<Expression>().accept1( node->target )
500                );
501                return stmtPostamble( stmt, node );
502        }
503
504        const ast::Stmt * visit( const ast::TryStmt * node ) override final {
505                if ( inCache( node ) ) return nullptr;
506                auto handlers = get<CatchStmt>().acceptL( node->handlers );
507                auto stmt = new TryStmt(
508                        get<CompoundStmt>().accept1( node->body ),
509                        handlers,
510                        get<FinallyStmt>().accept1( node->finally )
511                );
512                return stmtPostamble( stmt, node );
513        }
514
515        const ast::Stmt * visit( const ast::CatchStmt * node ) override final {
516                if ( inCache( node ) ) return nullptr;
517                CatchStmt::Kind kind;
518                switch (node->kind) {
519                case ast::ExceptionKind::Terminate:
520                        kind = CatchStmt::Terminate;
521                        break;
522                case ast::ExceptionKind::Resume:
523                        kind = CatchStmt::Resume;
524                        break;
525                default:
526                        assertf(false, "Invalid ast::CatchStmt::Kind: %d\n", node->kind);
527                }
528                auto stmt = new CatchStmt(
529                        kind,
530                        get<Declaration>().accept1( node->decl ),
531                        get<Expression>().accept1( node->cond ),
532                        get<Statement>().accept1( node->body )
533                );
534                return stmtPostamble( stmt, node );
535        }
536
537        const ast::Stmt * visit( const ast::FinallyStmt * node ) override final {
538                if ( inCache( node ) ) return nullptr;
539                auto stmt = new FinallyStmt( get<CompoundStmt>().accept1( node->body ) );
540                return stmtPostamble( stmt, node );
541        }
542
543        const ast::Stmt * visit(const ast::SuspendStmt * node ) override final {
544                if ( inCache( node ) ) return nullptr;
545                auto stmt = new SuspendStmt();
546                stmt->then   = get<CompoundStmt>().accept1( node->then   );
547                switch(node->type) {
548                        case ast::SuspendStmt::None     : stmt->type = SuspendStmt::None     ; break;
549                        case ast::SuspendStmt::Coroutine: stmt->type = SuspendStmt::Coroutine; break;
550                        case ast::SuspendStmt::Generator: stmt->type = SuspendStmt::Generator; break;
551                }
552                return stmtPostamble( stmt, node );
553        }
554
555        const ast::Stmt * visit( const ast::WaitForStmt * node ) override final {
556                if ( inCache( node ) ) return nullptr;
557                auto stmt = new WaitForStmt;
558                stmt->clauses.reserve( node->clauses.size() );
559                for ( auto clause : node->clauses ) {
560                        stmt->clauses.push_back({{
561                                        get<Expression>().accept1( clause.target.func ),
562                                        get<Expression>().acceptL( clause.target.args ),
563                                },
564                                get<Statement>().accept1( clause.stmt ),
565                                get<Expression>().accept1( clause.cond ),
566                        });
567                }
568                stmt->timeout = {
569                        get<Expression>().accept1( node->timeout.time ),
570                        get<Statement>().accept1( node->timeout.stmt ),
571                        get<Expression>().accept1( node->timeout.cond ),
572                };
573                stmt->orelse = {
574                        get<Statement>().accept1( node->orElse.stmt ),
575                        get<Expression>().accept1( node->orElse.cond ),
576                };
577                return stmtPostamble( stmt, node );
578        }
579
580        const ast::Decl * visit( const ast::WithStmt * node ) override final {
581                if ( inCache( node ) ) return nullptr;
582                auto stmt = new WithStmt(
583                        get<Expression>().acceptL( node->exprs ),
584                        get<Statement>().accept1( node->stmt )
585                );
586                declPostamble( stmt, node );
587                return nullptr;
588        }
589
590        const ast::NullStmt * visit( const ast::NullStmt * node ) override final {
591                if ( inCache( node ) ) return nullptr;
592                auto stmt = new NullStmt();
593                stmtPostamble( stmt, node );
594                return nullptr;
595        }
596
597        const ast::Stmt * visit( const ast::DeclStmt * node ) override final {
598                if ( inCache( node ) ) return nullptr;
599                auto stmt = new DeclStmt( get<Declaration>().accept1( node->decl ) );
600                return stmtPostamble( stmt, node );
601        }
602
603        const ast::Stmt * visit( const ast::ImplicitCtorDtorStmt * node ) override final {
604                if ( inCache( node ) ) return nullptr;
605                auto stmt = new ImplicitCtorDtorStmt{
606                        get<Statement>().accept1( node->callStmt )
607                };
608                return stmtPostamble( stmt, node );
609        }
610
611        const ast::Stmt * visit( const ast::MutexStmt * node ) override final {
612                if ( inCache( node ) ) return nullptr;
613                 auto stmt = new MutexStmt(
614                        get<Statement>().accept1( node->stmt ),
615                        get<Expression>().acceptL( node->mutexObjs )
616                );
617                return stmtPostamble( stmt, node );
618        }
619
620        TypeSubstitution * convertTypeSubstitution(const ast::TypeSubstitution * src) {
621
622                if (!src) return nullptr;
623
624                TypeSubstitution *rslt = new TypeSubstitution();
625
626                for (decltype(src->begin()) src_i = src->begin(); src_i != src->end(); src_i++) {
627                        rslt->add( src_i->first.typeString(),
628                                   get<Type>().accept1(src_i->second) );
629                }
630
631                return rslt;
632        }
633
634        void convertInferUnion(std::map<UniqueId,ParamEntry> &tgtInferParams,
635                                                   std::vector<UniqueId>         &tgtResnSlots,
636                                                   const ast::Expr::InferUnion   &srcInferred ) {
637
638                assert( tgtInferParams.empty() );
639                assert( tgtResnSlots.empty() );
640
641                if ( srcInferred.data.inferParams ) {
642                        const ast::InferredParams &srcParams = srcInferred.inferParams();
643                        for (auto & srcParam : srcParams) {
644                                auto res = tgtInferParams.emplace(srcParam.first, ParamEntry(
645                                        srcParam.second.decl,
646                                        get<Declaration>().accept1(srcParam.second.declptr),
647                                        get<Type>().accept1(srcParam.second.actualType)->clone(),
648                                        get<Type>().accept1(srcParam.second.formalType)->clone(),
649                                        get<Expression>().accept1(srcParam.second.expr)->clone()
650                                ));
651                                assert(res.second);
652                        }
653                }
654                if ( srcInferred.data.resnSlots ) {
655                        const ast::ResnSlots &srcSlots = srcInferred.resnSlots();
656                        for (auto srcSlot : srcSlots) {
657                                tgtResnSlots.push_back(srcSlot);
658                        }
659                }
660        }
661
662        Expression * visitBaseExpr_skipResultType(const ast::Expr * src, Expression * tgt) {
663
664                tgt->location  = src->location;
665                tgt->env       = convertTypeSubstitution(src->env);
666                tgt->extension = src->extension;
667
668                convertInferUnion(tgt->inferParams, tgt->resnSlots, src->inferred);
669                return tgt;
670        }
671
672        Expression * visitBaseExpr(const ast::Expr * src, Expression * tgt) {
673
674                tgt->result = get<Type>().accept1(src->result);
675                // Unconditionally use a clone of the result type.
676                // We know this will leak some objects: much of the immediate conversion result.
677                // In some cases, using the conversion result directly gives unintended object sharing.
678                // A parameter (ObjectDecl, a child of a FunctionType) is shared by the weak-ref cache.
679                // But tgt->result must be fully owned privately by tgt.
680                // Applying these conservative copies here means
681                // - weak references point at the declaration's copy, not these expr.result copies (good)
682                // - we copy more objects than really needed (bad, tolerated)
683                if (tgt->result) {
684                        tgt->result = tgt->result->clone();
685                }
686                return visitBaseExpr_skipResultType(src, tgt);
687        }
688
689        const ast::Expr * visit( const ast::ApplicationExpr * node ) override final {
690                auto expr = visitBaseExpr( node,
691                        new ApplicationExpr(
692                                get<Expression>().accept1(node->func),
693                                get<Expression>().acceptL(node->args)
694                        )
695                );
696                this->node = expr;
697                return nullptr;
698        }
699
700        const ast::Expr * visit( const ast::UntypedExpr * node ) override final {
701                auto expr = visitBaseExpr( node,
702                        new UntypedExpr(
703                                get<Expression>().accept1(node->func),
704                                get<Expression>().acceptL(node->args)
705                        )
706                );
707                this->node = expr;
708                return nullptr;
709        }
710
711        const ast::Expr * visit( const ast::NameExpr * node ) override final {
712                auto expr = visitBaseExpr( node,
713                        new NameExpr(
714                                node->name
715                        )
716                );
717                this->node = expr;
718                return nullptr;
719        }
720
721        const ast::Expr * visit( const ast::AddressExpr * node ) override final {
722                auto expr = visitBaseExpr( node,
723                        new AddressExpr(
724                                get<Expression>().accept1(node->arg)
725                        )
726                );
727                this->node = expr;
728                return nullptr;
729        }
730
731        const ast::Expr * visit( const ast::LabelAddressExpr * node ) override final {
732                auto expr = visitBaseExpr( node,
733                        new LabelAddressExpr(
734                                makeLabel(nullptr, node->arg)
735                        )
736                );
737                this->node = expr;
738                return nullptr;
739        }
740
741        const ast::Expr * visit( const ast::CastExpr * node ) override final {
742                auto expr = visitBaseExpr( node,
743                        new CastExpr(
744                                get<Expression>().accept1(node->arg),
745                                (node->isGenerated == ast::GeneratedCast)
746                        )
747                );
748                this->node = expr;
749                return nullptr;
750        }
751
752        const ast::Expr * visit( const ast::KeywordCastExpr * node ) override final {
753                AggregateDecl::Aggregate castTarget = (AggregateDecl::Aggregate)node->target;
754                assert( AggregateDecl::Generator <= castTarget && castTarget <= AggregateDecl::Thread );
755                auto expr = visitBaseExpr( node,
756                        new KeywordCastExpr(
757                                get<Expression>().accept1(node->arg),
758                                castTarget,
759                                {node->concrete_target.field, node->concrete_target.getter}
760                        )
761                );
762                this->node = expr;
763                return nullptr;
764        }
765
766        const ast::Expr * visit( const ast::VirtualCastExpr * node ) override final {
767                auto expr = visitBaseExpr_skipResultType( node,
768                        new VirtualCastExpr(
769                                get<Expression>().accept1(node->arg),
770                                get<Type>().accept1(node->result)
771                        )
772                );
773                this->node = expr;
774                return nullptr;
775        }
776
777        const ast::Expr * visit( const ast::UntypedMemberExpr * node ) override final {
778                auto expr = visitBaseExpr( node,
779                        new UntypedMemberExpr(
780                                get<Expression>().accept1(node->member),
781                                get<Expression>().accept1(node->aggregate)
782                        )
783                );
784                this->node = expr;
785                return nullptr;
786        }
787
788        const ast::Expr * visit( const ast::MemberExpr * node ) override final {
789                auto expr = visitBaseExpr( node,
790                        new MemberExpr(
791                                get<DeclarationWithType>().accept1(node->member),
792                                get<Expression>().accept1(node->aggregate)
793                        )
794                );
795                this->node = expr;
796                return nullptr;
797        }
798
799        const ast::Expr * visit( const ast::VariableExpr * node ) override final {
800                auto expr = new VariableExpr();
801                expr->var = get<DeclarationWithType>().accept1(node->var);
802                visitBaseExpr( node, expr );
803                this->node = expr;
804                return nullptr;
805        }
806
807        const ast::Expr * visit( const ast::ConstantExpr * node ) override final {
808                // Old world:   two types: rslt->constant.type, rslt->result
809                // New workd:   one public type: node->result, plus node->underlyer only to support roundtrip conversion
810                //              preserving underlyer because the correct type for string literals is complicated to construct,
811            //              and distinguishing a string from other literals using the type is hard to do accurately
812                // Both worlds: the outer, expression-level type can change during resolution
813                //              for a string, that's char[k] before-resolve and char * after
814                // Old world:   the inner Constant type stays what it was built with
815                //              for a string, that's char[k] always
816                // Both worlds: the "rep" field of a constant is the C source file fragment that compiles to the desired value
817        //              for a string, that includes outer quotes, backslashes, et al cases from the Literals test
818                ConstantExpr *rslt = new ConstantExpr(Constant(
819                        get<Type>().accept1(node->underlyer),
820                        node->rep,
821                        node->ival));
822                auto expr = visitBaseExpr( node, rslt );
823                this->node = expr;
824                return nullptr;
825        }
826
827        const ast::Expr * visit( const ast::SizeofExpr * node ) override final {
828                assert (node->expr || node->type);
829                assert (! (node->expr && node->type));
830                SizeofExpr *rslt;
831                if (node->expr) {
832                        rslt = new SizeofExpr(
833                                get<Expression>().accept1(node->expr)
834                        );
835                        assert (!rslt->isType);
836                }
837                else {
838                        assert(node->type);
839                        rslt = new SizeofExpr(
840                                get<Type>().accept1(node->type)
841                        );
842                        assert (rslt->isType);
843                }
844                auto expr = visitBaseExpr( node, rslt );
845                this->node = expr;
846                return nullptr;
847        }
848
849        const ast::Expr * visit( const ast::AlignofExpr * node ) override final {
850                assert (node->expr || node->type);
851                assert (! (node->expr && node->type));
852                AlignofExpr *rslt;
853                if (node->expr) {
854                        rslt = new AlignofExpr(
855                                get<Expression>().accept1(node->expr)
856                        );
857                        assert (!rslt->isType);
858                }
859                else {
860                        assert(node->type);
861                        rslt = new AlignofExpr(
862                                get<Type>().accept1(node->type)
863                        );
864                        assert (rslt->isType);
865                }
866                auto expr = visitBaseExpr( node, rslt );
867                this->node = expr;
868                return nullptr;
869        }
870
871        const ast::Expr * visit( const ast::UntypedOffsetofExpr * node ) override final {
872                auto expr = visitBaseExpr( node,
873                        new UntypedOffsetofExpr(
874                                get<Type>().accept1(node->type),
875                                node->member
876                        )
877                );
878                this->node = expr;
879                return nullptr;
880        }
881
882        const ast::Expr * visit( const ast::OffsetofExpr * node ) override final {
883                auto expr = visitBaseExpr( node,
884                        new OffsetofExpr(
885                                get<Type>().accept1(node->type),
886                                get<DeclarationWithType>().accept1(node->member)
887                        )
888                );
889                this->node = expr;
890                return nullptr;
891        }
892
893        const ast::Expr * visit( const ast::OffsetPackExpr * node ) override final {
894                auto expr = visitBaseExpr( node,
895                        new OffsetPackExpr(
896                                get<StructInstType>().accept1(node->type)
897                        )
898                );
899                this->node = expr;
900                return nullptr;
901        }
902
903        const ast::Expr * visit( const ast::LogicalExpr * node ) override final {
904                assert (node->isAnd == ast::LogicalFlag::AndExpr ||
905                                node->isAnd == ast::LogicalFlag::OrExpr );
906                auto expr = visitBaseExpr( node,
907                        new LogicalExpr(
908                                get<Expression>().accept1(node->arg1),
909                                get<Expression>().accept1(node->arg2),
910                                (node->isAnd == ast::LogicalFlag::AndExpr)
911                        )
912                );
913                this->node = expr;
914                return nullptr;
915        }
916
917        const ast::Expr * visit( const ast::ConditionalExpr * node ) override final {
918                auto expr = visitBaseExpr( node,
919                        new ConditionalExpr(
920                                get<Expression>().accept1(node->arg1),
921                                get<Expression>().accept1(node->arg2),
922                                get<Expression>().accept1(node->arg3)
923                        )
924                );
925                this->node = expr;
926                return nullptr;
927        }
928
929        const ast::Expr * visit( const ast::CommaExpr * node ) override final {
930                auto expr = visitBaseExpr( node,
931                        new CommaExpr(
932                                get<Expression>().accept1(node->arg1),
933                                get<Expression>().accept1(node->arg2)
934                        )
935                );
936                this->node = expr;
937                return nullptr;
938        }
939
940        const ast::Expr * visit( const ast::TypeExpr * node ) override final {
941                auto expr = visitBaseExpr( node,
942                        new TypeExpr(
943                                get<Type>().accept1(node->type)
944                        )
945                );
946                this->node = expr;
947                return nullptr;
948        }
949
950        const ast::Expr * visit( const ast::AsmExpr * node ) override final {
951                auto expr = visitBaseExpr( node,
952                        new AsmExpr(
953                                new std::string(node->inout),
954                                get<Expression>().accept1(node->constraint),
955                                get<Expression>().accept1(node->operand)
956                        )
957                );
958                this->node = expr;
959                return nullptr;
960        }
961
962        const ast::Expr * visit( const ast::ImplicitCopyCtorExpr * node ) override final {
963                auto rslt = new ImplicitCopyCtorExpr(
964                        get<ApplicationExpr>().accept1(node->callExpr)
965                );
966
967                auto expr = visitBaseExpr( node, rslt );
968                this->node = expr;
969                return nullptr;
970        }
971
972        const ast::Expr * visit( const ast::ConstructorExpr * node ) override final {
973                auto expr = visitBaseExpr( node,
974                        new ConstructorExpr(
975                                get<Expression>().accept1(node->callExpr)
976                        )
977                );
978                this->node = expr;
979                return nullptr;
980        }
981
982        const ast::Expr * visit( const ast::CompoundLiteralExpr * node ) override final {
983                auto expr = visitBaseExpr_skipResultType( node,
984                        new CompoundLiteralExpr(
985                                get<Type>().accept1(node->result),
986                                get<Initializer>().accept1(node->init)
987                        )
988                );
989                this->node = expr;
990                return nullptr;
991        }
992
993        const ast::Expr * visit( const ast::RangeExpr * node ) override final {
994                auto expr = visitBaseExpr( node,
995                        new RangeExpr(
996                                get<Expression>().accept1(node->low),
997                                get<Expression>().accept1(node->high)
998                        )
999                );
1000                this->node = expr;
1001                return nullptr;
1002        }
1003
1004        const ast::Expr * visit( const ast::UntypedTupleExpr * node ) override final {
1005                auto expr = visitBaseExpr( node,
1006                        new UntypedTupleExpr(
1007                                get<Expression>().acceptL(node->exprs)
1008                        )
1009                );
1010                this->node = expr;
1011                return nullptr;
1012        }
1013
1014        const ast::Expr * visit( const ast::TupleExpr * node ) override final {
1015                auto expr = visitBaseExpr( node,
1016                        new TupleExpr(
1017                                get<Expression>().acceptL(node->exprs)
1018                        )
1019                );
1020                this->node = expr;
1021                return nullptr;
1022        }
1023
1024        const ast::Expr * visit( const ast::TupleIndexExpr * node ) override final {
1025                auto expr = visitBaseExpr( node,
1026                        new TupleIndexExpr(
1027                                get<Expression>().accept1(node->tuple),
1028                                node->index
1029                        )
1030                );
1031                this->node = expr;
1032                return nullptr;
1033        }
1034
1035        const ast::Expr * visit( const ast::TupleAssignExpr * node ) override final {
1036                auto expr = visitBaseExpr( node,
1037                        new TupleAssignExpr(
1038                                get<StmtExpr>().accept1(node->stmtExpr)
1039                        )
1040                );
1041                this->node = expr;
1042                return nullptr;
1043        }
1044
1045        const ast::Expr * visit( const ast::StmtExpr * node ) override final {
1046                auto rslt = new StmtExpr(
1047                        get<CompoundStmt>().accept1(node->stmts)
1048                );
1049
1050                rslt->returnDecls = get<ObjectDecl>().acceptL(node->returnDecls);
1051                rslt->dtors       = get<Expression>().acceptL(node->dtors);
1052
1053                // is this even used after convert?
1054                //if (tmp->resultExpr) {
1055                //      // this MUST be found by children visit
1056                //      rslt->resultExpr  = strict_dynamic_cast<ExprStmt *>(readonlyCache.at(tmp->resultExpr));
1057                //}
1058
1059                auto expr = visitBaseExpr( node, rslt );
1060                this->node = expr;
1061                return nullptr;
1062        }
1063
1064        const ast::Expr * visit( const ast::UniqueExpr * node ) override final {
1065                auto rslt = new UniqueExpr(
1066                        get<Expression>().accept1(node->expr),
1067                        node->id
1068                );
1069
1070                rslt->object = get<ObjectDecl>  ().accept1(node->object);
1071                rslt->var    = get<VariableExpr>().accept1(node->var);
1072
1073                auto expr = visitBaseExpr( node, rslt );
1074                this->node = expr->clone();
1075                return nullptr;
1076        }
1077
1078        const ast::Expr * visit( const ast::UntypedInitExpr * node ) override final {
1079                std::list<InitAlternative> initAlts;
1080                for (auto ia : node->initAlts) {
1081                        initAlts.push_back(InitAlternative(
1082                                get<Type>       ().accept1(ia.type),
1083                                get<Designation>().accept1(ia.designation)
1084                        ));
1085                }
1086                auto expr = visitBaseExpr( node,
1087                        new UntypedInitExpr(
1088                                get<Expression>().accept1(node->expr),
1089                                initAlts
1090                        )
1091                );
1092                this->node = expr;
1093                return nullptr;
1094        }
1095
1096        const ast::Expr * visit( const ast::InitExpr * node ) override final {
1097                auto expr = visitBaseExpr( node,
1098                        new InitExpr(
1099                                get<Expression>().accept1(node->expr),
1100                                get<Designation>().accept1(node->designation)
1101                        )
1102                );
1103                this->node = expr;
1104                return nullptr;
1105        }
1106
1107        const ast::Expr * visit( const ast::DeletedExpr * node ) override final {
1108                auto expr = visitBaseExpr( node,
1109                        new DeletedExpr(
1110                                get<Expression>().accept1(node->expr),
1111                                inCache(node->deleteStmt) ?
1112                                        strict_dynamic_cast<Declaration*>(this->node) :
1113                                        get<Declaration>().accept1(node->deleteStmt)
1114                        )
1115                );
1116                this->node = expr;
1117                return nullptr;
1118        }
1119
1120        const ast::Expr * visit( const ast::DefaultArgExpr * node ) override final {
1121                auto expr = visitBaseExpr( node,
1122                        new DefaultArgExpr(
1123                                get<Expression>().accept1(node->expr)
1124                        )
1125                );
1126                this->node = expr;
1127                return nullptr;
1128        }
1129
1130        const ast::Expr * visit( const ast::GenericExpr * node ) override final {
1131                std::list<GenericExpr::Association> associations;
1132                for (auto association : node->associations) {
1133                        associations.push_back(GenericExpr::Association(
1134                                get<Type>      ().accept1(association.type),
1135                                get<Expression>().accept1(association.expr)
1136                        ));
1137                }
1138                auto expr = visitBaseExpr( node,
1139                        new GenericExpr(
1140                                get<Expression>().accept1(node->control),
1141                                associations
1142                        )
1143                );
1144                this->node = expr;
1145                return nullptr;
1146        }
1147
1148        const ast::Type * visitType( const ast::Type * node, Type * type ) {
1149                // Some types do this in their constructor so add a check.
1150                if ( !node->attributes.empty() && type->attributes.empty() ) {
1151                        type->attributes = get<Attribute>().acceptL( node->attributes );
1152                }
1153                this->node = type;
1154                return nullptr;
1155        }
1156
1157        const ast::Type * visit( const ast::VoidType * node ) override final {
1158                return visitType( node, new VoidType{ cv( node ) } );
1159        }
1160
1161        const ast::Type * visit( const ast::BasicType * node ) override final {
1162                auto type = new BasicType{ cv( node ), (BasicType::Kind)(unsigned)node->kind };
1163                // I believe this should always be a BasicType.
1164                if ( ast::sizeType == node ) {
1165                        Validate::SizeType = type;
1166                }
1167                return visitType( node, type );
1168        }
1169
1170        const ast::Type * visit( const ast::PointerType * node ) override final {
1171                return visitType( node, new PointerType{
1172                        cv( node ),
1173                        get<Type>().accept1( node->base ),
1174                        get<Expression>().accept1( node->dimension ),
1175                        (bool)node->isVarLen,
1176                        (bool)node->isStatic
1177                } );
1178        }
1179
1180        const ast::Type * visit( const ast::ArrayType * node ) override final {
1181                return visitType( node, new ArrayType{
1182                        cv( node ),
1183                        get<Type>().accept1( node->base ),
1184                        get<Expression>().accept1( node->dimension ),
1185                        (bool)node->isVarLen,
1186                        (bool)node->isStatic
1187                } );
1188        }
1189
1190        const ast::Type * visit( const ast::ReferenceType * node ) override final {
1191                return visitType( node, new ReferenceType{
1192                        cv( node ),
1193                        get<Type>().accept1( node->base )
1194                } );
1195        }
1196
1197        const ast::Type * visit( const ast::QualifiedType * node ) override final {
1198                return visitType( node, new QualifiedType{
1199                        cv( node ),
1200                        get<Type>().accept1( node->parent ),
1201                        get<Type>().accept1( node->child )
1202                } );
1203        }
1204
1205        const ast::Type * visit( const ast::FunctionType * node ) override final {
1206                static std::string dummy_paramvar_prefix = "__param_";
1207                static std::string dummy_returnvar_prefix = "__retval_";
1208
1209                auto ty = new FunctionType {
1210                        cv( node ),
1211                        (bool)node->isVarArgs
1212                };
1213                auto returns = get<Type>().acceptL(node->returns);
1214                auto params = get<Type>().acceptL(node->params);
1215
1216                int ret_index = 0;
1217                for (auto t: returns) {
1218                        // xxx - LinkageSpec shouldn't matter but needs to be something
1219                        ObjectDecl * dummy = new ObjectDecl(dummy_returnvar_prefix + std::to_string(ret_index++), {}, LinkageSpec::C, nullptr, t, nullptr);
1220                        ty->returnVals.push_back(dummy);
1221                }
1222                int param_index = 0;
1223                for (auto t: params) {
1224                        ObjectDecl * dummy = new ObjectDecl(dummy_paramvar_prefix + std::to_string(param_index++), {}, LinkageSpec::C, nullptr, t, nullptr);
1225                        ty->parameters.push_back(dummy);
1226                }
1227
1228                // ty->returnVals = get<DeclarationWithType>().acceptL( node->returns );
1229                // ty->parameters = get<DeclarationWithType>().acceptL( node->params );
1230
1231                auto types = get<TypeInstType>().acceptL( node->forall );
1232                for (auto t : types) {
1233                        auto newT = new TypeDecl(*t->baseType);
1234                        newT->name = t->name; // converted by typeString()
1235                        for (auto asst : newT->assertions) delete asst;
1236                        newT->assertions.clear();
1237                        ty->forall.push_back(newT);
1238                }
1239                auto assts = get<VariableExpr>().acceptL( node->assertions );
1240                if (!assts.empty()) {
1241                        assert(!types.empty());
1242                        for (auto asst : assts) {
1243                                auto newDecl = new ObjectDecl(*strict_dynamic_cast<ObjectDecl*>(asst->var));
1244                                delete newDecl->type;
1245                                newDecl->type = asst->result->clone();
1246                                newDecl->storageClasses.is_extern = true; // hack
1247                                ty->forall.back()->assertions.push_back(newDecl);
1248                        }
1249                }
1250
1251                return visitType( node, ty );
1252        }
1253
1254        const ast::Type * postvisit( const ast::BaseInstType * old, ReferenceToType * ty ) {
1255                ty->parameters = get<Expression>().acceptL( old->params );
1256                ty->hoistType = old->hoistType;
1257                return visitType( old, ty );
1258        }
1259
1260        const ast::Type * visit( const ast::StructInstType * node ) override final {
1261                StructInstType * ty;
1262                if ( node->base ) {
1263                        ty = new StructInstType{
1264                                cv( node ),
1265                                get<StructDecl>().accept1( node->base ),
1266                                get<Attribute>().acceptL( node->attributes )
1267                        };
1268                } else {
1269                        ty = new StructInstType{
1270                                cv( node ),
1271                                node->name,
1272                                get<Attribute>().acceptL( node->attributes )
1273                        };
1274                }
1275                return postvisit( node, ty );
1276        }
1277
1278        const ast::Type * visit( const ast::UnionInstType * node ) override final {
1279                UnionInstType * ty;
1280                if ( node->base ) {
1281                        ty = new UnionInstType{
1282                                cv( node ),
1283                                get<UnionDecl>().accept1( node->base ),
1284                                get<Attribute>().acceptL( node->attributes )
1285                        };
1286                } else {
1287                        ty = new UnionInstType{
1288                                cv( node ),
1289                                node->name,
1290                                get<Attribute>().acceptL( node->attributes )
1291                        };
1292                }
1293                return postvisit( node, ty );
1294        }
1295
1296        const ast::Type * visit( const ast::EnumInstType * node ) override final {
1297                EnumInstType * ty;
1298                if ( node->base ) {
1299                        ty = new EnumInstType{
1300                                cv( node ),
1301                                get<EnumDecl>().accept1( node->base ),
1302                                get<Attribute>().acceptL( node->attributes )
1303                        };
1304                } else {
1305                        ty = new EnumInstType{
1306                                cv( node ),
1307                                node->name,
1308                                get<Attribute>().acceptL( node->attributes )
1309                        };
1310                }
1311                return postvisit( node, ty );
1312        }
1313
1314        const ast::Type * visit( const ast::TraitInstType * node ) override final {
1315                TraitInstType * ty;
1316                if ( node->base ) {
1317                        ty = new TraitInstType{
1318                                cv( node ),
1319                                get<TraitDecl>().accept1( node->base ),
1320                                get<Attribute>().acceptL( node->attributes )
1321                        };
1322                } else {
1323                        ty = new TraitInstType{
1324                                cv( node ),
1325                                node->name,
1326                                get<Attribute>().acceptL( node->attributes )
1327                        };
1328                }
1329                return postvisit( node, ty );
1330        }
1331
1332        const ast::Type * visit( const ast::TypeInstType * node ) override final {
1333                TypeInstType * ty;
1334                if ( node->base ) {
1335                        ty = new TypeInstType{
1336                                cv( node ),
1337                                node->typeString(),
1338                                get<TypeDecl>().accept1( node->base ),
1339                                get<Attribute>().acceptL( node->attributes )
1340                        };
1341                } else {
1342                        ty = new TypeInstType{
1343                                cv( node ),
1344                                node->typeString(),
1345                                node->kind == ast::TypeDecl::Ftype,
1346                                get<Attribute>().acceptL( node->attributes )
1347                        };
1348                }
1349                return postvisit( node, ty );
1350        }
1351
1352        const ast::Type * visit( const ast::TupleType * node ) override final {
1353                return visitType( node, new TupleType{
1354                        cv( node ),
1355                        get<Type>().acceptL( node->types )
1356                        // members generated by TupleType c'tor
1357                } );
1358        }
1359
1360        const ast::Type * visit( const ast::TypeofType * node ) override final {
1361                return visitType( node, new TypeofType{
1362                        cv( node ),
1363                        get<Expression>().accept1( node->expr ),
1364                        (bool)node->kind
1365                } );
1366        }
1367
1368        const ast::Type * visit( const ast::VTableType * node ) override final {
1369                return visitType( node, new VTableType{
1370                        cv( node ),
1371                        get<Type>().accept1( node->base )
1372                } );
1373        }
1374
1375        const ast::Type * visit( const ast::VarArgsType * node ) override final {
1376                return visitType( node, new VarArgsType{ cv( node ) } );
1377        }
1378
1379        const ast::Type * visit( const ast::ZeroType * node ) override final {
1380                return visitType( node, new ZeroType{ cv( node ) } );
1381        }
1382
1383        const ast::Type * visit( const ast::OneType * node ) override final {
1384                return visitType( node, new OneType{ cv( node ) } );
1385        }
1386
1387        const ast::Type * visit( const ast::GlobalScopeType * node ) override final {
1388                return visitType( node, new GlobalScopeType{} );
1389        }
1390
1391        const ast::Designation * visit( const ast::Designation * node ) override final {
1392                auto designation = new Designation( get<Expression>().acceptL( node->designators ) );
1393                designation->location = node->location;
1394                this->node = designation;
1395                return nullptr;
1396        }
1397
1398        const ast::Init * visit( const ast::SingleInit * node ) override final {
1399                auto init = new SingleInit(
1400                        get<Expression>().accept1( node->value ),
1401                        ast::MaybeConstruct == node->maybeConstructed
1402                );
1403                init->location = node->location;
1404                this->node = init;
1405                return nullptr;
1406        }
1407
1408        const ast::Init * visit( const ast::ListInit * node ) override final {
1409                auto init = new ListInit(
1410                        get<Initializer>().acceptL( node->initializers ),
1411                        get<Designation>().acceptL( node->designations ),
1412                        ast::MaybeConstruct == node->maybeConstructed
1413                );
1414                init->location = node->location;
1415                this->node = init;
1416                return nullptr;
1417        }
1418
1419        const ast::Init * visit( const ast::ConstructorInit * node ) override final {
1420                auto init = new ConstructorInit(
1421                        get<Statement>().accept1( node->ctor ),
1422                        get<Statement>().accept1( node->dtor ),
1423                        get<Initializer>().accept1( node->init )
1424                );
1425                init->location = node->location;
1426                this->node = init;
1427                return nullptr;
1428        }
1429
1430        const ast::Attribute * visit( const ast::Attribute * node ) override final {
1431                auto attr = new Attribute(
1432                        node->name,
1433                        get<Expression>().acceptL(node->params)
1434                );
1435                this->node = attr;
1436                return nullptr;
1437        }
1438
1439        const ast::TypeSubstitution * visit( const ast::TypeSubstitution * node ) override final {
1440                // Handled by convertTypeSubstitution helper instead.
1441                // TypeSubstitution is not a node in the old model, so the conversion result wouldn't fit in this->node.
1442                assert( 0 );
1443                (void)node;
1444                return nullptr;
1445        }
1446};
1447
1448std::list< Declaration * > convert( const ast::TranslationUnit && translationUnit ) {
1449        // Copy values from the global store to the local static variables.
1450        ast::sizeType = translationUnit.global.sizeType;
1451        ast::dereferenceOperator = translationUnit.global.dereference;
1452        ast::dtorStruct = translationUnit.global.dtorStruct;
1453        ast::dtorStructDestroy = translationUnit.global.dtorDestroy;
1454
1455        ConverterNewToOld c;
1456        std::list< Declaration * > decls;
1457        for(auto d : translationUnit.decls) {
1458                decls.emplace_back( c.decl( d ) );
1459        }
1460        return decls;
1461}
1462
1463//================================================================================================
1464
1465class ConverterOldToNew : public Visitor {
1466public:
1467        ast::Decl * decl() {
1468                return strict_dynamic_cast< ast::Decl * >( node );
1469        }
1470
1471        ConverterOldToNew() = default;
1472        ConverterOldToNew(const ConverterOldToNew &) = delete;
1473        ConverterOldToNew(ConverterOldToNew &&) = delete;
1474private:
1475        /// conversion output
1476        ast::Node * node = nullptr;
1477        /// cache of nodes that might be referenced by readonly<> for de-duplication
1478        /// in case that some nodes are dropped by conversion (due to possible structural change)
1479        /// use smart pointers in cache value to prevent accidental invalidation.
1480        /// at conversion stage, all created nodes are guaranteed to be unique, therefore
1481        /// const_casting out of smart pointers is permitted.
1482        std::unordered_map< const BaseSyntaxNode *, ast::readonly<ast::Node> > cache = {};
1483
1484        // Local Utilities:
1485
1486        template<typename NewT, typename OldT>
1487        NewT * getAccept1( OldT old ) {
1488                if ( ! old ) return nullptr;
1489                old->accept(*this);
1490                ast::Node * ret = node;
1491                node = nullptr;
1492                return strict_dynamic_cast< NewT * >( ret );
1493        }
1494
1495#       define GET_ACCEPT_1(child, type) \
1496                getAccept1< ast::type, decltype( old->child ) >( old->child )
1497
1498#       define GET_ACCEPT_E(child, type) \
1499                getAccept1< ast::type, decltype( old->base ) >( old->base )
1500
1501        template<typename NewT, typename OldC>
1502        std::vector< ast::ptr<NewT> > getAcceptV( const OldC& old ) {
1503                std::vector< ast::ptr<NewT> > ret;
1504                ret.reserve( old.size() );
1505                for ( auto a : old ) {
1506                        a->accept( *this );
1507                        ret.emplace_back( strict_dynamic_cast< NewT * >(node) );
1508                        node = nullptr;
1509                }
1510                return ret;
1511        }
1512
1513#       define GET_ACCEPT_V(child, type) \
1514                getAcceptV< ast::type, decltype( old->child ) >( old->child )
1515
1516        template<typename NewT, typename OldC>
1517        std::deque< ast::ptr<NewT> > getAcceptD( const OldC& old ) {
1518                std::deque< ast::ptr<NewT> > ret;
1519                for ( auto a : old ) {
1520                        a->accept( *this );
1521                        ret.emplace_back( strict_dynamic_cast< NewT * >(node) );
1522                        node = nullptr;
1523                }
1524                return ret;
1525        }
1526
1527#       define GET_ACCEPT_D(child, type) \
1528                getAcceptD< ast::type, decltype( old->child ) >( old->child )
1529
1530        ast::Label make_label(const Label* old) {
1531                CodeLocation const & location =
1532                    ( old->labelled ) ? old->labelled->location : CodeLocation();
1533                return ast::Label(
1534                        location,
1535                        old->name,
1536                        GET_ACCEPT_V(attributes, Attribute)
1537                );
1538        }
1539
1540        template<template <class...> class C>
1541        C<ast::Label> make_labels(C<Label> olds) {
1542                C<ast::Label> ret;
1543                for (auto oldn : olds) {
1544                        ret.push_back( make_label( &oldn ) );
1545                }
1546                return ret;
1547        }
1548
1549#       define GET_LABELS_V(labels) \
1550                to<std::vector>::from( make_labels( std::move( labels ) ) )
1551
1552        static ast::CV::Qualifiers cv( const Type * ty ) { return { ty->tq.val }; }
1553
1554        /// returns true and sets `node` if in cache
1555        bool inCache( const BaseSyntaxNode * old ) {
1556                auto it = cache.find( old );
1557                if ( it == cache.end() ) return false;
1558                node = const_cast<ast::Node *>(it->second.get());
1559                return true;
1560        }
1561
1562        // Now all the visit functions:
1563
1564        virtual void visit( const ObjectDecl * old ) override final {
1565                auto&& type = GET_ACCEPT_1(type, Type);
1566                auto&& init = GET_ACCEPT_1(init, Init);
1567                auto&& bfwd = GET_ACCEPT_1(bitfieldWidth, Expr);
1568                auto&& attr = GET_ACCEPT_V(attributes, Attribute);
1569                if ( inCache( old ) ) {
1570                        return;
1571                }
1572                auto decl = new ast::ObjectDecl(
1573                        old->location,
1574                        old->name,
1575                        type,
1576                        init,
1577                        { old->get_storageClasses().val },
1578                        { old->linkage.val },
1579                        bfwd,
1580                        std::move(attr),
1581                        { old->get_funcSpec().val }
1582                );
1583                cache.emplace(old, decl);
1584                assert(cache.find( old ) != cache.end());
1585                decl->scopeLevel = old->scopeLevel;
1586                decl->mangleName = old->mangleName;
1587                decl->isDeleted  = old->isDeleted;
1588                decl->asmName    = GET_ACCEPT_1(asmName, Expr);
1589                decl->uniqueId   = old->uniqueId;
1590                decl->extension  = old->extension;
1591
1592                this->node = decl;
1593        }
1594
1595        virtual void visit( const FunctionDecl * old ) override final {
1596                if ( inCache( old ) ) return;
1597                auto paramVars = GET_ACCEPT_V(type->parameters, DeclWithType);
1598                auto returnVars = GET_ACCEPT_V(type->returnVals, DeclWithType);
1599                auto forall = GET_ACCEPT_V(type->forall, TypeDecl);
1600
1601                // function type is now derived from parameter decls instead of storing them
1602
1603                /*
1604                auto ftype = new ast::FunctionType((ast::ArgumentFlag)old->type->isVarArgs, cv(old->type));
1605                ftype->params.reserve(paramVars.size());
1606                ftype->returns.reserve(returnVars.size());
1607
1608                for (auto & v: paramVars) {
1609                        ftype->params.emplace_back(v->get_type());
1610                }
1611                for (auto & v: returnVars) {
1612                        ftype->returns.emplace_back(v->get_type());
1613                }
1614                ftype->forall = std::move(forall);
1615                */
1616
1617                // can function type have attributes? seems not to be the case.
1618                // visitType(old->type, ftype);
1619
1620                // collect assertions and put directly in FunctionDecl
1621                std::vector<ast::ptr<ast::DeclWithType>> assertions;
1622                for (auto & param: forall) {
1623                        for (auto & asst: param->assertions) {
1624                                assertf(asst->unique(), "newly converted decl must be unique");
1625                                assertions.emplace_back(asst);
1626                        }
1627                        auto mut = param.get_and_mutate();
1628                        assertf(mut == param, "newly converted decl must be unique");
1629                        mut->assertions.clear();
1630                }
1631
1632                auto decl = new ast::FunctionDecl{
1633                        old->location,
1634                        old->name,
1635                        // GET_ACCEPT_1(type, FunctionType),
1636                        std::move(forall),
1637                        std::move(paramVars),
1638                        std::move(returnVars),
1639                        {},
1640                        { old->storageClasses.val },
1641                        { old->linkage.val },
1642                        GET_ACCEPT_V(attributes, Attribute),
1643                        { old->get_funcSpec().val },
1644                        old->type->isVarArgs
1645                };
1646
1647                // decl->type = ftype;
1648                cache.emplace( old, decl );
1649
1650                decl->assertions = std::move(assertions);
1651                decl->withExprs = GET_ACCEPT_V(withExprs, Expr);
1652                decl->stmts = GET_ACCEPT_1(statements, CompoundStmt);
1653                decl->scopeLevel = old->scopeLevel;
1654                decl->mangleName = old->mangleName;
1655                decl->isDeleted  = old->isDeleted;
1656                decl->asmName    = GET_ACCEPT_1(asmName, Expr);
1657                decl->uniqueId   = old->uniqueId;
1658                decl->extension  = old->extension;
1659
1660                this->node = decl;
1661
1662                if ( Validate::dereferenceOperator == old ) {
1663                        ast::dereferenceOperator = decl;
1664                }
1665
1666                if ( Validate::dtorStructDestroy == old ) {
1667                        ast::dtorStructDestroy = decl;
1668                }
1669        }
1670
1671        virtual void visit( const StructDecl * old ) override final {
1672                if ( inCache( old ) ) return;
1673                auto decl = new ast::StructDecl(
1674                        old->location,
1675                        old->name,
1676                        (ast::AggregateDecl::Aggregate)old->kind,
1677                        GET_ACCEPT_V(attributes, Attribute),
1678                        { old->linkage.val }
1679                );
1680                cache.emplace( old, decl );
1681                decl->parent = GET_ACCEPT_1(parent, AggregateDecl);
1682                decl->body   = old->body;
1683                decl->params = GET_ACCEPT_V(parameters, TypeDecl);
1684                decl->members    = GET_ACCEPT_V(members, Decl);
1685                decl->extension  = old->extension;
1686                decl->uniqueId   = old->uniqueId;
1687                decl->storage    = { old->storageClasses.val };
1688
1689                this->node = decl;
1690
1691                if ( Validate::dtorStruct == old ) {
1692                        ast::dtorStruct = decl;
1693                }
1694        }
1695
1696        virtual void visit( const UnionDecl * old ) override final {
1697                if ( inCache( old ) ) return;
1698                auto decl = new ast::UnionDecl(
1699                        old->location,
1700                        old->name,
1701                        GET_ACCEPT_V(attributes, Attribute),
1702                        { old->linkage.val }
1703                );
1704                cache.emplace( old, decl );
1705                decl->parent = GET_ACCEPT_1(parent, AggregateDecl);
1706                decl->body   = old->body;
1707                decl->params = GET_ACCEPT_V(parameters, TypeDecl);
1708                decl->members    = GET_ACCEPT_V(members, Decl);
1709                decl->extension  = old->extension;
1710                decl->uniqueId   = old->uniqueId;
1711                decl->storage    = { old->storageClasses.val };
1712
1713                this->node = decl;
1714        }
1715
1716        // Marker
1717        // Convert SynTree::EnumDecl to AST::EnumDecl
1718        virtual void visit( const EnumDecl * old ) override final {
1719                if ( inCache( old ) ) return;
1720                auto decl = new ast::EnumDecl(
1721                        old->location,
1722                        old->name,
1723                        GET_ACCEPT_V(attributes, Attribute),
1724                        { old->linkage.val },
1725                        old->base? GET_ACCEPT_E(base, Type) : nullptr,
1726                        old->enumValues
1727                );
1728                cache.emplace( old, decl );
1729                decl->parent = GET_ACCEPT_1(parent, AggregateDecl);
1730                decl->body   = old->body;
1731                decl->params = GET_ACCEPT_V(parameters, TypeDecl);
1732                decl->members    = GET_ACCEPT_V(members, Decl);
1733                decl->extension  = old->extension;
1734                decl->uniqueId   = old->uniqueId;
1735                decl->storage    = { old->storageClasses.val };
1736                this->node = decl;
1737        }
1738
1739        virtual void visit( const TraitDecl * old ) override final {
1740                if ( inCache( old ) ) return;
1741                auto decl = new ast::TraitDecl(
1742                        old->location,
1743                        old->name,
1744                        GET_ACCEPT_V(attributes, Attribute),
1745                        { old->linkage.val }
1746                );
1747                cache.emplace( old, decl );
1748                decl->parent = GET_ACCEPT_1(parent, AggregateDecl);
1749                decl->body   = old->body;
1750                decl->params = GET_ACCEPT_V(parameters, TypeDecl);
1751                decl->members    = GET_ACCEPT_V(members, Decl);
1752                decl->extension  = old->extension;
1753                decl->uniqueId   = old->uniqueId;
1754                decl->storage    = { old->storageClasses.val };
1755
1756                this->node = decl;
1757        }
1758
1759        virtual void visit( const TypeDecl * old ) override final {
1760                if ( inCache( old ) ) return;
1761                auto decl = new ast::TypeDecl{
1762                        old->location,
1763                        old->name,
1764                        { old->storageClasses.val },
1765                        GET_ACCEPT_1(base, Type),
1766                        (ast::TypeDecl::Kind)(unsigned)old->kind,
1767                        old->sized,
1768                        GET_ACCEPT_1(init, Type)
1769                };
1770                cache.emplace( old, decl );
1771                decl->assertions = GET_ACCEPT_V(assertions, DeclWithType);
1772                decl->extension  = old->extension;
1773                decl->uniqueId   = old->uniqueId;
1774
1775                this->node = decl;
1776        }
1777
1778        virtual void visit( const TypedefDecl * old ) override final {
1779                auto decl = new ast::TypedefDecl(
1780                        old->location,
1781                        old->name,
1782                        { old->storageClasses.val },
1783                        GET_ACCEPT_1(base, Type),
1784                        { old->linkage.val }
1785                );
1786                decl->assertions = GET_ACCEPT_V(assertions, DeclWithType);
1787                decl->extension  = old->extension;
1788                decl->uniqueId   = old->uniqueId;
1789                decl->storage    = { old->storageClasses.val };
1790
1791                this->node = decl;
1792        }
1793
1794        virtual void visit( const AsmDecl * old ) override final {
1795                auto decl = new ast::AsmDecl{
1796                        old->location,
1797                        GET_ACCEPT_1(stmt, AsmStmt)
1798                };
1799                decl->extension  = old->extension;
1800                decl->uniqueId   = old->uniqueId;
1801                decl->storage    = { old->storageClasses.val };
1802
1803                this->node = decl;
1804        }
1805
1806        virtual void visit( const DirectiveDecl * old ) override final {
1807                auto decl = new ast::DirectiveDecl{
1808                        old->location,
1809                        GET_ACCEPT_1(stmt, DirectiveStmt)
1810                };
1811                decl->extension  = old->extension;
1812                decl->uniqueId   = old->uniqueId;
1813                decl->storage    = { old->storageClasses.val };
1814
1815                this->node = decl;
1816        }
1817
1818        virtual void visit( const StaticAssertDecl * old ) override final {
1819                auto decl = new ast::StaticAssertDecl{
1820                        old->location,
1821                        GET_ACCEPT_1(condition, Expr),
1822                        GET_ACCEPT_1(message, ConstantExpr)
1823                };
1824                decl->extension  = old->extension;
1825                decl->uniqueId   = old->uniqueId;
1826                decl->storage    = { old->storageClasses.val };
1827
1828                this->node = decl;
1829        }
1830
1831        virtual void visit( const CompoundStmt * old ) override final {
1832                if ( inCache( old ) ) return;
1833                auto stmt = new ast::CompoundStmt(
1834                        old->location,
1835                        to<std::list>::from( GET_ACCEPT_V(kids, Stmt) ),
1836                        GET_LABELS_V(old->labels)
1837                );
1838
1839                this->node = stmt;
1840                cache.emplace( old, this->node );
1841        }
1842
1843        virtual void visit( const ExprStmt * old ) override final {
1844                if ( inCache( old ) ) return;
1845                this->node = new ast::ExprStmt(
1846                        old->location,
1847                        GET_ACCEPT_1(expr, Expr),
1848                        GET_LABELS_V(old->labels)
1849                );
1850                cache.emplace( old, this->node );
1851        }
1852
1853        virtual void visit( const AsmStmt * old ) override final {
1854                if ( inCache( old ) ) return;
1855                this->node = new ast::AsmStmt(
1856                        old->location,
1857                        old->voltile,
1858                        GET_ACCEPT_1(instruction, Expr),
1859                        GET_ACCEPT_V(output, Expr),
1860                        GET_ACCEPT_V(input, Expr),
1861                        GET_ACCEPT_V(clobber, ConstantExpr),
1862                        GET_LABELS_V(old->gotolabels),
1863                        GET_LABELS_V(old->labels)
1864                );
1865                cache.emplace( old, this->node );
1866        }
1867
1868        virtual void visit( const DirectiveStmt * old ) override final {
1869                if ( inCache( old ) ) return;
1870                this->node = new ast::DirectiveStmt(
1871                        old->location,
1872                        old->directive,
1873                        GET_LABELS_V(old->labels)
1874                );
1875                cache.emplace( old, this->node );
1876        }
1877
1878        virtual void visit( const IfStmt * old ) override final {
1879                if ( inCache( old ) ) return;
1880                this->node = new ast::IfStmt(
1881                        old->location,
1882                        GET_ACCEPT_1(condition, Expr),
1883                        GET_ACCEPT_1(then, Stmt),
1884                        GET_ACCEPT_1(else_, Stmt),
1885                        GET_ACCEPT_V(initialization, Stmt),
1886                        GET_LABELS_V(old->labels)
1887                );
1888                cache.emplace( old, this->node );
1889        }
1890
1891        virtual void visit( const SwitchStmt * old ) override final {
1892                if ( inCache( old ) ) return;
1893                this->node = new ast::SwitchStmt(
1894                        old->location,
1895                        GET_ACCEPT_1(condition, Expr),
1896                        GET_ACCEPT_V(statements, Stmt),
1897                        GET_LABELS_V(old->labels)
1898                );
1899                cache.emplace( old, this->node );
1900        }
1901
1902        virtual void visit( const CaseStmt * old ) override final {
1903                if ( inCache( old ) ) return;
1904                this->node = new ast::CaseStmt(
1905                        old->location,
1906                        GET_ACCEPT_1(condition, Expr),
1907                        GET_ACCEPT_V(stmts, Stmt),
1908                        GET_LABELS_V(old->labels)
1909                );
1910                cache.emplace( old, this->node );
1911        }
1912
1913        virtual void visit( const WhileDoStmt * old ) override final {
1914                if ( inCache( old ) ) return;
1915                this->node = new ast::WhileDoStmt(
1916                        old->location,
1917                        GET_ACCEPT_1(condition, Expr),
1918                        GET_ACCEPT_1(body, Stmt),
1919                        GET_ACCEPT_1(else_, Stmt),
1920                        GET_ACCEPT_V(initialization, Stmt),
1921                        old->isDoWhile,
1922                        GET_LABELS_V(old->labels)
1923                );
1924                cache.emplace( old, this->node );
1925        }
1926
1927        virtual void visit( const ForStmt * old ) override final {
1928                if ( inCache( old ) ) return;
1929                this->node = new ast::ForStmt(
1930                        old->location,
1931                        GET_ACCEPT_V(initialization, Stmt),
1932                        GET_ACCEPT_1(condition, Expr),
1933                        GET_ACCEPT_1(increment, Expr),
1934                        GET_ACCEPT_1(body, Stmt),
1935                        GET_ACCEPT_1(else_, Stmt),
1936                        GET_LABELS_V(old->labels)
1937                );
1938                cache.emplace( old, this->node );
1939        }
1940
1941        virtual void visit( const BranchStmt * old ) override final {
1942                if ( inCache( old ) ) return;
1943                if (old->computedTarget) {
1944                        this->node = new ast::BranchStmt(
1945                                old->location,
1946                                GET_ACCEPT_1(computedTarget, Expr),
1947                                GET_LABELS_V(old->labels)
1948                        );
1949                } else {
1950                        ast::BranchStmt::Kind kind;
1951                        switch (old->type) {
1952                        #define CASE(n) \
1953                        case BranchStmt::n: \
1954                                kind = ast::BranchStmt::n; \
1955                                break
1956                        CASE(Goto);
1957                        CASE(Break);
1958                        CASE(Continue);
1959                        CASE(FallThrough);
1960                        CASE(FallThroughDefault);
1961                        #undef CASE
1962                        default:
1963                                assertf(false, "Invalid BranchStmt::Type %d\n", old->type);
1964                        }
1965
1966                        auto stmt = new ast::BranchStmt(
1967                                old->location,
1968                                kind,
1969                                make_label(&old->originalTarget),
1970                                GET_LABELS_V(old->labels)
1971                        );
1972                        stmt->target = make_label(&old->target);
1973                        this->node = stmt;
1974                }
1975                cache.emplace( old, this->node );
1976        }
1977
1978        virtual void visit( const ReturnStmt * old ) override final {
1979                if ( inCache( old ) ) return;
1980                this->node = new ast::ReturnStmt(
1981                        old->location,
1982                        GET_ACCEPT_1(expr, Expr),
1983                        GET_LABELS_V(old->labels)
1984                );
1985                cache.emplace( old, this->node );
1986        }
1987
1988        virtual void visit( const ThrowStmt * old ) override final {
1989                if ( inCache( old ) ) return;
1990                ast::ExceptionKind kind;
1991                switch (old->kind) {
1992                case ThrowStmt::Terminate:
1993                        kind = ast::ExceptionKind::Terminate;
1994                        break;
1995                case ThrowStmt::Resume:
1996                        kind = ast::ExceptionKind::Resume;
1997                        break;
1998                default:
1999                        assertf(false, "Invalid ThrowStmt::Kind %d\n", old->kind);
2000                }
2001
2002                this->node = new ast::ThrowStmt(
2003                        old->location,
2004                        kind,
2005                        GET_ACCEPT_1(expr, Expr),
2006                        GET_ACCEPT_1(target, Expr),
2007                        GET_LABELS_V(old->labels)
2008                );
2009                cache.emplace( old, this->node );
2010        }
2011
2012        virtual void visit( const TryStmt * old ) override final {
2013                if ( inCache( old ) ) return;
2014                this->node = new ast::TryStmt(
2015                        old->location,
2016                        GET_ACCEPT_1(block, CompoundStmt),
2017                        GET_ACCEPT_V(handlers, CatchStmt),
2018                        GET_ACCEPT_1(finallyBlock, FinallyStmt),
2019                        GET_LABELS_V(old->labels)
2020                );
2021                cache.emplace( old, this->node );
2022        }
2023
2024        virtual void visit( const CatchStmt * old ) override final {
2025                if ( inCache( old ) ) return;
2026                ast::ExceptionKind kind;
2027                switch (old->kind) {
2028                case CatchStmt::Terminate:
2029                        kind = ast::ExceptionKind::Terminate;
2030                        break;
2031                case CatchStmt::Resume:
2032                        kind = ast::ExceptionKind::Resume;
2033                        break;
2034                default:
2035                        assertf(false, "Invalid CatchStmt::Kind %d\n", old->kind);
2036                }
2037
2038                this->node = new ast::CatchStmt(
2039                        old->location,
2040                        kind,
2041                        GET_ACCEPT_1(decl, Decl),
2042                        GET_ACCEPT_1(cond, Expr),
2043                        GET_ACCEPT_1(body, Stmt),
2044                        GET_LABELS_V(old->labels)
2045                );
2046                cache.emplace( old, this->node );
2047        }
2048
2049        virtual void visit( const FinallyStmt * old ) override final {
2050                if ( inCache( old ) ) return;
2051                this->node = new ast::FinallyStmt(
2052                        old->location,
2053                        GET_ACCEPT_1(block, CompoundStmt),
2054                        GET_LABELS_V(old->labels)
2055                );
2056                cache.emplace( old, this->node );
2057        }
2058
2059        virtual void visit( const SuspendStmt * old ) override final {
2060                if ( inCache( old ) ) return;
2061                ast::SuspendStmt::Type type;
2062                switch (old->type) {
2063                        case SuspendStmt::Coroutine: type = ast::SuspendStmt::Coroutine; break;
2064                        case SuspendStmt::Generator: type = ast::SuspendStmt::Generator; break;
2065                        case SuspendStmt::None     : type = ast::SuspendStmt::None     ; break;
2066                        default: abort();
2067                }
2068                this->node = new ast::SuspendStmt(
2069                        old->location,
2070                        GET_ACCEPT_1(then  , CompoundStmt),
2071                        type,
2072                        GET_LABELS_V(old->labels)
2073                );
2074                cache.emplace( old, this->node );
2075        }
2076
2077        virtual void visit( const WaitForStmt * old ) override final {
2078                if ( inCache( old ) ) return;
2079                ast::WaitForStmt * stmt = new ast::WaitForStmt(
2080                        old->location,
2081                        GET_LABELS_V(old->labels)
2082                );
2083
2084                stmt->clauses.reserve( old->clauses.size() );
2085                for (size_t i = 0 ; i < old->clauses.size() ; ++i) {
2086                        stmt->clauses.push_back({
2087                                ast::WaitForStmt::Target{
2088                                        GET_ACCEPT_1(clauses[i].target.function, Expr),
2089                                        GET_ACCEPT_V(clauses[i].target.arguments, Expr)
2090                                },
2091                                GET_ACCEPT_1(clauses[i].statement, Stmt),
2092                                GET_ACCEPT_1(clauses[i].condition, Expr)
2093                        });
2094                }
2095                stmt->timeout = {
2096                        GET_ACCEPT_1(timeout.time, Expr),
2097                        GET_ACCEPT_1(timeout.statement, Stmt),
2098                        GET_ACCEPT_1(timeout.condition, Expr),
2099                };
2100                stmt->orElse = {
2101                        GET_ACCEPT_1(orelse.statement, Stmt),
2102                        GET_ACCEPT_1(orelse.condition, Expr),
2103                };
2104
2105                this->node = stmt;
2106                cache.emplace( old, this->node );
2107        }
2108
2109        virtual void visit( const WithStmt * old ) override final {
2110                if ( inCache( old ) ) return;
2111                this->node = new ast::WithStmt(
2112                        old->location,
2113                        GET_ACCEPT_V(exprs, Expr),
2114                        GET_ACCEPT_1(stmt, Stmt)
2115                );
2116                cache.emplace( old, this->node );
2117        }
2118
2119        virtual void visit( const NullStmt * old ) override final {
2120                if ( inCache( old ) ) return;
2121                this->node = new ast::NullStmt(
2122                        old->location,
2123                        GET_LABELS_V(old->labels)
2124                );
2125                cache.emplace( old, this->node );
2126        }
2127
2128        virtual void visit( const DeclStmt * old ) override final {
2129                if ( inCache( old ) ) return;
2130                this->node = new ast::DeclStmt(
2131                        old->location,
2132                        GET_ACCEPT_1(decl, Decl),
2133                        GET_LABELS_V(old->labels)
2134                );
2135                cache.emplace( old, this->node );
2136        }
2137
2138        virtual void visit( const ImplicitCtorDtorStmt * old ) override final {
2139                if ( inCache( old ) ) return;
2140                auto stmt = new ast::ImplicitCtorDtorStmt(
2141                        old->location,
2142                        nullptr,
2143                        GET_LABELS_V(old->labels)
2144                );
2145                cache.emplace( old, stmt );
2146                stmt->callStmt = GET_ACCEPT_1(callStmt, Stmt);
2147                this->node = stmt;
2148        }
2149
2150        virtual void visit( const MutexStmt * old ) override final {
2151                if ( inCache( old ) ) return;
2152                this->node = new ast::MutexStmt(
2153                        old->location,
2154                        GET_ACCEPT_1(stmt, Stmt),
2155                        GET_ACCEPT_V(mutexObjs, Expr)
2156                );
2157                cache.emplace( old, this->node );
2158        }
2159
2160        // TypeSubstitution shouldn't exist yet in old.
2161        ast::TypeSubstitution * convertTypeSubstitution(const TypeSubstitution * old) {
2162               
2163                if (!old) return nullptr;
2164                if (old->empty()) return nullptr;
2165                assert(false);
2166
2167                /*
2168                ast::TypeSubstitution *rslt = new ast::TypeSubstitution();
2169
2170                for (decltype(old->begin()) old_i = old->begin(); old_i != old->end(); old_i++) {
2171                        rslt->add( old_i->first,
2172                                   getAccept1<ast::Type>(old_i->second) );
2173                }
2174
2175                return rslt;
2176                */
2177        }
2178
2179        void convertInferUnion(ast::Expr::InferUnion               &newInferred,
2180                                                   const std::map<UniqueId,ParamEntry> &oldInferParams,
2181                                                   const std::vector<UniqueId>         &oldResnSlots) {
2182
2183                assert( oldInferParams.empty() || oldResnSlots.empty() );
2184                // assert( newInferred.mode == ast::Expr::InferUnion::Empty );
2185
2186                if ( !oldInferParams.empty() ) {
2187                        ast::InferredParams &tgt = newInferred.inferParams();
2188                        for (auto & old : oldInferParams) {
2189                                tgt[old.first] = ast::ParamEntry(
2190                                        old.second.decl,
2191                                        getAccept1<ast::Decl>(old.second.declptr),
2192                                        getAccept1<ast::Type>(old.second.actualType),
2193                                        getAccept1<ast::Type>(old.second.formalType),
2194                                        getAccept1<ast::Expr>(old.second.expr)
2195                                );
2196                        }
2197                } else if ( !oldResnSlots.empty() ) {
2198                        ast::ResnSlots &tgt = newInferred.resnSlots();
2199                        for (auto old : oldResnSlots) {
2200                                tgt.push_back(old);
2201                        }
2202                }
2203        }
2204
2205        ast::Expr * visitBaseExpr_SkipResultType( const Expression * old, ast::Expr * nw) {
2206
2207                nw->env    = convertTypeSubstitution(old->env);
2208
2209                nw->extension = old->extension;
2210                convertInferUnion(nw->inferred, old->inferParams, old->resnSlots);
2211
2212                return nw;
2213        }
2214
2215        ast::Expr * visitBaseExpr( const Expression * old, ast::Expr * nw) {
2216
2217                nw->result = GET_ACCEPT_1(result, Type);
2218                return visitBaseExpr_SkipResultType(old, nw);;
2219        }
2220
2221        virtual void visit( const ApplicationExpr * old ) override final {
2222                this->node = visitBaseExpr( old,
2223                        new ast::ApplicationExpr(
2224                                old->location,
2225                                GET_ACCEPT_1(function, Expr),
2226                                GET_ACCEPT_V(args, Expr)
2227                        )
2228                );
2229        }
2230
2231        virtual void visit( const UntypedExpr * old ) override final {
2232                this->node = visitBaseExpr( old,
2233                        new ast::UntypedExpr(
2234                                old->location,
2235                                GET_ACCEPT_1(function, Expr),
2236                                GET_ACCEPT_V(args, Expr)
2237                        )
2238                );
2239        }
2240
2241        virtual void visit( const NameExpr * old ) override final {
2242                this->node = visitBaseExpr( old,
2243                        new ast::NameExpr(
2244                                old->location,
2245                                old->get_name()
2246                        )
2247                );
2248        }
2249
2250        virtual void visit( const CastExpr * old ) override final {
2251                this->node = visitBaseExpr( old,
2252                        new ast::CastExpr(
2253                                old->location,
2254                                GET_ACCEPT_1(arg, Expr),
2255                                old->isGenerated ? ast::GeneratedCast : ast::ExplicitCast
2256                        )
2257                );
2258        }
2259
2260        virtual void visit( const KeywordCastExpr * old ) override final {
2261                ast::AggregateDecl::Aggregate castTarget = (ast::AggregateDecl::Aggregate)old->target;
2262                assert( ast::AggregateDecl::Generator <= castTarget && castTarget <= ast::AggregateDecl::Thread );
2263                this->node = visitBaseExpr( old,
2264                        new ast::KeywordCastExpr(
2265                                old->location,
2266                                GET_ACCEPT_1(arg, Expr),
2267                                castTarget,
2268                                {old->concrete_target.field, old->concrete_target.getter}
2269                        )
2270                );
2271        }
2272
2273        virtual void visit( const VirtualCastExpr * old ) override final {
2274                this->node = visitBaseExpr_SkipResultType( old,
2275                        new ast::VirtualCastExpr(
2276                                old->location,
2277                                GET_ACCEPT_1(arg, Expr),
2278                                GET_ACCEPT_1(result, Type)
2279                        )
2280                );
2281        }
2282
2283        virtual void visit( const AddressExpr * old ) override final {
2284                this->node = visitBaseExpr( old,
2285                        new ast::AddressExpr(
2286                                old->location,
2287                                GET_ACCEPT_1(arg, Expr)
2288                        )
2289                );
2290        }
2291
2292        virtual void visit( const LabelAddressExpr * old ) override final {
2293                this->node = visitBaseExpr( old,
2294                        new ast::LabelAddressExpr(
2295                                old->location,
2296                                make_label(&old->arg)
2297                        )
2298                );
2299        }
2300
2301        virtual void visit( const UntypedMemberExpr * old ) override final {
2302                this->node = visitBaseExpr( old,
2303                        new ast::UntypedMemberExpr(
2304                                old->location,
2305                                GET_ACCEPT_1(member, Expr),
2306                                GET_ACCEPT_1(aggregate, Expr)
2307                        )
2308                );
2309        }
2310
2311        virtual void visit( const MemberExpr * old ) override final {
2312                this->node = visitBaseExpr( old,
2313                        new ast::MemberExpr(
2314                                old->location,
2315                                GET_ACCEPT_1(member, DeclWithType),
2316                                GET_ACCEPT_1(aggregate, Expr),
2317                                ast::MemberExpr::NoOpConstructionChosen
2318                        )
2319                );
2320        }
2321
2322        virtual void visit( const VariableExpr * old ) override final {
2323                auto expr = new ast::VariableExpr(
2324                        old->location
2325                );
2326
2327                expr->var = GET_ACCEPT_1(var, DeclWithType);
2328                visitBaseExpr( old, expr );
2329
2330                this->node = expr;
2331        }
2332
2333        virtual void visit( const ConstantExpr * old ) override final {
2334                ast::ConstantExpr *rslt = new ast::ConstantExpr(
2335                        old->location,
2336                        GET_ACCEPT_1(result, Type),
2337                        old->constant.rep,
2338                        old->constant.ival
2339                );
2340                rslt->underlyer = getAccept1< ast::Type, Type* >( old->constant.type );
2341                this->node = visitBaseExpr( old, rslt );
2342        }
2343
2344        virtual void visit( const SizeofExpr * old ) override final {
2345                assert (old->expr || old->type);
2346                assert (! (old->expr && old->type));
2347                ast::SizeofExpr *rslt;
2348                if (old->expr) {
2349                        assert(!old->isType);
2350                        rslt = new ast::SizeofExpr(
2351                                old->location,
2352                                GET_ACCEPT_1(expr, Expr)
2353                        );
2354                }
2355                if (old->type) {
2356                        assert(old->isType);
2357                        rslt = new ast::SizeofExpr(
2358                                old->location,
2359                                GET_ACCEPT_1(type, Type)
2360                        );
2361                }
2362                this->node = visitBaseExpr( old, rslt );
2363        }
2364
2365        virtual void visit( const AlignofExpr * old ) override final {
2366                assert (old->expr || old->type);
2367                assert (! (old->expr && old->type));
2368                ast::AlignofExpr *rslt;
2369                if (old->expr) {
2370                        assert(!old->isType);
2371                        rslt = new ast::AlignofExpr(
2372                                old->location,
2373                                GET_ACCEPT_1(expr, Expr)
2374                        );
2375                }
2376                if (old->type) {
2377                        assert(old->isType);
2378                        rslt = new ast::AlignofExpr(
2379                                old->location,
2380                                GET_ACCEPT_1(type, Type)
2381                        );
2382                }
2383                this->node = visitBaseExpr( old, rslt );
2384        }
2385
2386        virtual void visit( const UntypedOffsetofExpr * old ) override final {
2387                this->node = visitBaseExpr( old,
2388                        new ast::UntypedOffsetofExpr(
2389                                old->location,
2390                                GET_ACCEPT_1(type, Type),
2391                                old->member
2392                        )
2393                );
2394        }
2395
2396        virtual void visit( const OffsetofExpr * old ) override final {
2397                this->node = visitBaseExpr( old,
2398                        new ast::OffsetofExpr(
2399                                old->location,
2400                                GET_ACCEPT_1(type, Type),
2401                                GET_ACCEPT_1(member, DeclWithType)
2402                        )
2403                );
2404        }
2405
2406        virtual void visit( const OffsetPackExpr * old ) override final {
2407                this->node = visitBaseExpr( old,
2408                        new ast::OffsetPackExpr(
2409                                old->location,
2410                                GET_ACCEPT_1(type, StructInstType)
2411                        )
2412                );
2413        }
2414
2415        virtual void visit( const LogicalExpr * old ) override final {
2416                this->node = visitBaseExpr( old,
2417                        new ast::LogicalExpr(
2418                                old->location,
2419                                GET_ACCEPT_1(arg1, Expr),
2420                                GET_ACCEPT_1(arg2, Expr),
2421                                old->get_isAnd() ?
2422                                        ast::LogicalFlag::AndExpr :
2423                                        ast::LogicalFlag::OrExpr
2424                        )
2425                );
2426        }
2427
2428        virtual void visit( const ConditionalExpr * old ) override final {
2429                this->node = visitBaseExpr( old,
2430                        new ast::ConditionalExpr(
2431                                old->location,
2432                                GET_ACCEPT_1(arg1, Expr),
2433                                GET_ACCEPT_1(arg2, Expr),
2434                                GET_ACCEPT_1(arg3, Expr)
2435                        )
2436                );
2437        }
2438
2439        virtual void visit( const CommaExpr * old ) override final {
2440                this->node = visitBaseExpr( old,
2441                        new ast::CommaExpr(
2442                                old->location,
2443                                GET_ACCEPT_1(arg1, Expr),
2444                                GET_ACCEPT_1(arg2, Expr)
2445                        )
2446                );
2447        }
2448
2449        virtual void visit( const TypeExpr * old ) override final {
2450                this->node = visitBaseExpr( old,
2451                        new ast::TypeExpr(
2452                                old->location,
2453                                GET_ACCEPT_1(type, Type)
2454                        )
2455                );
2456        }
2457
2458        virtual void visit( const DimensionExpr * old ) override final {
2459                // DimensionExpr gets desugared away in Validate.
2460                // As long as new-AST passes don't use it, this cheap-cheerful error
2461                // detection helps ensure that these occurrences have been compiled
2462                // away, as expected.  To move the DimensionExpr boundary downstream
2463                // or move the new-AST translation boundary upstream, implement
2464                // DimensionExpr in the new AST and implement a conversion.
2465                (void) old;
2466                assert(false && "DimensionExpr should not be present at new-AST boundary");
2467        }
2468
2469        virtual void visit( const AsmExpr * old ) override final {
2470                this->node = visitBaseExpr( old,
2471                        new ast::AsmExpr(
2472                                old->location,
2473                                old->inout,
2474                                GET_ACCEPT_1(constraint, Expr),
2475                                GET_ACCEPT_1(operand, Expr)
2476                        )
2477                );
2478        }
2479
2480        virtual void visit( const ImplicitCopyCtorExpr * old ) override final {
2481                auto rslt = new ast::ImplicitCopyCtorExpr(
2482                        old->location,
2483                        GET_ACCEPT_1(callExpr, ApplicationExpr)
2484                );
2485
2486                this->node = visitBaseExpr( old, rslt );
2487        }
2488
2489        virtual void visit( const ConstructorExpr * old ) override final {
2490                this->node = visitBaseExpr( old,
2491                        new ast::ConstructorExpr(
2492                                old->location,
2493                                GET_ACCEPT_1(callExpr, Expr)
2494                        )
2495                );
2496        }
2497
2498        virtual void visit( const CompoundLiteralExpr * old ) override final {
2499                this->node = visitBaseExpr_SkipResultType( old,
2500                        new ast::CompoundLiteralExpr(
2501                                old->location,
2502                                GET_ACCEPT_1(result, Type),
2503                                GET_ACCEPT_1(initializer, Init)
2504                        )
2505                );
2506        }
2507
2508        virtual void visit( const RangeExpr * old ) override final {
2509                this->node = visitBaseExpr( old,
2510                        new ast::RangeExpr(
2511                                old->location,
2512                                GET_ACCEPT_1(low, Expr),
2513                                GET_ACCEPT_1(high, Expr)
2514                        )
2515                );
2516        }
2517
2518        virtual void visit( const UntypedTupleExpr * old ) override final {
2519                this->node = visitBaseExpr( old,
2520                        new ast::UntypedTupleExpr(
2521                                old->location,
2522                                GET_ACCEPT_V(exprs, Expr)
2523                        )
2524                );
2525        }
2526
2527        virtual void visit( const TupleExpr * old ) override final {
2528                this->node = visitBaseExpr( old,
2529                        new ast::TupleExpr(
2530                                old->location,
2531                                GET_ACCEPT_V(exprs, Expr)
2532                        )
2533                );
2534        }
2535
2536        virtual void visit( const TupleIndexExpr * old ) override final {
2537                this->node = visitBaseExpr( old,
2538                        new ast::TupleIndexExpr(
2539                                old->location,
2540                                GET_ACCEPT_1(tuple, Expr),
2541                                old->index
2542                        )
2543                );
2544        }
2545
2546        virtual void visit( const TupleAssignExpr * old ) override final {
2547                this->node = visitBaseExpr_SkipResultType( old,
2548                        new ast::TupleAssignExpr(
2549                                old->location,
2550                                GET_ACCEPT_1(result, Type),
2551                                GET_ACCEPT_1(stmtExpr, StmtExpr)
2552                        )
2553                );
2554        }
2555
2556        virtual void visit( const StmtExpr * old ) override final {
2557                auto rslt = new ast::StmtExpr(
2558                        old->location,
2559                        GET_ACCEPT_1(statements, CompoundStmt)
2560                );
2561                rslt->returnDecls = GET_ACCEPT_V(returnDecls, ObjectDecl);
2562                rslt->dtors       = GET_ACCEPT_V(dtors      , Expr);
2563
2564                this->node = visitBaseExpr_SkipResultType( old, rslt );
2565        }
2566
2567        virtual void visit( const UniqueExpr * old ) override final {
2568                auto rslt = new ast::UniqueExpr(
2569                        old->location,
2570                        GET_ACCEPT_1(expr, Expr),
2571                        old->get_id()
2572                );
2573                rslt->object = GET_ACCEPT_1(object, ObjectDecl);
2574                rslt->var    = GET_ACCEPT_1(var   , VariableExpr);
2575
2576                this->node = visitBaseExpr( old, rslt );
2577        }
2578
2579        virtual void visit( const UntypedInitExpr * old ) override final {
2580                std::deque<ast::InitAlternative> initAlts;
2581                for (auto ia : old->initAlts) {
2582                        initAlts.push_back(ast::InitAlternative(
2583                                getAccept1< ast::Type, Type * >( ia.type ),
2584                                getAccept1< ast::Designation, Designation * >( ia.designation )
2585                        ));
2586                }
2587                this->node = visitBaseExpr( old,
2588                        new ast::UntypedInitExpr(
2589                                old->location,
2590                                GET_ACCEPT_1(expr, Expr),
2591                                std::move(initAlts)
2592                        )
2593                );
2594        }
2595
2596        virtual void visit( const InitExpr * old ) override final {
2597                this->node = visitBaseExpr( old,
2598                        new ast::InitExpr(
2599                                old->location,
2600                                GET_ACCEPT_1(expr, Expr),
2601                                GET_ACCEPT_1(designation, Designation)
2602                        )
2603                );
2604        }
2605
2606        virtual void visit( const DeletedExpr * old ) override final {
2607                this->node = visitBaseExpr( old,
2608                        new ast::DeletedExpr(
2609                                old->location,
2610                                GET_ACCEPT_1(expr, Expr),
2611                                inCache(old->deleteStmt) ?
2612                                        strict_dynamic_cast<ast::Decl*>(this->node) :
2613                                        GET_ACCEPT_1(deleteStmt, Decl)
2614                        )
2615                );
2616        }
2617
2618        virtual void visit( const DefaultArgExpr * old ) override final {
2619                this->node = visitBaseExpr( old,
2620                        new ast::DefaultArgExpr(
2621                                old->location,
2622                                GET_ACCEPT_1(expr, Expr)
2623                        )
2624                );
2625        }
2626
2627        virtual void visit( const GenericExpr * old ) override final {
2628                std::vector<ast::GenericExpr::Association> associations;
2629                for (auto association : old->associations) {
2630                        associations.push_back(ast::GenericExpr::Association(
2631                                getAccept1< ast::Type, Type * >( association.type ),
2632                                getAccept1< ast::Expr, Expression * >( association.expr )
2633                        ));
2634                }
2635                this->node = visitBaseExpr( old,
2636                        new ast::GenericExpr(
2637                                old->location,
2638                                GET_ACCEPT_1(control, Expr),
2639                                std::move(associations)
2640                        )
2641                );
2642        }
2643
2644        void visitType( const Type * old, ast::Type * type ) {
2645                // Some types do this in their constructor so add a check.
2646                if ( !old->attributes.empty() && type->attributes.empty() ) {
2647                        type->attributes = GET_ACCEPT_V(attributes, Attribute);
2648                }
2649                this->node = type;
2650        }
2651
2652        virtual void visit( const VoidType * old ) override final {
2653                visitType( old, new ast::VoidType{ cv( old ) } );
2654        }
2655
2656        virtual void visit( const BasicType * old ) override final {
2657                auto type = new ast::BasicType{ (ast::BasicType::Kind)(unsigned)old->kind, cv( old ) };
2658                // I believe this should always be a BasicType.
2659                if ( Validate::SizeType == old ) {
2660                        ast::sizeType = type;
2661                }
2662                visitType( old, type );
2663        }
2664
2665        virtual void visit( const PointerType * old ) override final {
2666                visitType( old, new ast::PointerType{
2667                        GET_ACCEPT_1( base, Type ),
2668                        GET_ACCEPT_1( dimension, Expr ),
2669                        (ast::LengthFlag)old->isVarLen,
2670                        (ast::DimensionFlag)old->isStatic,
2671                        cv( old )
2672                } );
2673        }
2674
2675        virtual void visit( const ArrayType * old ) override final {
2676                visitType( old, new ast::ArrayType{
2677                        GET_ACCEPT_1( base, Type ),
2678                        GET_ACCEPT_1( dimension, Expr ),
2679                        (ast::LengthFlag)old->isVarLen,
2680                        (ast::DimensionFlag)old->isStatic,
2681                        cv( old )
2682                } );
2683        }
2684
2685        virtual void visit( const ReferenceType * old ) override final {
2686                visitType( old, new ast::ReferenceType{
2687                        GET_ACCEPT_1( base, Type ),
2688                        cv( old )
2689                } );
2690        }
2691
2692        virtual void visit( const QualifiedType * old ) override final {
2693                visitType( old, new ast::QualifiedType{
2694                        GET_ACCEPT_1( parent, Type ),
2695                        GET_ACCEPT_1( child, Type ),
2696                        cv( old )
2697                } );
2698        }
2699
2700        virtual void visit( const FunctionType * old ) override final {
2701                auto ty = new ast::FunctionType {
2702                        (ast::ArgumentFlag)old->isVarArgs,
2703                        cv( old )
2704                };
2705                auto returnVars = GET_ACCEPT_V(returnVals, DeclWithType);
2706                auto paramVars = GET_ACCEPT_V(parameters, DeclWithType);
2707                // ty->returns = GET_ACCEPT_V( returnVals, DeclWithType );
2708                // ty->params = GET_ACCEPT_V( parameters, DeclWithType );
2709                for (auto & v: returnVars) {
2710                        ty->returns.emplace_back(v->get_type());
2711                }
2712                for (auto & v: paramVars) {
2713                        ty->params.emplace_back(v->get_type());
2714                }
2715                // xxx - when will this be non-null?
2716                // will have to create dangling (no-owner) decls to be pointed to
2717                auto foralls = GET_ACCEPT_V( forall, TypeDecl );
2718
2719                for (auto & param : foralls) {
2720                        ty->forall.emplace_back(new ast::TypeInstType(param->name, param));
2721                        for (auto asst : param->assertions) {
2722                                ty->assertions.emplace_back(new ast::VariableExpr({}, asst));
2723                        }
2724                }
2725                visitType( old, ty );
2726        }
2727
2728        void postvisit( const ReferenceToType * old, ast::BaseInstType * ty ) {
2729                ty->params = GET_ACCEPT_V( parameters, Expr );
2730                ty->hoistType = old->hoistType;
2731                visitType( old, ty );
2732        }
2733
2734        virtual void visit( const StructInstType * old ) override final {
2735                ast::StructInstType * ty;
2736                if ( old->baseStruct ) {
2737                        ty = new ast::StructInstType{
2738                                GET_ACCEPT_1( baseStruct, StructDecl ),
2739                                cv( old ),
2740                                GET_ACCEPT_V( attributes, Attribute )
2741                        };
2742                } else {
2743                        ty = new ast::StructInstType{
2744                                old->name,
2745                                cv( old ),
2746                                GET_ACCEPT_V( attributes, Attribute )
2747                        };
2748                }
2749                postvisit( old, ty );
2750        }
2751
2752        virtual void visit( const UnionInstType * old ) override final {
2753                ast::UnionInstType * ty;
2754                if ( old->baseUnion ) {
2755                        ty = new ast::UnionInstType{
2756                                GET_ACCEPT_1( baseUnion, UnionDecl ),
2757                                cv( old ),
2758                                GET_ACCEPT_V( attributes, Attribute )
2759                        };
2760                } else {
2761                        ty = new ast::UnionInstType{
2762                                old->name,
2763                                cv( old ),
2764                                GET_ACCEPT_V( attributes, Attribute )
2765                        };
2766                }
2767                postvisit( old, ty );
2768        }
2769
2770        virtual void visit( const EnumInstType * old ) override final { // Here is visiting the EnumInst Decl not the usage.
2771                ast::EnumInstType * ty; 
2772                if ( old->baseEnum ) {
2773                        ty = new ast::EnumInstType{
2774                                GET_ACCEPT_1( baseEnum, EnumDecl ),
2775                                cv( old ),
2776                                GET_ACCEPT_V( attributes, Attribute )
2777                        };
2778                } else {
2779                        ty = new ast::EnumInstType{
2780                                old->name,
2781                                cv( old ),
2782                                GET_ACCEPT_V( attributes, Attribute )
2783                        };
2784                }
2785                postvisit( old, ty );
2786        }
2787
2788        virtual void visit( const TraitInstType * old ) override final {
2789                ast::TraitInstType * ty;
2790                if ( old->baseTrait ) {
2791                        ty = new ast::TraitInstType{
2792                                GET_ACCEPT_1( baseTrait, TraitDecl ),
2793                                cv( old ),
2794                                GET_ACCEPT_V( attributes, Attribute )
2795                        };
2796                } else {
2797                        ty = new ast::TraitInstType{
2798                                old->name,
2799                                cv( old ),
2800                                GET_ACCEPT_V( attributes, Attribute )
2801                        };
2802                }
2803                postvisit( old, ty );
2804        }
2805
2806        virtual void visit( const TypeInstType * old ) override final {
2807                ast::TypeInstType * ty;
2808                if ( old->baseType ) {
2809                        ty = new ast::TypeInstType{
2810                                old->name,
2811                                GET_ACCEPT_1( baseType, TypeDecl ),
2812                                cv( old ),
2813                                GET_ACCEPT_V( attributes, Attribute )
2814                        };
2815                } else {
2816                        ty = new ast::TypeInstType{
2817                                old->name,
2818                                old->isFtype ? ast::TypeDecl::Ftype : ast::TypeDecl::Dtype,
2819                                cv( old ),
2820                                GET_ACCEPT_V( attributes, Attribute )
2821                        };
2822                }
2823                postvisit( old, ty );
2824        }
2825
2826        virtual void visit( const TupleType * old ) override final {
2827                visitType( old, new ast::TupleType{
2828                        GET_ACCEPT_V( types, Type ),
2829                        // members generated by TupleType c'tor
2830                        cv( old )
2831                } );
2832        }
2833
2834        virtual void visit( const TypeofType * old ) override final {
2835                visitType( old, new ast::TypeofType{
2836                        GET_ACCEPT_1( expr, Expr ),
2837                        (ast::TypeofType::Kind)old->is_basetypeof,
2838                        cv( old )
2839                } );
2840        }
2841
2842        virtual void visit( const VTableType * old ) override final {
2843                visitType( old, new ast::VTableType{
2844                        GET_ACCEPT_1( base, Type ),
2845                        cv( old )
2846                } );
2847        }
2848
2849        virtual void visit( const AttrType * ) override final {
2850                assertf( false, "AttrType deprecated in new AST." );
2851        }
2852
2853        virtual void visit( const VarArgsType * old ) override final {
2854                visitType( old, new ast::VarArgsType{ cv( old ) } );
2855        }
2856
2857        virtual void visit( const ZeroType * old ) override final {
2858                visitType( old, new ast::ZeroType{ cv( old ) } );
2859        }
2860
2861        virtual void visit( const OneType * old ) override final {
2862                visitType( old, new ast::OneType{ cv( old ) } );
2863        }
2864
2865        virtual void visit( const GlobalScopeType * old ) override final {
2866                visitType( old, new ast::GlobalScopeType{} );
2867        }
2868
2869        virtual void visit( const Designation * old ) override final {
2870                this->node = new ast::Designation(
2871                        old->location,
2872                        GET_ACCEPT_D(designators, Expr)
2873                );
2874        }
2875
2876        virtual void visit( const SingleInit * old ) override final {
2877                this->node = new ast::SingleInit(
2878                        old->location,
2879                        GET_ACCEPT_1(value, Expr),
2880                        (old->get_maybeConstructed()) ? ast::MaybeConstruct : ast::NoConstruct
2881                );
2882        }
2883
2884        virtual void visit( const ListInit * old ) override final {
2885                this->node = new ast::ListInit(
2886                        old->location,
2887                        GET_ACCEPT_V(initializers, Init),
2888                        GET_ACCEPT_V(designations, Designation),
2889                        (old->get_maybeConstructed()) ? ast::MaybeConstruct : ast::NoConstruct
2890                );
2891        }
2892
2893        virtual void visit( const ConstructorInit * old ) override final {
2894                this->node = new ast::ConstructorInit(
2895                        old->location,
2896                        GET_ACCEPT_1(ctor, Stmt),
2897                        GET_ACCEPT_1(dtor, Stmt),
2898                        GET_ACCEPT_1(init, Init)
2899                );
2900        }
2901
2902        virtual void visit( const Constant * ) override final {
2903                // Handled in visit( ConstantEpxr * ).
2904                // In the new tree, Constant fields are inlined into containing ConstantExpression.
2905                assert( 0 );
2906        }
2907
2908        virtual void visit( const Attribute * old ) override final {
2909                this->node = new ast::Attribute(
2910                        old->name,
2911                        GET_ACCEPT_V( parameters, Expr )
2912                );
2913        }
2914};
2915
2916#undef GET_LABELS_V
2917#undef GET_ACCEPT_V
2918#undef GET_ACCEPT_1
2919
2920ast::TranslationUnit convert( const std::list< Declaration * > && translationUnit ) {
2921        ConverterOldToNew c;
2922        ast::TranslationUnit unit;
2923        if (Validate::SizeType) {
2924                // this should be a BasicType.
2925                auto old = strict_dynamic_cast<BasicType *>(Validate::SizeType);
2926                ast::sizeType = new ast::BasicType{ (ast::BasicType::Kind)(unsigned)old->kind };
2927        }
2928
2929        for(auto d : translationUnit) {
2930                d->accept( c );
2931                unit.decls.emplace_back( c.decl() );
2932        }
2933        deleteAll(translationUnit);
2934
2935        // Load the local static varables into the global store.
2936        unit.global.sizeType = ast::sizeType;
2937        unit.global.dereference = ast::dereferenceOperator;
2938        unit.global.dtorStruct = ast::dtorStruct;
2939        unit.global.dtorDestroy = ast::dtorStructDestroy;
2940
2941        return unit;
2942}
Note: See TracBrowser for help on using the repository browser.