source: src/AST/Convert.cpp @ eb211bf

ADTast-experimentalenumpthread-emulationqualifiedEnum
Last change on this file since eb211bf was ff3b0249, checked in by Peter A. Buhr <pabuhr@…>, 2 years ago

add else clause into WhileDoStmt? and ForStmt?

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