Ignore:
File:
1 edited

Legend:

Unmodified
Added
Removed
  • src/ControlStruct/MultiLevelExit.cpp

    r3b0bc16 r3e5db5b4  
    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 : Tue Feb  1 18:48:47 2022
    13 // Update Count     : 29
     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, WhileDoStmtK, 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 WhileDoStmt * stmt, Label breakExit, Label contExit ) :
    56                 stmt( stmt ), firstTarget( breakExit ), secondTarget( contExit ), kind( WhileDoStmtK ) {}
    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 <= WhileDoStmtK; }
    69         bool isBreakTarget() const { return kind != CaseStmtK; }
    70         bool isFallTarget() const { return kind == CaseStmtK; }
    71         bool isFallDefaultTarget() const { return kind == SwitchStmtK; }
     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; }
    7273
    7374        // These routines set a target as being "used" by a BranchStmt
    74         Label useContExit() { assert( kind <= WhileDoStmtK ); return useTarget(secondTarget); }
    75         Label useBreakExit() { assert( kind != CaseStmtK ); return useTarget(firstTarget); }
    76         Label useFallExit() { assert( kind == CaseStmtK );  return useTarget(firstTarget); }
    77         Label useFallDefaultExit() { assert( kind == SwitchStmtK ); return useTarget(secondTarget); }
     75        ast::Label useContExit() { assert( kind <= WhileStmt ); return useTarget(secondTarget); }
     76        ast::Label useBreakExit() { assert( CaseStmt != kind ); return useTarget(firstTarget); }
     77        ast::Label useFallExit() { assert( CaseStmt == kind );  return useTarget(firstTarget); }
     78        ast::Label useFallDefaultExit() { assert( SwitchStmt == kind ); return useTarget(secondTarget); }
    7879
    7980        // These routines check if a specific label for a statement is used by a BranchStmt
    80         bool isContUsed() const { assert( kind <= WhileDoStmtK ); return secondTarget.used; }
    81         bool isBreakUsed() const { assert( kind != CaseStmtK ); return firstTarget.used; }
    82         bool isFallUsed() const { assert( kind == CaseStmtK ); return firstTarget.used; }
    83         bool isFallDefaultUsed() const { assert( kind == SwitchStmtK ); return secondTarget.used; }
     81        bool isContUsed() const { assert( kind <= WhileStmt ); return secondTarget.used; }
     82        bool isBreakUsed() const { assert( CaseStmt != kind ); return firstTarget.used; }
     83        bool isFallUsed() const { assert( CaseStmt == kind ); return firstTarget.used; }
     84        bool isFallDefaultUsed() const { assert( SwitchStmt == kind ); return secondTarget.used; }
    8485        void seenDefault() { fallDefaultValid = false; }
    8586        bool isFallDefaultValid() const { return fallDefaultValid; }
    8687};
    8788
    88 // Helper predicates used in find_if calls (it doesn't take methods):
     89// Helper predicates used in std::find_if calls (it doesn't take methods):
    8990bool isBreakTarget( const Entry & entry ) {
    9091        return entry.isBreakTarget();
     
    104105
    105106struct MultiLevelExitCore final :
    106         public WithVisitorRef<MultiLevelExitCore>,
    107         public WithShortCircuiting, public WithGuards {
     107                public ast::WithVisitorRef<MultiLevelExitCore>,
     108                public ast::WithShortCircuiting, public ast::WithGuards {
    108109        MultiLevelExitCore( const LabelToStmt & lt );
    109110
    110         void previsit( const FunctionDecl * );
    111 
    112         const CompoundStmt * previsit( const CompoundStmt * );
    113         const BranchStmt * postvisit( const BranchStmt * );
    114         void previsit( const WhileDoStmt * );
    115         const WhileDoStmt * postvisit( const WhileDoStmt * );
    116         void previsit( const ForStmt * );
    117         const ForStmt * postvisit( const ForStmt * );
    118         const CaseStmt * previsit( const CaseStmt * );
    119         void previsit( const IfStmt * );
    120         const IfStmt * postvisit( const IfStmt * );
    121         void previsit( const SwitchStmt * );
    122         const SwitchStmt * postvisit( const SwitchStmt * );
    123         void previsit( const ReturnStmt * );
    124         void previsit( const TryStmt * );
    125         void postvisit( const TryStmt * );
    126         void previsit( const FinallyStmt * );
    127 
    128         const Stmt * mutateLoop( const Stmt * body, Entry& );
     111        void previsit( const ast::FunctionDecl * );
     112
     113        const ast::CompoundStmt * previsit( const ast::CompoundStmt * );
     114        const ast::BranchStmt * postvisit( const ast::BranchStmt * );
     115        void previsit( const ast::WhileStmt * );
     116        const ast::WhileStmt * postvisit( const ast::WhileStmt * );
     117        void previsit( const ast::ForStmt * );
     118        const ast::ForStmt * postvisit( const ast::ForStmt * );
     119        const ast::CaseStmt * previsit( const ast::CaseStmt * );
     120        void previsit( const ast::IfStmt * );
     121        const ast::IfStmt * postvisit( const ast::IfStmt * );
     122        void previsit( const ast::SwitchStmt * );
     123        const ast::SwitchStmt * postvisit( const ast::SwitchStmt * );
     124        void previsit( const ast::ReturnStmt * );
     125        void previsit( const ast::TryStmt * );
     126        void postvisit( const ast::TryStmt * );
     127        void previsit( const ast::FinallyStmt * );
     128
     129        const ast::Stmt * mutateLoop( const ast::Stmt * body, Entry& );
    129130
    130131        const LabelToStmt & target_table;
    131         set<Label> fallthrough_labels;
    132         vector<Entry> enclosing_control_structures;
    133         Label break_label;
     132        std::set<ast::Label> fallthrough_labels;
     133        std::vector<Entry> enclosing_control_structures;
     134        ast::Label break_label;
    134135        bool inFinally;
    135136
     
    139140        const LoopNode * posthandleLoopStmt( const LoopNode * loopStmt );
    140141
    141         list<ptr<Stmt>> fixBlock(
    142                 const list<ptr<Stmt>> & kids, bool caseClause );
     142        std::list<ast::ptr<ast::Stmt>> fixBlock(
     143                const std::list<ast::ptr<ast::Stmt>> & kids, bool caseClause );
    143144
    144145        template<typename UnaryPredicate>
    145146        auto findEnclosingControlStructure( UnaryPredicate pred ) {
    146                 return find_if( enclosing_control_structures.rbegin(),
    147                                                 enclosing_control_structures.rend(), pred );
     147                return std::find_if( enclosing_control_structures.rbegin(),
     148                        enclosing_control_structures.rend(), pred );
    148149        }
    149150};
    150151
    151 NullStmt * labelledNullStmt(
    152         const CodeLocation & cl, const Label & label ) {
    153         return new NullStmt( cl, vector<Label>{ label } );
     152ast::NullStmt * labelledNullStmt(
     153                const CodeLocation & cl, const ast::Label & label ) {
     154        return new ast::NullStmt( cl, std::vector<ast::Label>{ label } );
    154155}
    155156
     
    159160{}
    160161
    161 void MultiLevelExitCore::previsit( const FunctionDecl * ) {
     162void MultiLevelExitCore::previsit( const ast::FunctionDecl * ) {
    162163        visit_children = false;
    163164}
    164165
    165 const CompoundStmt * MultiLevelExitCore::previsit(
    166         const CompoundStmt * stmt ) {
     166const ast::CompoundStmt * MultiLevelExitCore::previsit(
     167                const ast::CompoundStmt * stmt ) {
    167168        visit_children = false;
    168169
     
    170171        bool isLabeled = !stmt->labels.empty();
    171172        if ( isLabeled ) {
    172                 Label breakLabel = newLabel( "blockBreak", stmt );
     173                ast::Label breakLabel = LabelGenerator::newLabel( "blockBreak", stmt );
    173174                enclosing_control_structures.emplace_back( stmt, breakLabel );
    174175                GuardAction( [this]() { enclosing_control_structures.pop_back(); } );
    175176        }
    176177
    177         auto mutStmt = mutate( stmt );
     178        auto mutStmt = ast::mutate( stmt );
    178179        // A child statement may set the break label.
    179         mutStmt->kids = move( fixBlock( stmt->kids, false ) );
     180        mutStmt->kids = std::move( fixBlock( stmt->kids, false ) );
    180181
    181182        if ( isLabeled ) {
     
    190191
    191192size_t getUnusedIndex(
    192         const Stmt * stmt, const Label & originalTarget ) {
     193                const ast::Stmt * stmt, const ast::Label & originalTarget ) {
    193194        const size_t size = stmt->labels.size();
    194195
    195         // If the label is empty, do not add unused attribute.
    196   if ( originalTarget.empty() ) return size;
     196        // If the label is empty, we can skip adding the unused attribute:
     197        if ( originalTarget.empty() ) return size;
    197198
    198199        // Search for a label that matches the originalTarget.
    199200        for ( size_t i = 0 ; i < size ; ++i ) {
    200                 const Label & label = stmt->labels[i];
     201                const ast::Label & label = stmt->labels[i];
    201202                if ( label == originalTarget ) {
    202                         for ( const Attribute * attr : label.attributes ) {
     203                        for ( const ast::Attribute * attr : label.attributes ) {
    203204                                if ( attr->name == "unused" ) return size;
    204205                        }
     
    207208        }
    208209        assertf( false, "Could not find label '%s' on statement %s",
    209                          originalTarget.name.c_str(), toString( stmt ).c_str() );
    210 }
    211 
    212 const Stmt * addUnused(
    213         const Stmt * stmt, const Label & originalTarget ) {
     210                originalTarget.name.c_str(), toString( stmt ).c_str() );
     211}
     212
     213const ast::Stmt * addUnused(
     214                const ast::Stmt * stmt, const ast::Label & originalTarget ) {
    214215        size_t i = getUnusedIndex( stmt, originalTarget );
    215216        if ( i == stmt->labels.size() ) {
    216217                return stmt;
    217218        }
    218         Stmt * mutStmt = mutate( stmt );
    219         mutStmt->labels[i].attributes.push_back( new Attribute( "unused" ) );
     219        ast::Stmt * mutStmt = ast::mutate( stmt );
     220        mutStmt->labels[i].attributes.push_back( new ast::Attribute( "unused" ) );
    220221        return mutStmt;
    221222}
     
    223224// This routine updates targets on enclosing control structures to indicate which
    224225//     label is used by the BranchStmt that is passed
    225 const BranchStmt * MultiLevelExitCore::postvisit( const BranchStmt * stmt ) {
    226         vector<Entry>::reverse_iterator targetEntry =
     226const ast::BranchStmt * MultiLevelExitCore::postvisit( const ast::BranchStmt * stmt ) {
     227        std::vector<Entry>::reverse_iterator targetEntry =
    227228                enclosing_control_structures.rend();
    228229
    229230        // Labels on different stmts require different approaches to access
    230231        switch ( stmt->kind ) {
    231           case BranchStmt::Goto:
     232        case ast::BranchStmt::Goto:
    232233                return stmt;
    233           case BranchStmt::Continue:
    234           case BranchStmt::Break: {
    235                   bool isContinue = stmt->kind == BranchStmt::Continue;
    236                   // Handle unlabeled break and continue.
    237                   if ( stmt->target.empty() ) {
    238                           if ( isContinue ) {
    239                                   targetEntry = findEnclosingControlStructure( isContinueTarget );
    240                           } else {
    241                                   if ( enclosing_control_structures.empty() ) {
    242                                           SemanticError( stmt->location,
    243                                                                          "'break' outside a loop, 'switch', or labelled block" );
    244                                   }
    245                                   targetEntry = findEnclosingControlStructure( isBreakTarget );
    246                           }
    247                           // Handle labeled break and continue.
    248                   } else {
    249                           // Lookup label in table to find attached control structure.
    250                           targetEntry = findEnclosingControlStructure(
    251                                   [ targetStmt = target_table.at(stmt->target) ](auto entry){
    252                                           return entry.stmt == targetStmt;
    253                                   } );
    254                   }
    255                   // Ensure that selected target is valid.
    256                   if ( targetEntry == enclosing_control_structures.rend() || ( isContinue && !isContinueTarget( *targetEntry ) ) ) {
    257                           SemanticError( stmt->location, toString( (isContinue ? "'continue'" : "'break'"),
    258                                                         " target must be an enclosing ", (isContinue ? "loop: " : "control structure: "),
    259                                                         stmt->originalTarget ) );
    260                   }
    261                   break;
    262           }
    263           // handle fallthrough in case/switch stmts
    264           case BranchStmt::FallThrough: {
    265                   targetEntry = findEnclosingControlStructure( isFallthroughTarget );
    266                   // Check that target is valid.
    267                   if ( targetEntry == enclosing_control_structures.rend() ) {
    268                           SemanticError( stmt->location, "'fallthrough' must be enclosed in a 'switch' or 'choose'" );
    269                   }
    270                   if ( !stmt->target.empty() ) {
    271                           // Labelled fallthrough: target must be a valid fallthough label.
    272                           if ( !fallthrough_labels.count( stmt->target ) ) {
    273                                   SemanticError( stmt->location, toString( "'fallthrough' target must be a later case statement: ",
    274                                                                                                                    stmt->originalTarget ) );
    275                           }
    276                           return new BranchStmt(
    277                                   stmt->location, BranchStmt::Goto, stmt->originalTarget );
    278                   }
    279                   break;
    280           }
    281           case BranchStmt::FallThroughDefault: {
    282                   targetEntry = findEnclosingControlStructure( isFallthroughDefaultTarget );
    283 
    284                   // Check if in switch or choose statement.
    285                   if ( targetEntry == enclosing_control_structures.rend() ) {
    286                           SemanticError( stmt->location, "'fallthrough' must be enclosed in a 'switch' or 'choose'" );
    287                   }
    288 
    289                   // Check if switch or choose has default clause.
    290                   auto switchStmt = strict_dynamic_cast< const SwitchStmt * >( targetEntry->stmt );
    291                   bool foundDefault = false;
    292                   for ( auto subStmt : switchStmt->stmts ) {
    293                           const CaseStmt * caseStmt = subStmt.strict_as<CaseStmt>();
    294                           if ( caseStmt->isDefault() ) {
    295                                   foundDefault = true;
    296                                   break;
    297                           }
    298                   }
    299                   if ( ! foundDefault ) {
    300                           SemanticError( stmt->location, "'fallthrough default' must be enclosed in a 'switch' or 'choose'"
    301                                                          "control structure with a 'default' clause" );
    302                   }
    303                   break;
    304           }
    305           default:
     234        case ast::BranchStmt::Continue:
     235        case ast::BranchStmt::Break: {
     236                bool isContinue = stmt->kind == ast::BranchStmt::Continue;
     237                // Handle unlabeled break and continue.
     238                if ( stmt->target.empty() ) {
     239                        if ( isContinue ) {
     240                                targetEntry = findEnclosingControlStructure( isContinueTarget );
     241                        } else {
     242                                if ( enclosing_control_structures.empty() ) {
     243                                        SemanticError( stmt->location,
     244                                                "'break' outside a loop, 'switch', or labelled block" );
     245                                }
     246                                targetEntry = findEnclosingControlStructure( isBreakTarget );
     247                        }
     248                // Handle labeled break and continue.
     249                } else {
     250                        // Lookup label in table to find attached control structure.
     251                        targetEntry = findEnclosingControlStructure(
     252                                [ targetStmt = target_table.at(stmt->target) ](auto entry){
     253                                        return entry.stmt == targetStmt;
     254                                } );
     255                }
     256                // Ensure that selected target is valid.
     257                if ( targetEntry == enclosing_control_structures.rend() || ( isContinue && !isContinueTarget( *targetEntry ) ) ) {
     258                        SemanticError(
     259                                stmt->location,
     260                                toString( (isContinue ? "'continue'" : "'break'"),
     261                                        " target must be an enclosing ",
     262                                        (isContinue ? "loop: " : "control structure: "),
     263                                        stmt->originalTarget ) );
     264                }
     265                break;
     266        }
     267        // handle fallthrough in case/switch stmts
     268        case ast::BranchStmt::FallThrough: {
     269                targetEntry = findEnclosingControlStructure( isFallthroughTarget );
     270                // Check that target is valid.
     271                if ( targetEntry == enclosing_control_structures.rend() ) {
     272                        SemanticError( stmt->location, "'fallthrough' must be enclosed in a 'switch' or 'choose'" );
     273                }
     274                if ( !stmt->target.empty() ) {
     275                        // Labelled fallthrough: target must be a valid fallthough label.
     276                        if ( !fallthrough_labels.count( stmt->target ) ) {
     277                                SemanticError( stmt->location, toString( "'fallthrough' target must be a later case statement: ", stmt->originalTarget ) );
     278                        }
     279                        return new ast::BranchStmt(
     280                                stmt->location, ast::BranchStmt::Goto, stmt->originalTarget );
     281                }
     282                break;
     283        }
     284        case ast::BranchStmt::FallThroughDefault: {
     285                targetEntry = findEnclosingControlStructure( isFallthroughDefaultTarget );
     286
     287                // Check that this is in a switch or choose statement.
     288                if ( targetEntry == enclosing_control_structures.rend() ) {
     289                        SemanticError( stmt->location, "'fallthrough' must be enclosed in a 'switch' or 'choose'" );
     290                }
     291
     292                // Check that the switch or choose has a default clause.
     293                auto switchStmt = strict_dynamic_cast< const ast::SwitchStmt * >(
     294                        targetEntry->stmt );
     295                bool foundDefault = false;
     296                for ( auto subStmt : switchStmt->stmts ) {
     297                        const ast::CaseStmt * caseStmt = subStmt.strict_as<ast::CaseStmt>();
     298                        if ( caseStmt->isDefault() ) {
     299                                foundDefault = true;
     300                                break;
     301                        }
     302                }
     303                if ( !foundDefault ) {
     304                        SemanticError( stmt->location, "'fallthrough default' must be enclosed in a 'switch' or 'choose' control structure with a 'default' clause" );
     305                }
     306                break;
     307        }
     308        default:
    306309                assert( false );
    307310        }
    308311
    309312        // Branch error checks: get the appropriate label name:
    310         // (This label is always replaced.)
    311         Label exitLabel( CodeLocation(), "" );
     313        // (This label will always be replaced.)
     314        ast::Label exitLabel( CodeLocation(), "" );
    312315        switch ( stmt->kind ) {
    313           case BranchStmt::Break:
     316        case ast::BranchStmt::Break:
    314317                assert( !targetEntry->useBreakExit().empty() );
    315318                exitLabel = targetEntry->useBreakExit();
    316319                break;
    317           case BranchStmt::Continue:
     320        case ast::BranchStmt::Continue:
    318321                assert( !targetEntry->useContExit().empty() );
    319322                exitLabel = targetEntry->useContExit();
    320323                break;
    321           case BranchStmt::FallThrough:
     324        case ast::BranchStmt::FallThrough:
    322325                assert( !targetEntry->useFallExit().empty() );
    323326                exitLabel = targetEntry->useFallExit();
    324327                break;
    325           case BranchStmt::FallThroughDefault:
     328        case ast::BranchStmt::FallThroughDefault:
    326329                assert( !targetEntry->useFallDefaultExit().empty() );
    327330                exitLabel = targetEntry->useFallDefaultExit();
    328331                // Check that fallthrough default comes before the default clause.
    329332                if ( !targetEntry->isFallDefaultValid() ) {
    330                         SemanticError( stmt->location, "'fallthrough default' must precede the 'default' clause" );
     333                        SemanticError( stmt->location,
     334                                "'fallthrough default' must precede the 'default' clause" );
    331335                }
    332336                break;
    333           default:
     337        default:
    334338                assert(0);
    335339        }
     
    338342        targetEntry->stmt = addUnused( targetEntry->stmt, stmt->originalTarget );
    339343
    340         // Replace with goto to make later passes more uniform.
    341         return new BranchStmt( stmt->location, BranchStmt::Goto, exitLabel );
    342 }
    343 
    344 void MultiLevelExitCore::previsit( const WhileDoStmt * stmt ) {
     344        // Replace this with a goto to make later passes more uniform.
     345        return new ast::BranchStmt( stmt->location, ast::BranchStmt::Goto, exitLabel );
     346}
     347
     348void MultiLevelExitCore::previsit( const ast::WhileStmt * stmt ) {
    345349        return prehandleLoopStmt( stmt );
    346350}
    347351
    348 const WhileDoStmt * MultiLevelExitCore::postvisit( const WhileDoStmt * stmt ) {
     352const ast::WhileStmt * MultiLevelExitCore::postvisit( const ast::WhileStmt * stmt ) {
    349353        return posthandleLoopStmt( stmt );
    350354}
    351355
    352 void MultiLevelExitCore::previsit( const ForStmt * stmt ) {
     356void MultiLevelExitCore::previsit( const ast::ForStmt * stmt ) {
    353357        return prehandleLoopStmt( stmt );
    354358}
    355359
    356 const ForStmt * MultiLevelExitCore::postvisit( const ForStmt * stmt ) {
     360const ast::ForStmt * MultiLevelExitCore::postvisit( const ast::ForStmt * stmt ) {
    357361        return posthandleLoopStmt( stmt );
    358362}
     
    360364// Mimic what the built-in push_front would do anyways. It is O(n).
    361365void push_front(
    362         vector<ptr<Stmt>> & vec, const Stmt * element ) {
     366                std::vector<ast::ptr<ast::Stmt>> & vec, const ast::Stmt * element ) {
    363367        vec.emplace_back( nullptr );
    364368        for ( size_t i = vec.size() - 1 ; 0 < i ; --i ) {
    365                 vec[ i ] = move( vec[ i - 1 ] );
     369                vec[ i ] = std::move( vec[ i - 1 ] );
    366370        }
    367371        vec[ 0 ] = element;
    368372}
    369373
    370 const CaseStmt * MultiLevelExitCore::previsit( const CaseStmt * stmt ) {
     374const ast::CaseStmt * MultiLevelExitCore::previsit( const ast::CaseStmt * stmt ) {
    371375        visit_children = false;
    372376
    373         // If default, mark seen.
     377        // If it is the default, mark the default as seen.
    374378        if ( stmt->isDefault() ) {
    375379                assert( !enclosing_control_structures.empty() );
     
    378382
    379383        // The cond may not exist, but if it does update it now.
    380         visitor->maybe_accept( stmt, &CaseStmt::cond );
     384        visitor->maybe_accept( stmt, &ast::CaseStmt::cond );
    381385
    382386        // Just save the mutated node for simplicity.
    383         CaseStmt * mutStmt = mutate( stmt );
    384 
    385         Label fallLabel = newLabel( "fallThrough", stmt );
    386         if ( ! mutStmt->stmts.empty() ) {
     387        ast::CaseStmt * mutStmt = ast::mutate( stmt );
     388
     389        ast::Label fallLabel = LabelGenerator::newLabel( "fallThrough", stmt );
     390        if ( !mutStmt->stmts.empty() ) {
    387391                // Ensure that the stack isn't corrupted by exceptions in fixBlock.
    388392                auto guard = makeFuncGuard(
    389393                        [&](){ enclosing_control_structures.emplace_back( mutStmt, fallLabel ); },
    390394                        [this](){ enclosing_control_structures.pop_back(); }
    391                         );
     395                );
    392396
    393397                // These should already be in a block.
    394                 auto block = mutate( mutStmt->stmts.front().strict_as<CompoundStmt>() );
     398                auto block = ast::mutate( mutStmt->stmts.front().strict_as<ast::CompoundStmt>() );
    395399                block->kids = fixBlock( block->kids, true );
    396400
    397401                // Add fallthrough label if necessary.
    398                 assert( ! enclosing_control_structures.empty() );
     402                assert( !enclosing_control_structures.empty() );
    399403                Entry & entry = enclosing_control_structures.back();
    400404                if ( entry.isFallUsed() ) {
     
    403407                }
    404408        }
    405         assert( ! enclosing_control_structures.empty() );
     409        assert( !enclosing_control_structures.empty() );
    406410        Entry & entry = enclosing_control_structures.back();
    407         assertf( dynamic_cast< const SwitchStmt * >( entry.stmt ),
    408                          "Control structure enclosing a case clause must be a switch, but is: %s",
    409                          toString( entry.stmt ).c_str() );
     411        assertf( dynamic_cast< const ast::SwitchStmt * >( entry.stmt ),
     412                "Control structure enclosing a case clause must be a switch, but is: %s",
     413                toString( entry.stmt ).c_str() );
    410414        if ( mutStmt->isDefault() ) {
    411415                if ( entry.isFallDefaultUsed() ) {
    412416                        // Add fallthrough default label if necessary.
    413417                        push_front( mutStmt->stmts, labelledNullStmt(
    414                                                         stmt->location, entry.useFallDefaultExit()
    415                                                         ) );
     418                                stmt->location, entry.useFallDefaultExit()
     419                        ) );
    416420                }
    417421        }
     
    419423}
    420424
    421 void MultiLevelExitCore::previsit( const IfStmt * stmt ) {
     425void MultiLevelExitCore::previsit( const ast::IfStmt * stmt ) {
    422426        bool labeledBlock = !stmt->labels.empty();
    423427        if ( labeledBlock ) {
    424                 Label breakLabel = newLabel( "blockBreak", stmt );
     428                ast::Label breakLabel = LabelGenerator::newLabel( "blockBreak", stmt );
    425429                enclosing_control_structures.emplace_back( stmt, breakLabel );
    426430                GuardAction( [this](){ enclosing_control_structures.pop_back(); } );
     
    428432}
    429433
    430 const IfStmt * MultiLevelExitCore::postvisit( const IfStmt * stmt ) {
     434const ast::IfStmt * MultiLevelExitCore::postvisit( const ast::IfStmt * stmt ) {
    431435        bool labeledBlock = !stmt->labels.empty();
    432436        if ( labeledBlock ) {
     
    439443}
    440444
    441 bool isDefaultCase( const ptr<Stmt> & stmt ) {
    442         const CaseStmt * caseStmt = stmt.strict_as<CaseStmt>();
     445bool isDefaultCase( const ast::ptr<ast::Stmt> & stmt ) {
     446        const ast::CaseStmt * caseStmt = stmt.strict_as<ast::CaseStmt>();
    443447        return caseStmt->isDefault();
    444448}
    445449
    446 void MultiLevelExitCore::previsit( const SwitchStmt * stmt ) {
    447         Label label = newLabel( "switchBreak", stmt );
    448         auto it = find_if( stmt->stmts.rbegin(), stmt->stmts.rend(), isDefaultCase );
    449 
    450         const CaseStmt * defaultCase = it != stmt->stmts.rend()
    451                 ? (it)->strict_as<CaseStmt>() : nullptr;
    452         Label defaultLabel = defaultCase
    453                 ? newLabel( "fallThroughDefault", defaultCase )
    454                 : Label( stmt->location, "" );
     450void MultiLevelExitCore::previsit( const ast::SwitchStmt * stmt ) {
     451        ast::Label label = LabelGenerator::newLabel( "switchBreak", stmt );
     452        auto it = std::find_if( stmt->stmts.rbegin(), stmt->stmts.rend(), isDefaultCase );
     453
     454        const ast::CaseStmt * defaultCase = it != stmt->stmts.rend()
     455                ? (it)->strict_as<ast::CaseStmt>() : nullptr;
     456        ast::Label defaultLabel = defaultCase
     457                ? LabelGenerator::newLabel( "fallThroughDefault", defaultCase )
     458                : ast::Label( stmt->location, "" );
    455459        enclosing_control_structures.emplace_back( stmt, label, defaultLabel );
    456460        GuardAction( [this]() { enclosing_control_structures.pop_back(); } );
    457461
    458462        // Collect valid labels for fallthrough. It starts with all labels at
    459         // this level, then remove as each is seen during traversal.
    460         for ( const Stmt * stmt : stmt->stmts ) {
    461                 auto * caseStmt = strict_dynamic_cast< const CaseStmt * >( stmt );
     463        // this level, then removed as we see them in traversal.
     464        for ( const ast::Stmt * stmt : stmt->stmts ) {
     465                auto * caseStmt = strict_dynamic_cast< const ast::CaseStmt * >( stmt );
    462466                if ( caseStmt->stmts.empty() ) continue;
    463                 auto block = caseStmt->stmts.front().strict_as<CompoundStmt>();
    464                 for ( const Stmt * stmt : block->kids ) {
    465                         for ( const Label & l : stmt->labels ) {
     467                auto block = caseStmt->stmts.front().strict_as<ast::CompoundStmt>();
     468                for ( const ast::Stmt * stmt : block->kids ) {
     469                        for ( const ast::Label & l : stmt->labels ) {
    466470                                fallthrough_labels.insert( l );
    467471                        }
     
    470474}
    471475
    472 const SwitchStmt * MultiLevelExitCore::postvisit( const SwitchStmt * stmt ) {
     476const ast::SwitchStmt * MultiLevelExitCore::postvisit( const ast::SwitchStmt * stmt ) {
    473477        assert( !enclosing_control_structures.empty() );
    474478        Entry & entry = enclosing_control_structures.back();
    475479        assert( entry.stmt == stmt );
    476480
    477         // Only run to generate the break label.
     481        // Only run if we need to generate the break label.
    478482        if ( entry.isBreakUsed() ) {
    479483                // To keep the switch statements uniform (all direct children of a
    480484                // SwitchStmt should be CastStmts), append the exit label and break
    481485                // to the last case, create a default case is there are no cases.
    482                 SwitchStmt * mutStmt = mutate( stmt );
     486                ast::SwitchStmt * mutStmt = ast::mutate( stmt );
    483487                if ( mutStmt->stmts.empty() ) {
    484                         mutStmt->stmts.push_back( new CaseStmt(
    485                                                                                   mutStmt->location, nullptr, {} ));
    486                 }
    487 
    488                 auto caseStmt = mutStmt->stmts.back().strict_as<CaseStmt>();
    489                 auto mutCase = mutate( caseStmt );
     488                        mutStmt->stmts.push_back( new ast::CaseStmt(
     489                                mutStmt->location, nullptr, {} ));
     490                }
     491
     492                auto caseStmt = mutStmt->stmts.back().strict_as<ast::CaseStmt>();
     493                auto mutCase = ast::mutate( caseStmt );
    490494                mutStmt->stmts.back() = mutCase;
    491495
    492                 Label label( mutCase->location, "breakLabel" );
    493                 auto branch = new BranchStmt( mutCase->location, BranchStmt::Break, label );
     496                ast::Label label( mutCase->location, "breakLabel" );
     497                auto branch = new ast::BranchStmt( mutCase->location, ast::BranchStmt::Break, label );
    494498                branch->labels.push_back( entry.useBreakExit() );
    495499                mutCase->stmts.push_back( branch );
     
    500504}
    501505
    502 void MultiLevelExitCore::previsit( const ReturnStmt * stmt ) {
     506void MultiLevelExitCore::previsit( const ast::ReturnStmt * stmt ) {
    503507        if ( inFinally ) {
    504508                SemanticError( stmt->location, "'return' may not appear in a finally clause" );
     
    506510}
    507511
    508 void MultiLevelExitCore::previsit( const TryStmt * stmt ) {
     512void MultiLevelExitCore::previsit( const ast::TryStmt * stmt ) {
    509513        bool isLabeled = !stmt->labels.empty();
    510514        if ( isLabeled ) {
    511                 Label breakLabel = newLabel( "blockBreak", stmt );
     515                ast::Label breakLabel = LabelGenerator::newLabel( "blockBreak", stmt );
    512516                enclosing_control_structures.emplace_back( stmt, breakLabel );
    513517                GuardAction([this](){ enclosing_control_structures.pop_back(); } );
     
    515519}
    516520
    517 void MultiLevelExitCore::postvisit( const TryStmt * stmt ) {
     521void MultiLevelExitCore::postvisit( const ast::TryStmt * stmt ) {
    518522        bool isLabeled = !stmt->labels.empty();
    519523        if ( isLabeled ) {
     
    525529}
    526530
    527 void MultiLevelExitCore::previsit( const FinallyStmt * ) {
    528         GuardAction([this, old = move(enclosing_control_structures)](){
    529                                         enclosing_control_structures = move(old);
    530                                 });
    531         enclosing_control_structures = vector<Entry>();
     531void MultiLevelExitCore::previsit( const ast::FinallyStmt * ) {
     532        GuardAction([this, old = std::move(enclosing_control_structures)](){
     533                enclosing_control_structures = std::move(old);
     534        });
     535        enclosing_control_structures = std::vector<Entry>();
    532536        GuardValue( inFinally ) = true;
    533537}
    534538
    535 const Stmt * MultiLevelExitCore::mutateLoop(
    536         const Stmt * body, Entry & entry ) {
     539const ast::Stmt * MultiLevelExitCore::mutateLoop(
     540                const ast::Stmt * body, Entry & entry ) {
    537541        if ( entry.isBreakUsed() ) {
    538542                break_label = entry.useBreakExit();
     
    541545        // if continue is used insert a continue label into the back of the body of the loop
    542546        if ( entry.isContUsed() ) {
    543                 CompoundStmt * new_body = new CompoundStmt( body->location );
     547                ast::CompoundStmt * new_body = new ast::CompoundStmt( body->location );
    544548                // {}
    545549                new_body->kids.push_back( body );
     
    563567        // Remember is loop before going onto mutate the body.
    564568        // The labels will be folded in if they are used.
    565         Label breakLabel = newLabel( "loopBreak", loopStmt );
    566         Label contLabel = newLabel( "loopContinue", loopStmt );
     569        ast::Label breakLabel = LabelGenerator::newLabel( "loopBreak", loopStmt );
     570        ast::Label contLabel = LabelGenerator::newLabel( "loopContinue", loopStmt );
    567571        enclosing_control_structures.emplace_back( loopStmt, breakLabel, contLabel );
    568572        // labels are added temporarily to see if they are used and then added permanently in postvisit if ther are used
     
    579583        assert( entry.stmt == loopStmt );
    580584
    581         // Now check if the labels are used and add them if so.
    582         return mutate_field(
     585        // Now we check if the labels are used and add them if so.
     586        return ast::mutate_field(
    583587                loopStmt, &LoopNode::body, mutateLoop( loopStmt->body, entry ) );
    584588        // this call to mutate_field compares loopStmt->body and the result of mutateLoop
     
    587591}
    588592
    589 list<ptr<Stmt>> MultiLevelExitCore::fixBlock(
    590         const list<ptr<Stmt>> & kids, bool is_case_clause ) {
    591         // Unfortunately cannot use automatic error collection.
     593std::list<ast::ptr<ast::Stmt>> MultiLevelExitCore::fixBlock(
     594                const std::list<ast::ptr<ast::Stmt>> & kids, bool is_case_clause ) {
     595        // Unfortunately we can't use the automatic error collection.
    592596        SemanticErrorException errors;
    593597
    594         list<ptr<Stmt>> ret;
     598        std::list<ast::ptr<ast::Stmt>> ret;
    595599
    596600        // Manually visit each child.
    597         for ( const ptr<Stmt> & kid : kids ) {
     601        for ( const ast::ptr<ast::Stmt> & kid : kids ) {
    598602                if ( is_case_clause ) {
    599603                        // Once a label is seen, it's no longer a valid for fallthrough.
    600                         for ( const Label & l : kid->labels ) {
     604                        for ( const ast::Label & l : kid->labels ) {
    601605                                fallthrough_labels.erase( l );
    602606                        }
     
    612616                        ret.push_back(
    613617                                labelledNullStmt( ret.back()->location, break_label ) );
    614                         break_label = Label( CodeLocation(), "" );
     618                        break_label = ast::Label( CodeLocation(), "" );
    615619                }
    616620        }
     
    622626}
    623627
    624 const CompoundStmt * multiLevelExitUpdate(
    625         const CompoundStmt * stmt,
    626         const LabelToStmt & labelTable ) {
     628} // namespace
     629
     630const ast::CompoundStmt * multiLevelExitUpdate(
     631        const ast::CompoundStmt * stmt,
     632                const LabelToStmt & labelTable ) {
    627633        // Must start in the body, so FunctionDecls can be a stopping point.
    628         Pass<MultiLevelExitCore> visitor( labelTable );
    629         const CompoundStmt * ret = stmt->accept( visitor );
     634        ast::Pass<MultiLevelExitCore> visitor( labelTable );
     635        const ast::CompoundStmt * ret = stmt->accept( visitor );
    630636        return ret;
    631637}
     638
    632639} // namespace ControlStruct
    633640
Note: See TracChangeset for help on using the changeset viewer.