Ignore:
File:
1 edited

Legend:

Unmodified
Added
Removed
  • src/ControlStruct/MultiLevelExit.cpp

    r66daee4 rcb921d4  
    99// Author           : Andrew Beach
    1010// Created On       : Mon Nov  1 13:48:00 2021
    11 // Last Modified By : Peter A. Buhr
    12 // Last Modified On : Mon Jan 31 22:35:08 2022
    13 // Update Count     : 28
     11// Last Modified By : Andrew Beach
     12// Last Modified On : Mon Nov  8 10:56:00 2021
     13// Update Count     : 2
    1414//
    1515
     
    1818#include "AST/Pass.hpp"
    1919#include "AST/Stmt.hpp"
    20 #include "LabelGeneratorNew.hpp"
     20#include "ControlStruct/LabelGenerator.h"
    2121
    2222#include <set>
    23 using namespace std;
    24 using namespace ast;
    2523
    2624namespace ControlStruct {
     25
     26namespace {
     27
    2728class Entry {
    28   public:
    29         const Stmt * stmt;
    30   private:
     29public:
     30        const ast::Stmt * stmt;
     31private:
    3132        // Organized like a manual ADT. Avoids creating a bunch of dead data.
    3233        struct Target {
    33                 Label label;
     34                ast::Label label;
    3435                bool used = false;
    35                 Target( const Label & label ) : label( label ) {}
     36                Target( const ast::Label & label ) : label( label ) {}
    3637                Target() : label( CodeLocation() ) {}
    3738        };
     
    4041
    4142        enum Kind {
    42                 ForStmtK, WhileStmtK, CompoundStmtK, IfStmtK, CaseStmtK, SwitchStmtK, TryStmtK
     43                ForStmt, WhileStmt, CompoundStmt, IfStmt, CaseStmt, SwitchStmt, TryStmt
    4344        } kind;
    4445
    4546        bool fallDefaultValid = true;
    4647
    47         static Label & useTarget( Target & target ) {
     48        static ast::Label & useTarget( Target & target ) {
    4849                target.used = true;
    4950                return target.label;
    5051        }
    5152
    52   public:
    53         Entry( const ForStmt * stmt, Label breakExit, Label contExit ) :
    54                 stmt( stmt ), firstTarget( breakExit ), secondTarget( contExit ), kind( ForStmtK ) {}
    55         Entry( const WhileStmt * stmt, Label breakExit, Label contExit ) :
    56                 stmt( stmt ), firstTarget( breakExit ), secondTarget( contExit ), kind( WhileStmtK ) {}
    57         Entry( const CompoundStmt *stmt, Label breakExit ) :
    58                 stmt( stmt ), firstTarget( breakExit ), secondTarget(), kind( CompoundStmtK ) {}
    59         Entry( const IfStmt *stmt, Label breakExit ) :
    60                 stmt( stmt ), firstTarget( breakExit ), secondTarget(), kind( IfStmtK ) {}
    61         Entry( const CaseStmt *stmt, Label fallExit ) :
    62                 stmt( stmt ), firstTarget( fallExit ), secondTarget(), kind( CaseStmtK ) {}
    63         Entry( const SwitchStmt *stmt, Label breakExit, Label fallDefaultExit ) :
    64                 stmt( stmt ), firstTarget( breakExit ), secondTarget( fallDefaultExit ), kind( SwitchStmtK ) {}
    65         Entry( const TryStmt *stmt, Label breakExit ) :
    66                 stmt( stmt ), firstTarget( breakExit ), secondTarget(), kind( TryStmtK ) {}
    67 
    68         bool isContTarget() const { return kind <= WhileStmtK; }
    69         bool isBreakTarget() const { return kind != CaseStmtK; }
    70         bool isFallTarget() const { return kind == CaseStmtK; }
    71         bool isFallDefaultTarget() const { return kind == SwitchStmtK; }
    72 
    73         Label useContExit() { assert( kind <= WhileStmtK ); return useTarget(secondTarget); }
    74         Label useBreakExit() { assert( kind != CaseStmtK ); return useTarget(firstTarget); }
    75         Label useFallExit() { assert( kind == CaseStmtK );  return useTarget(firstTarget); }
    76         Label useFallDefaultExit() { assert( kind == SwitchStmtK ); return useTarget(secondTarget); }
    77 
    78         bool isContUsed() const { assert( kind <= WhileStmtK ); return secondTarget.used; }
    79         bool isBreakUsed() const { assert( kind != CaseStmtK ); return firstTarget.used; }
    80         bool isFallUsed() const { assert( kind == CaseStmtK ); return firstTarget.used; }
    81         bool isFallDefaultUsed() const { assert( kind == SwitchStmtK ); return secondTarget.used; }
     53public:
     54        Entry( const ast::ForStmt * stmt, ast::Label breakExit, ast::Label contExit ) :
     55                stmt( stmt ), firstTarget( breakExit ), secondTarget( contExit ), kind( ForStmt ) {}
     56        Entry( const ast::WhileStmt * stmt, ast::Label breakExit, ast::Label contExit ) :
     57                stmt( stmt ), firstTarget( breakExit ), secondTarget( contExit ), kind( WhileStmt ) {}
     58        Entry( const ast::CompoundStmt *stmt, ast::Label breakExit ) :
     59                stmt( stmt ), firstTarget( breakExit ), secondTarget(), kind( CompoundStmt ) {}
     60        Entry( const ast::IfStmt *stmt, ast::Label breakExit ) :
     61                stmt( stmt ), firstTarget( breakExit ), secondTarget(), kind( IfStmt ) {}
     62        Entry( const ast::CaseStmt *stmt, ast::Label fallExit ) :
     63                stmt( stmt ), firstTarget( fallExit ), secondTarget(), kind( CaseStmt ) {}
     64        Entry( const ast::SwitchStmt *stmt, ast::Label breakExit, ast::Label fallDefaultExit ) :
     65                stmt( stmt ), firstTarget( breakExit ), secondTarget( fallDefaultExit ), kind( SwitchStmt ) {}
     66        Entry( const ast::TryStmt *stmt, ast::Label breakExit ) :
     67                stmt( stmt ), firstTarget( breakExit ), secondTarget(), kind( TryStmt ) {}
     68
     69        bool isContTarget() const { return kind <= WhileStmt; }
     70        bool isBreakTarget() const { return CaseStmt != kind; }
     71        bool isFallTarget() const { return CaseStmt == kind; }
     72        bool isFallDefaultTarget() const { return SwitchStmt == kind; }
     73
     74        ast::Label useContExit() { assert( kind <= WhileStmt ); return useTarget(secondTarget); }
     75        ast::Label useBreakExit() { assert( CaseStmt != kind ); return useTarget(firstTarget); }
     76        ast::Label useFallExit() { assert( CaseStmt == kind );  return useTarget(firstTarget); }
     77        ast::Label useFallDefaultExit() { assert( SwitchStmt == kind ); return useTarget(secondTarget); }
     78
     79        bool isContUsed() const { assert( kind <= WhileStmt ); return secondTarget.used; }
     80        bool isBreakUsed() const { assert( CaseStmt != kind ); return firstTarget.used; }
     81        bool isFallUsed() const { assert( CaseStmt == kind ); return firstTarget.used; }
     82        bool isFallDefaultUsed() const { assert( SwitchStmt == kind ); return secondTarget.used; }
    8283        void seenDefault() { fallDefaultValid = false; }
    8384        bool isFallDefaultValid() const { return fallDefaultValid; }
    8485};
    8586
    86 // Helper predicates used in find_if calls (it doesn't take methods):
     87// Helper predicates used in std::find_if calls (it doesn't take methods):
    8788bool isBreakTarget( const Entry & entry ) {
    8889        return entry.isBreakTarget();
     
    102103
    103104struct MultiLevelExitCore final :
    104         public WithVisitorRef<MultiLevelExitCore>,
    105         public WithShortCircuiting, public WithGuards {
     105                public ast::WithVisitorRef<MultiLevelExitCore>,
     106                public ast::WithShortCircuiting, public ast::WithGuards {
    106107        MultiLevelExitCore( const LabelToStmt & lt );
    107108
    108         void previsit( const FunctionDecl * );
    109 
    110         const CompoundStmt * previsit( const CompoundStmt * );
    111         const BranchStmt * postvisit( const BranchStmt * );
    112         void previsit( const WhileStmt * );
    113         const WhileStmt * postvisit( const WhileStmt * );
    114         void previsit( const ForStmt * );
    115         const ForStmt * postvisit( const ForStmt * );
    116         const CaseStmt * previsit( const CaseStmt * );
    117         void previsit( const IfStmt * );
    118         const IfStmt * postvisit( const IfStmt * );
    119         void previsit( const SwitchStmt * );
    120         const SwitchStmt * postvisit( const SwitchStmt * );
    121         void previsit( const ReturnStmt * );
    122         void previsit( const TryStmt * );
    123         void postvisit( const TryStmt * );
    124         void previsit( const FinallyStmt * );
    125 
    126         const Stmt * mutateLoop( const Stmt * body, Entry& );
     109        void previsit( const ast::FunctionDecl * );
     110
     111        const ast::CompoundStmt * previsit( const ast::CompoundStmt * );
     112        const ast::BranchStmt * postvisit( const ast::BranchStmt * );
     113        void previsit( const ast::WhileStmt * );
     114        const ast::WhileStmt * postvisit( const ast::WhileStmt * );
     115        void previsit( const ast::ForStmt * );
     116        const ast::ForStmt * postvisit( const ast::ForStmt * );
     117        const ast::CaseStmt * previsit( const ast::CaseStmt * );
     118        void previsit( const ast::IfStmt * );
     119        const ast::IfStmt * postvisit( const ast::IfStmt * );
     120        void previsit( const ast::SwitchStmt * );
     121        const ast::SwitchStmt * postvisit( const ast::SwitchStmt * );
     122        void previsit( const ast::ReturnStmt * );
     123        void previsit( const ast::TryStmt * );
     124        void postvisit( const ast::TryStmt * );
     125        void previsit( const ast::FinallyStmt * );
     126
     127        const ast::Stmt * mutateLoop( const ast::Stmt * body, Entry& );
    127128
    128129        const LabelToStmt & target_table;
    129         set<Label> fallthrough_labels;
    130         vector<Entry> enclosing_control_structures;
    131         Label break_label;
     130        std::set<ast::Label> fallthrough_labels;
     131        std::vector<Entry> enclosing_control_structures;
     132        ast::Label break_label;
    132133        bool inFinally;
    133134
     
    137138        const LoopNode * posthandleLoopStmt( const LoopNode * loopStmt );
    138139
    139         list<ptr<Stmt>> fixBlock(
    140                 const list<ptr<Stmt>> & kids, bool caseClause );
     140        std::list<ast::ptr<ast::Stmt>> fixBlock(
     141                const std::list<ast::ptr<ast::Stmt>> & kids, bool caseClause );
    141142
    142143        template<typename UnaryPredicate>
    143144        auto findEnclosingControlStructure( UnaryPredicate pred ) {
    144                 return find_if( enclosing_control_structures.rbegin(),
    145                                                 enclosing_control_structures.rend(), pred );
     145                return std::find_if( enclosing_control_structures.rbegin(),
     146                        enclosing_control_structures.rend(), pred );
    146147        }
    147148};
    148149
    149 NullStmt * labelledNullStmt(
    150         const CodeLocation & cl, const Label & label ) {
    151         return new NullStmt( cl, vector<Label>{ label } );
     150ast::NullStmt * labelledNullStmt(
     151                const CodeLocation & cl, const ast::Label & label ) {
     152        return new ast::NullStmt( cl, std::vector<ast::Label>{ label } );
    152153}
    153154
     
    157158{}
    158159
    159 void MultiLevelExitCore::previsit( const FunctionDecl * ) {
     160void MultiLevelExitCore::previsit( const ast::FunctionDecl * ) {
    160161        visit_children = false;
    161162}
    162163
    163 const CompoundStmt * MultiLevelExitCore::previsit(
    164         const CompoundStmt * stmt ) {
     164const ast::CompoundStmt * MultiLevelExitCore::previsit(
     165                const ast::CompoundStmt * stmt ) {
    165166        visit_children = false;
    166167        bool isLabeled = !stmt->labels.empty();
    167168        if ( isLabeled ) {
    168                 Label breakLabel = newLabel( "blockBreak", stmt );
     169                ast::Label breakLabel = LabelGenerator::newLabel( "blockBreak", stmt );
    169170                enclosing_control_structures.emplace_back( stmt, breakLabel );
    170171                GuardAction( [this]() { enclosing_control_structures.pop_back(); } );
    171172        }
    172173
    173         auto mutStmt = mutate( stmt );
     174        auto mutStmt = ast::mutate( stmt );
    174175        // A child statement may set the break label.
    175         mutStmt->kids = move( fixBlock( stmt->kids, false ) );
     176        mutStmt->kids = std::move( fixBlock( stmt->kids, false ) );
    176177
    177178        if ( isLabeled ) {
     
    186187
    187188size_t getUnusedIndex(
    188         const Stmt * stmt, const Label & originalTarget ) {
     189                const ast::Stmt * stmt, const ast::Label & originalTarget ) {
    189190        const size_t size = stmt->labels.size();
    190191
    191         // If the label is empty, do not add unused attribute.
    192   if ( originalTarget.empty() ) return size;
     192        // If the label is empty, we can skip adding the unused attribute:
     193        if ( originalTarget.empty() ) return size;
    193194
    194195        // Search for a label that matches the originalTarget.
    195196        for ( size_t i = 0 ; i < size ; ++i ) {
    196                 const Label & label = stmt->labels[i];
     197                const ast::Label & label = stmt->labels[i];
    197198                if ( label == originalTarget ) {
    198                         for ( const Attribute * attr : label.attributes ) {
     199                        for ( const ast::Attribute * attr : label.attributes ) {
    199200                                if ( attr->name == "unused" ) return size;
    200201                        }
     
    203204        }
    204205        assertf( false, "Could not find label '%s' on statement %s",
    205                          originalTarget.name.c_str(), toString( stmt ).c_str() );
    206 }
    207 
    208 const Stmt * addUnused(
    209         const Stmt * stmt, const Label & originalTarget ) {
     206                originalTarget.name.c_str(), toString( stmt ).c_str() );
     207}
     208
     209const ast::Stmt * addUnused(
     210                const ast::Stmt * stmt, const ast::Label & originalTarget ) {
    210211        size_t i = getUnusedIndex( stmt, originalTarget );
    211212        if ( i == stmt->labels.size() ) {
    212213                return stmt;
    213214        }
    214         Stmt * mutStmt = mutate( stmt );
    215         mutStmt->labels[i].attributes.push_back( new Attribute( "unused" ) );
     215        ast::Stmt * mutStmt = ast::mutate( stmt );
     216        mutStmt->labels[i].attributes.push_back( new ast::Attribute( "unused" ) );
    216217        return mutStmt;
    217218}
    218219
    219 const BranchStmt * MultiLevelExitCore::postvisit( const BranchStmt * stmt ) {
    220         vector<Entry>::reverse_iterator targetEntry =
     220const ast::BranchStmt * MultiLevelExitCore::postvisit( const ast::BranchStmt * stmt ) {
     221        std::vector<Entry>::reverse_iterator targetEntry =
    221222                enclosing_control_structures.rend();
    222223        switch ( stmt->kind ) {
    223           case BranchStmt::Goto:
     224        case ast::BranchStmt::Goto:
    224225                return stmt;
    225           case BranchStmt::Continue:
    226           case BranchStmt::Break: {
    227                   bool isContinue = stmt->kind == BranchStmt::Continue;
    228                   // Handle unlabeled break and continue.
    229                   if ( stmt->target.empty() ) {
    230                           if ( isContinue ) {
    231                                   targetEntry = findEnclosingControlStructure( isContinueTarget );
    232                           } else {
    233                                   if ( enclosing_control_structures.empty() ) {
    234                                           SemanticError( stmt->location,
    235                                                                          "'break' outside a loop, 'switch', or labelled block" );
    236                                   }
    237                                   targetEntry = findEnclosingControlStructure( isBreakTarget );
    238                           }
    239                           // Handle labeled break and continue.
    240                   } else {
    241                           // Lookup label in table to find attached control structure.
    242                           targetEntry = findEnclosingControlStructure(
    243                                   [ targetStmt = target_table.at(stmt->target) ](auto entry){
    244                                           return entry.stmt == targetStmt;
    245                                   } );
    246                   }
    247                   // Ensure that selected target is valid.
    248                   if ( targetEntry == enclosing_control_structures.rend() || ( isContinue && !isContinueTarget( *targetEntry ) ) ) {
    249                           SemanticError( stmt->location, toString( (isContinue ? "'continue'" : "'break'"),
    250                                                         " target must be an enclosing ", (isContinue ? "loop: " : "control structure: "),
    251                                                         stmt->originalTarget ) );
    252                   }
    253                   break;
    254           }
    255           case BranchStmt::FallThrough: {
    256                   targetEntry = findEnclosingControlStructure( isFallthroughTarget );
    257                   // Check that target is valid.
    258                   if ( targetEntry == enclosing_control_structures.rend() ) {
    259                           SemanticError( stmt->location, "'fallthrough' must be enclosed in a 'switch' or 'choose'" );
    260                   }
    261                   if ( !stmt->target.empty() ) {
    262                           // Labelled fallthrough: target must be a valid fallthough label.
    263                           if ( !fallthrough_labels.count( stmt->target ) ) {
    264                                   SemanticError( stmt->location, toString( "'fallthrough' target must be a later case statement: ",
    265                                                                                                                    stmt->originalTarget ) );
    266                           }
    267                           return new BranchStmt(
    268                                   stmt->location, BranchStmt::Goto, stmt->originalTarget );
    269                   }
    270                   break;
    271           }
    272           case BranchStmt::FallThroughDefault: {
    273                   targetEntry = findEnclosingControlStructure( isFallthroughDefaultTarget );
    274 
    275                   // Check if in switch or choose statement.
    276                   if ( targetEntry == enclosing_control_structures.rend() ) {
    277                           SemanticError( stmt->location, "'fallthrough' must be enclosed in a 'switch' or 'choose'" );
    278                   }
    279 
    280                   // Check if switch or choose has default clause.
    281                   auto switchStmt = strict_dynamic_cast< const SwitchStmt * >( targetEntry->stmt );
    282                   bool foundDefault = false;
    283                   for ( auto subStmt : switchStmt->stmts ) {
    284                           const CaseStmt * caseStmt = subStmt.strict_as<CaseStmt>();
    285                           if ( caseStmt->isDefault() ) {
    286                                   foundDefault = true;
    287                                   break;
    288                           }
    289                   }
    290                   if ( ! foundDefault ) {
    291                           SemanticError( stmt->location, "'fallthrough default' must be enclosed in a 'switch' or 'choose'"
    292                                                          "control structure with a 'default' clause" );
    293                   }
    294                   break;
    295           }
    296           default:
     226        case ast::BranchStmt::Continue:
     227        case ast::BranchStmt::Break: {
     228                bool isContinue = stmt->kind == ast::BranchStmt::Continue;
     229                // Handle unlabeled break and continue.
     230                if ( stmt->target.empty() ) {
     231                        if ( isContinue ) {
     232                                targetEntry = findEnclosingControlStructure( isContinueTarget );
     233                        } else {
     234                                if ( enclosing_control_structures.empty() ) {
     235                                        SemanticError( stmt->location,
     236                                                "'break' outside a loop, 'switch', or labelled block" );
     237                                }
     238                                targetEntry = findEnclosingControlStructure( isBreakTarget );
     239                        }
     240                // Handle labeled break and continue.
     241                } else {
     242                        // Lookup label in table to find attached control structure.
     243                        targetEntry = findEnclosingControlStructure(
     244                                [ targetStmt = target_table.at(stmt->target) ](auto entry){
     245                                        return entry.stmt == targetStmt;
     246                                } );
     247                }
     248                // Ensure that selected target is valid.
     249                if ( targetEntry == enclosing_control_structures.rend() || ( isContinue && !isContinueTarget( *targetEntry ) ) ) {
     250                        SemanticError(
     251                                stmt->location,
     252                                toString( (isContinue ? "'continue'" : "'break'"),
     253                                        " target must be an enclosing ",
     254                                        (isContinue ? "loop: " : "control structure: "),
     255                                        stmt->originalTarget ) );
     256                }
     257                break;
     258        }
     259        case ast::BranchStmt::FallThrough: {
     260                targetEntry = findEnclosingControlStructure( isFallthroughTarget );
     261                // Check that target is valid.
     262                if ( targetEntry == enclosing_control_structures.rend() ) {
     263                        SemanticError( stmt->location, "'fallthrough' must be enclosed in a 'switch' or 'choose'" );
     264                }
     265                if ( !stmt->target.empty() ) {
     266                        // Labelled fallthrough: target must be a valid fallthough label.
     267                        if ( !fallthrough_labels.count( stmt->target ) ) {
     268                                SemanticError( stmt->location, toString( "'fallthrough' target must be a later case statement: ", stmt->originalTarget ) );
     269                        }
     270                        return new ast::BranchStmt(
     271                                stmt->location, ast::BranchStmt::Goto, stmt->originalTarget );
     272                }
     273                break;
     274        }
     275        case ast::BranchStmt::FallThroughDefault: {
     276                targetEntry = findEnclosingControlStructure( isFallthroughDefaultTarget );
     277
     278                // Check that this is in a switch or choose statement.
     279                if ( targetEntry == enclosing_control_structures.rend() ) {
     280                        SemanticError( stmt->location, "'fallthrough' must be enclosed in a 'switch' or 'choose'" );
     281                }
     282
     283                // Check that the switch or choose has a default clause.
     284                auto switchStmt = strict_dynamic_cast< const ast::SwitchStmt * >(
     285                        targetEntry->stmt );
     286                bool foundDefault = false;
     287                for ( auto subStmt : switchStmt->stmts ) {
     288                        const ast::CaseStmt * caseStmt = subStmt.strict_as<ast::CaseStmt>();
     289                        if ( caseStmt->isDefault() ) {
     290                                foundDefault = true;
     291                                break;
     292                        }
     293                }
     294                if ( !foundDefault ) {
     295                        SemanticError( stmt->location, "'fallthrough default' must be enclosed in a 'switch' or 'choose' control structure with a 'default' clause" );
     296                }
     297                break;
     298        }
     299        default:
    297300                assert( false );
    298301        }
    299302
    300303        // Branch error checks: get the appropriate label name:
    301         // (This label is always replaced.)
    302         Label exitLabel( CodeLocation(), "" );
     304        // (This label will always be replaced.)
     305        ast::Label exitLabel( CodeLocation(), "" );
    303306        switch ( stmt->kind ) {
    304           case BranchStmt::Break:
     307        case ast::BranchStmt::Break:
    305308                assert( !targetEntry->useBreakExit().empty() );
    306309                exitLabel = targetEntry->useBreakExit();
    307310                break;
    308           case BranchStmt::Continue:
     311        case ast::BranchStmt::Continue:
    309312                assert( !targetEntry->useContExit().empty() );
    310313                exitLabel = targetEntry->useContExit();
    311314                break;
    312           case BranchStmt::FallThrough:
     315        case ast::BranchStmt::FallThrough:
    313316                assert( !targetEntry->useFallExit().empty() );
    314317                exitLabel = targetEntry->useFallExit();
    315318                break;
    316           case BranchStmt::FallThroughDefault:
     319        case ast::BranchStmt::FallThroughDefault:
    317320                assert( !targetEntry->useFallDefaultExit().empty() );
    318321                exitLabel = targetEntry->useFallDefaultExit();
    319322                // Check that fallthrough default comes before the default clause.
    320323                if ( !targetEntry->isFallDefaultValid() ) {
    321                         SemanticError( stmt->location, "'fallthrough default' must precede the 'default' clause" );
     324                        SemanticError( stmt->location,
     325                                "'fallthrough default' must precede the 'default' clause" );
    322326                }
    323327                break;
    324           default:
     328        default:
    325329                assert(0);
    326330        }
     
    329333        targetEntry->stmt = addUnused( targetEntry->stmt, stmt->originalTarget );
    330334
    331         // Replace with goto to make later passes more uniform.
    332         return new BranchStmt( stmt->location, BranchStmt::Goto, exitLabel );
    333 }
    334 
    335 void MultiLevelExitCore::previsit( const WhileStmt * stmt ) {
     335        // Replace this with a goto to make later passes more uniform.
     336        return new ast::BranchStmt( stmt->location, ast::BranchStmt::Goto, exitLabel );
     337}
     338
     339void MultiLevelExitCore::previsit( const ast::WhileStmt * stmt ) {
    336340        return prehandleLoopStmt( stmt );
    337341}
    338342
    339 const WhileStmt * MultiLevelExitCore::postvisit( const WhileStmt * stmt ) {
     343const ast::WhileStmt * MultiLevelExitCore::postvisit( const ast::WhileStmt * stmt ) {
    340344        return posthandleLoopStmt( stmt );
    341345}
    342346
    343 void MultiLevelExitCore::previsit( const ForStmt * stmt ) {
     347void MultiLevelExitCore::previsit( const ast::ForStmt * stmt ) {
    344348        return prehandleLoopStmt( stmt );
    345349}
    346350
    347 const ForStmt * MultiLevelExitCore::postvisit( const ForStmt * stmt ) {
     351const ast::ForStmt * MultiLevelExitCore::postvisit( const ast::ForStmt * stmt ) {
    348352        return posthandleLoopStmt( stmt );
    349353}
     
    351355// Mimic what the built-in push_front would do anyways. It is O(n).
    352356void push_front(
    353         vector<ptr<Stmt>> & vec, const Stmt * element ) {
     357                std::vector<ast::ptr<ast::Stmt>> & vec, const ast::Stmt * element ) {
    354358        vec.emplace_back( nullptr );
    355359        for ( size_t i = vec.size() - 1 ; 0 < i ; --i ) {
    356                 vec[ i ] = move( vec[ i - 1 ] );
     360                vec[ i ] = std::move( vec[ i - 1 ] );
    357361        }
    358362        vec[ 0 ] = element;
    359363}
    360364
    361 const CaseStmt * MultiLevelExitCore::previsit( const CaseStmt * stmt ) {
     365const ast::CaseStmt * MultiLevelExitCore::previsit( const ast::CaseStmt * stmt ) {
    362366        visit_children = false;
    363367
    364         // If default, mark seen.
     368        // If it is the default, mark the default as seen.
    365369        if ( stmt->isDefault() ) {
    366370                assert( !enclosing_control_structures.empty() );
     
    369373
    370374        // The cond may not exist, but if it does update it now.
    371         visitor->maybe_accept( stmt, &CaseStmt::cond );
     375        visitor->maybe_accept( stmt, &ast::CaseStmt::cond );
    372376
    373377        // Just save the mutated node for simplicity.
    374         CaseStmt * mutStmt = mutate( stmt );
    375 
    376         Label fallLabel = newLabel( "fallThrough", stmt );
    377         if ( ! mutStmt->stmts.empty() ) {
     378        ast::CaseStmt * mutStmt = ast::mutate( stmt );
     379
     380        ast::Label fallLabel = LabelGenerator::newLabel( "fallThrough", stmt );
     381        if ( !mutStmt->stmts.empty() ) {
    378382                // Ensure that the stack isn't corrupted by exceptions in fixBlock.
    379383                auto guard = makeFuncGuard(
    380384                        [&](){ enclosing_control_structures.emplace_back( mutStmt, fallLabel ); },
    381385                        [this](){ enclosing_control_structures.pop_back(); }
    382                         );
     386                );
    383387
    384388                // These should already be in a block.
    385                 auto block = mutate( mutStmt->stmts.front().strict_as<CompoundStmt>() );
     389                auto block = ast::mutate( mutStmt->stmts.front().strict_as<ast::CompoundStmt>() );
    386390                block->kids = fixBlock( block->kids, true );
    387391
    388392                // Add fallthrough label if necessary.
    389                 assert( ! enclosing_control_structures.empty() );
     393                assert( !enclosing_control_structures.empty() );
    390394                Entry & entry = enclosing_control_structures.back();
    391395                if ( entry.isFallUsed() ) {
     
    394398                }
    395399        }
    396         assert( ! enclosing_control_structures.empty() );
     400        assert( !enclosing_control_structures.empty() );
    397401        Entry & entry = enclosing_control_structures.back();
    398         assertf( dynamic_cast< const SwitchStmt * >( entry.stmt ),
    399                          "Control structure enclosing a case clause must be a switch, but is: %s",
    400                          toString( entry.stmt ).c_str() );
     402        assertf( dynamic_cast< const ast::SwitchStmt * >( entry.stmt ),
     403                "Control structure enclosing a case clause must be a switch, but is: %s",
     404                toString( entry.stmt ).c_str() );
    401405        if ( mutStmt->isDefault() ) {
    402406                if ( entry.isFallDefaultUsed() ) {
    403407                        // Add fallthrough default label if necessary.
    404408                        push_front( mutStmt->stmts, labelledNullStmt(
    405                                                         stmt->location, entry.useFallDefaultExit()
    406                                                         ) );
     409                                stmt->location, entry.useFallDefaultExit()
     410                        ) );
    407411                }
    408412        }
     
    410414}
    411415
    412 void MultiLevelExitCore::previsit( const IfStmt * stmt ) {
     416void MultiLevelExitCore::previsit( const ast::IfStmt * stmt ) {
    413417        bool labeledBlock = !stmt->labels.empty();
    414418        if ( labeledBlock ) {
    415                 Label breakLabel = newLabel( "blockBreak", stmt );
     419                ast::Label breakLabel = LabelGenerator::newLabel( "blockBreak", stmt );
    416420                enclosing_control_structures.emplace_back( stmt, breakLabel );
    417421                GuardAction( [this](){ enclosing_control_structures.pop_back(); } );
     
    419423}
    420424
    421 const IfStmt * MultiLevelExitCore::postvisit( const IfStmt * stmt ) {
     425const ast::IfStmt * MultiLevelExitCore::postvisit( const ast::IfStmt * stmt ) {
    422426        bool labeledBlock = !stmt->labels.empty();
    423427        if ( labeledBlock ) {
     
    430434}
    431435
    432 bool isDefaultCase( const ptr<Stmt> & stmt ) {
    433         const CaseStmt * caseStmt = stmt.strict_as<CaseStmt>();
     436bool isDefaultCase( const ast::ptr<ast::Stmt> & stmt ) {
     437        const ast::CaseStmt * caseStmt = stmt.strict_as<ast::CaseStmt>();
    434438        return caseStmt->isDefault();
    435439}
    436440
    437 void MultiLevelExitCore::previsit( const SwitchStmt * stmt ) {
    438         Label label = newLabel( "switchBreak", stmt );
    439         auto it = find_if( stmt->stmts.rbegin(), stmt->stmts.rend(), isDefaultCase );
    440 
    441         const CaseStmt * defaultCase = it != stmt->stmts.rend()
    442                 ? (it)->strict_as<CaseStmt>() : nullptr;
    443         Label defaultLabel = defaultCase
    444                 ? newLabel( "fallThroughDefault", defaultCase )
    445                 : Label( stmt->location, "" );
     441void MultiLevelExitCore::previsit( const ast::SwitchStmt * stmt ) {
     442        ast::Label label = LabelGenerator::newLabel( "switchBreak", stmt );
     443        auto it = std::find_if( stmt->stmts.rbegin(), stmt->stmts.rend(), isDefaultCase );
     444
     445        const ast::CaseStmt * defaultCase = it != stmt->stmts.rend()
     446                ? (it)->strict_as<ast::CaseStmt>() : nullptr;
     447        ast::Label defaultLabel = defaultCase
     448                ? LabelGenerator::newLabel( "fallThroughDefault", defaultCase )
     449                : ast::Label( stmt->location, "" );
    446450        enclosing_control_structures.emplace_back( stmt, label, defaultLabel );
    447451        GuardAction( [this]() { enclosing_control_structures.pop_back(); } );
    448452
    449453        // Collect valid labels for fallthrough. It starts with all labels at
    450         // this level, then remove as each is seen during traversal.
    451         for ( const Stmt * stmt : stmt->stmts ) {
    452                 auto * caseStmt = strict_dynamic_cast< const CaseStmt * >( stmt );
     454        // this level, then removed as we see them in traversal.
     455        for ( const ast::Stmt * stmt : stmt->stmts ) {
     456                auto * caseStmt = strict_dynamic_cast< const ast::CaseStmt * >( stmt );
    453457                if ( caseStmt->stmts.empty() ) continue;
    454                 auto block = caseStmt->stmts.front().strict_as<CompoundStmt>();
    455                 for ( const Stmt * stmt : block->kids ) {
    456                         for ( const Label & l : stmt->labels ) {
     458                auto block = caseStmt->stmts.front().strict_as<ast::CompoundStmt>();
     459                for ( const ast::Stmt * stmt : block->kids ) {
     460                        for ( const ast::Label & l : stmt->labels ) {
    457461                                fallthrough_labels.insert( l );
    458462                        }
     
    461465}
    462466
    463 const SwitchStmt * MultiLevelExitCore::postvisit( const SwitchStmt * stmt ) {
     467const ast::SwitchStmt * MultiLevelExitCore::postvisit( const ast::SwitchStmt * stmt ) {
    464468        assert( !enclosing_control_structures.empty() );
    465469        Entry & entry = enclosing_control_structures.back();
    466470        assert( entry.stmt == stmt );
    467471
    468         // Only run to generate the break label.
     472        // Only run if we need to generate the break label.
    469473        if ( entry.isBreakUsed() ) {
    470474                // To keep the switch statements uniform (all direct children of a
    471475                // SwitchStmt should be CastStmts), append the exit label and break
    472476                // to the last case, create a default case is there are no cases.
    473                 SwitchStmt * mutStmt = mutate( stmt );
     477                ast::SwitchStmt * mutStmt = ast::mutate( stmt );
    474478                if ( mutStmt->stmts.empty() ) {
    475                         mutStmt->stmts.push_back( new CaseStmt(
    476                                                                                   mutStmt->location, nullptr, {} ));
    477                 }
    478 
    479                 auto caseStmt = mutStmt->stmts.back().strict_as<CaseStmt>();
    480                 auto mutCase = mutate( caseStmt );
     479                        mutStmt->stmts.push_back( new ast::CaseStmt(
     480                                mutStmt->location, nullptr, {} ));
     481                }
     482
     483                auto caseStmt = mutStmt->stmts.back().strict_as<ast::CaseStmt>();
     484                auto mutCase = ast::mutate( caseStmt );
    481485                mutStmt->stmts.back() = mutCase;
    482486
    483                 Label label( mutCase->location, "breakLabel" );
    484                 auto branch = new BranchStmt( mutCase->location, BranchStmt::Break, label );
     487                ast::Label label( mutCase->location, "breakLabel" );
     488                auto branch = new ast::BranchStmt( mutCase->location, ast::BranchStmt::Break, label );
    485489                branch->labels.push_back( entry.useBreakExit() );
    486490                mutCase->stmts.push_back( branch );
     
    491495}
    492496
    493 void MultiLevelExitCore::previsit( const ReturnStmt * stmt ) {
     497void MultiLevelExitCore::previsit( const ast::ReturnStmt * stmt ) {
    494498        if ( inFinally ) {
    495499                SemanticError( stmt->location, "'return' may not appear in a finally clause" );
     
    497501}
    498502
    499 void MultiLevelExitCore::previsit( const TryStmt * stmt ) {
     503void MultiLevelExitCore::previsit( const ast::TryStmt * stmt ) {
    500504        bool isLabeled = !stmt->labels.empty();
    501505        if ( isLabeled ) {
    502                 Label breakLabel = newLabel( "blockBreak", stmt );
     506                ast::Label breakLabel = LabelGenerator::newLabel( "blockBreak", stmt );
    503507                enclosing_control_structures.emplace_back( stmt, breakLabel );
    504508                GuardAction([this](){ enclosing_control_structures.pop_back(); } );
     
    506510}
    507511
    508 void MultiLevelExitCore::postvisit( const TryStmt * stmt ) {
     512void MultiLevelExitCore::postvisit( const ast::TryStmt * stmt ) {
    509513        bool isLabeled = !stmt->labels.empty();
    510514        if ( isLabeled ) {
     
    516520}
    517521
    518 void MultiLevelExitCore::previsit( const FinallyStmt * ) {
    519         GuardAction([this, old = move(enclosing_control_structures)](){
    520                                         enclosing_control_structures = move(old);
    521                                 });
    522         enclosing_control_structures = vector<Entry>();
     522void MultiLevelExitCore::previsit( const ast::FinallyStmt * ) {
     523        GuardAction([this, old = std::move(enclosing_control_structures)](){
     524                enclosing_control_structures = std::move(old);
     525        });
     526        enclosing_control_structures = std::vector<Entry>();
    523527        GuardValue( inFinally ) = true;
    524528}
    525529
    526 const Stmt * MultiLevelExitCore::mutateLoop(
    527         const Stmt * body, Entry & entry ) {
     530const ast::Stmt * MultiLevelExitCore::mutateLoop(
     531                const ast::Stmt * body, Entry & entry ) {
    528532        if ( entry.isBreakUsed() ) {
    529533                break_label = entry.useBreakExit();
     
    531535
    532536        if ( entry.isContUsed() ) {
    533                 CompoundStmt * new_body = new CompoundStmt( body->location );
     537                ast::CompoundStmt * new_body = new ast::CompoundStmt( body->location );
    534538                new_body->kids.push_back( body );
    535539                new_body->kids.push_back(
     
    545549        // Remember is loop before going onto mutate the body.
    546550        // The labels will be folded in if they are used.
    547         Label breakLabel = newLabel( "loopBreak", loopStmt );
    548         Label contLabel = newLabel( "loopContinue", loopStmt );
     551        ast::Label breakLabel = LabelGenerator::newLabel( "loopBreak", loopStmt );
     552        ast::Label contLabel = LabelGenerator::newLabel( "loopContinue", loopStmt );
    549553        enclosing_control_structures.emplace_back( loopStmt, breakLabel, contLabel );
    550554        GuardAction( [this](){ enclosing_control_structures.pop_back(); } );
     
    557561        assert( entry.stmt == loopStmt );
    558562
    559         // Now check if the labels are used and add them if so.
    560         return mutate_field(
     563        // Now we check if the labels are used and add them if so.
     564        return ast::mutate_field(
    561565                loopStmt, &LoopNode::body, mutateLoop( loopStmt->body, entry ) );
    562566}
    563567
    564 list<ptr<Stmt>> MultiLevelExitCore::fixBlock(
    565         const list<ptr<Stmt>> & kids, bool is_case_clause ) {
    566         // Unfortunately cannot use automatic error collection.
     568std::list<ast::ptr<ast::Stmt>> MultiLevelExitCore::fixBlock(
     569                const std::list<ast::ptr<ast::Stmt>> & kids, bool is_case_clause ) {
     570        // Unfortunately we can't use the automatic error collection.
    567571        SemanticErrorException errors;
    568572
    569         list<ptr<Stmt>> ret;
     573        std::list<ast::ptr<ast::Stmt>> ret;
    570574
    571575        // Manually visit each child.
    572         for ( const ptr<Stmt> & kid : kids ) {
     576        for ( const ast::ptr<ast::Stmt> & kid : kids ) {
    573577                if ( is_case_clause ) {
    574578                        // Once a label is seen, it's no longer a valid for fallthrough.
    575                         for ( const Label & l : kid->labels ) {
     579                        for ( const ast::Label & l : kid->labels ) {
    576580                                fallthrough_labels.erase( l );
    577581                        }
     
    587591                        ret.push_back(
    588592                                labelledNullStmt( ret.back()->location, break_label ) );
    589                         break_label = Label( CodeLocation(), "" );
     593                        break_label = ast::Label( CodeLocation(), "" );
    590594                }
    591595        }
     
    597601}
    598602
    599 const CompoundStmt * multiLevelExitUpdate(
    600         const CompoundStmt * stmt,
    601         const LabelToStmt & labelTable ) {
     603} // namespace
     604
     605const ast::CompoundStmt * multiLevelExitUpdate(
     606        const ast::CompoundStmt * stmt,
     607                const LabelToStmt & labelTable ) {
    602608        // Must start in the body, so FunctionDecls can be a stopping point.
    603         Pass<MultiLevelExitCore> visitor( labelTable );
    604         const CompoundStmt * ret = stmt->accept( visitor );
     609        ast::Pass<MultiLevelExitCore> visitor( labelTable );
     610        const ast::CompoundStmt * ret = stmt->accept( visitor );
    605611        return ret;
    606612}
     613
    607614} // namespace ControlStruct
    608615
Note: See TracChangeset for help on using the changeset viewer.