Ignore:
File:
1 edited

Legend:

Unmodified
Added
Removed
  • src/ControlStruct/MultiLevelExit.cpp

    r66daee4 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 : 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        // These routines set a target as being "used" by a BranchStmt
     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); }
     79
     80        // These routines check if a specific label for a statement is used by a BranchStmt
     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; }
    8285        void seenDefault() { fallDefaultValid = false; }
    8386        bool isFallDefaultValid() const { return fallDefaultValid; }
    8487};
    8588
    86 // 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):
    8790bool isBreakTarget( const Entry & entry ) {
    8891        return entry.isBreakTarget();
     
    102105
    103106struct MultiLevelExitCore final :
    104         public WithVisitorRef<MultiLevelExitCore>,
    105         public WithShortCircuiting, public WithGuards {
     107                public ast::WithVisitorRef<MultiLevelExitCore>,
     108                public ast::WithShortCircuiting, public ast::WithGuards {
    106109        MultiLevelExitCore( const LabelToStmt & lt );
    107110
    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& );
     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& );
    127130
    128131        const LabelToStmt & target_table;
    129         set<Label> fallthrough_labels;
    130         vector<Entry> enclosing_control_structures;
    131         Label break_label;
     132        std::set<ast::Label> fallthrough_labels;
     133        std::vector<Entry> enclosing_control_structures;
     134        ast::Label break_label;
    132135        bool inFinally;
    133136
     
    137140        const LoopNode * posthandleLoopStmt( const LoopNode * loopStmt );
    138141
    139         list<ptr<Stmt>> fixBlock(
    140                 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 );
    141144
    142145        template<typename UnaryPredicate>
    143146        auto findEnclosingControlStructure( UnaryPredicate pred ) {
    144                 return find_if( enclosing_control_structures.rbegin(),
    145                                                 enclosing_control_structures.rend(), pred );
     147                return std::find_if( enclosing_control_structures.rbegin(),
     148                        enclosing_control_structures.rend(), pred );
    146149        }
    147150};
    148151
    149 NullStmt * labelledNullStmt(
    150         const CodeLocation & cl, const Label & label ) {
    151         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 } );
    152155}
    153156
     
    157160{}
    158161
    159 void MultiLevelExitCore::previsit( const FunctionDecl * ) {
     162void MultiLevelExitCore::previsit( const ast::FunctionDecl * ) {
    160163        visit_children = false;
    161164}
    162165
    163 const CompoundStmt * MultiLevelExitCore::previsit(
    164         const CompoundStmt * stmt ) {
     166const ast::CompoundStmt * MultiLevelExitCore::previsit(
     167                const ast::CompoundStmt * stmt ) {
    165168        visit_children = false;
     169
     170        // if the stmt is labelled then generate a label to check in postvisit if the label is used
    166171        bool isLabeled = !stmt->labels.empty();
    167172        if ( isLabeled ) {
    168                 Label breakLabel = newLabel( "blockBreak", stmt );
     173                ast::Label breakLabel = LabelGenerator::newLabel( "blockBreak", stmt );
    169174                enclosing_control_structures.emplace_back( stmt, breakLabel );
    170175                GuardAction( [this]() { enclosing_control_structures.pop_back(); } );
    171176        }
    172177
    173         auto mutStmt = mutate( stmt );
     178        auto mutStmt = ast::mutate( stmt );
    174179        // A child statement may set the break label.
    175         mutStmt->kids = move( fixBlock( stmt->kids, false ) );
     180        mutStmt->kids = std::move( fixBlock( stmt->kids, false ) );
    176181
    177182        if ( isLabeled ) {
     
    186191
    187192size_t getUnusedIndex(
    188         const Stmt * stmt, const Label & originalTarget ) {
     193                const ast::Stmt * stmt, const ast::Label & originalTarget ) {
    189194        const size_t size = stmt->labels.size();
    190195
    191         // If the label is empty, do not add unused attribute.
    192   if ( originalTarget.empty() ) return size;
     196        // If the label is empty, we can skip adding the unused attribute:
     197        if ( originalTarget.empty() ) return size;
    193198
    194199        // Search for a label that matches the originalTarget.
    195200        for ( size_t i = 0 ; i < size ; ++i ) {
    196                 const Label & label = stmt->labels[i];
     201                const ast::Label & label = stmt->labels[i];
    197202                if ( label == originalTarget ) {
    198                         for ( const Attribute * attr : label.attributes ) {
     203                        for ( const ast::Attribute * attr : label.attributes ) {
    199204                                if ( attr->name == "unused" ) return size;
    200205                        }
     
    203208        }
    204209        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 ) {
     210                originalTarget.name.c_str(), toString( stmt ).c_str() );
     211}
     212
     213const ast::Stmt * addUnused(
     214                const ast::Stmt * stmt, const ast::Label & originalTarget ) {
    210215        size_t i = getUnusedIndex( stmt, originalTarget );
    211216        if ( i == stmt->labels.size() ) {
    212217                return stmt;
    213218        }
    214         Stmt * mutStmt = mutate( stmt );
    215         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" ) );
    216221        return mutStmt;
    217222}
    218223
    219 const BranchStmt * MultiLevelExitCore::postvisit( const BranchStmt * stmt ) {
    220         vector<Entry>::reverse_iterator targetEntry =
     224// This routine updates targets on enclosing control structures to indicate which
     225//     label is used by the BranchStmt that is passed
     226const ast::BranchStmt * MultiLevelExitCore::postvisit( const ast::BranchStmt * stmt ) {
     227        std::vector<Entry>::reverse_iterator targetEntry =
    221228                enclosing_control_structures.rend();
     229
     230        // Labels on different stmts require different approaches to access
    222231        switch ( stmt->kind ) {
    223           case BranchStmt::Goto:
     232        case ast::BranchStmt::Goto:
    224233                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:
     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:
    297309                assert( false );
    298310        }
    299311
    300312        // Branch error checks: get the appropriate label name:
    301         // (This label is always replaced.)
    302         Label exitLabel( CodeLocation(), "" );
     313        // (This label will always be replaced.)
     314        ast::Label exitLabel( CodeLocation(), "" );
    303315        switch ( stmt->kind ) {
    304           case BranchStmt::Break:
     316        case ast::BranchStmt::Break:
    305317                assert( !targetEntry->useBreakExit().empty() );
    306318                exitLabel = targetEntry->useBreakExit();
    307319                break;
    308           case BranchStmt::Continue:
     320        case ast::BranchStmt::Continue:
    309321                assert( !targetEntry->useContExit().empty() );
    310322                exitLabel = targetEntry->useContExit();
    311323                break;
    312           case BranchStmt::FallThrough:
     324        case ast::BranchStmt::FallThrough:
    313325                assert( !targetEntry->useFallExit().empty() );
    314326                exitLabel = targetEntry->useFallExit();
    315327                break;
    316           case BranchStmt::FallThroughDefault:
     328        case ast::BranchStmt::FallThroughDefault:
    317329                assert( !targetEntry->useFallDefaultExit().empty() );
    318330                exitLabel = targetEntry->useFallDefaultExit();
    319331                // Check that fallthrough default comes before the default clause.
    320332                if ( !targetEntry->isFallDefaultValid() ) {
    321                         SemanticError( stmt->location, "'fallthrough default' must precede the 'default' clause" );
     333                        SemanticError( stmt->location,
     334                                "'fallthrough default' must precede the 'default' clause" );
    322335                }
    323336                break;
    324           default:
     337        default:
    325338                assert(0);
    326339        }
     
    329342        targetEntry->stmt = addUnused( targetEntry->stmt, stmt->originalTarget );
    330343
    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 ) {
     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 ) {
    336349        return prehandleLoopStmt( stmt );
    337350}
    338351
    339 const WhileStmt * MultiLevelExitCore::postvisit( const WhileStmt * stmt ) {
     352const ast::WhileStmt * MultiLevelExitCore::postvisit( const ast::WhileStmt * stmt ) {
    340353        return posthandleLoopStmt( stmt );
    341354}
    342355
    343 void MultiLevelExitCore::previsit( const ForStmt * stmt ) {
     356void MultiLevelExitCore::previsit( const ast::ForStmt * stmt ) {
    344357        return prehandleLoopStmt( stmt );
    345358}
    346359
    347 const ForStmt * MultiLevelExitCore::postvisit( const ForStmt * stmt ) {
     360const ast::ForStmt * MultiLevelExitCore::postvisit( const ast::ForStmt * stmt ) {
    348361        return posthandleLoopStmt( stmt );
    349362}
     
    351364// Mimic what the built-in push_front would do anyways. It is O(n).
    352365void push_front(
    353         vector<ptr<Stmt>> & vec, const Stmt * element ) {
     366                std::vector<ast::ptr<ast::Stmt>> & vec, const ast::Stmt * element ) {
    354367        vec.emplace_back( nullptr );
    355368        for ( size_t i = vec.size() - 1 ; 0 < i ; --i ) {
    356                 vec[ i ] = move( vec[ i - 1 ] );
     369                vec[ i ] = std::move( vec[ i - 1 ] );
    357370        }
    358371        vec[ 0 ] = element;
    359372}
    360373
    361 const CaseStmt * MultiLevelExitCore::previsit( const CaseStmt * stmt ) {
     374const ast::CaseStmt * MultiLevelExitCore::previsit( const ast::CaseStmt * stmt ) {
    362375        visit_children = false;
    363376
    364         // If default, mark seen.
     377        // If it is the default, mark the default as seen.
    365378        if ( stmt->isDefault() ) {
    366379                assert( !enclosing_control_structures.empty() );
     
    369382
    370383        // The cond may not exist, but if it does update it now.
    371         visitor->maybe_accept( stmt, &CaseStmt::cond );
     384        visitor->maybe_accept( stmt, &ast::CaseStmt::cond );
    372385
    373386        // Just save the mutated node for simplicity.
    374         CaseStmt * mutStmt = mutate( stmt );
    375 
    376         Label fallLabel = newLabel( "fallThrough", stmt );
    377         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() ) {
    378391                // Ensure that the stack isn't corrupted by exceptions in fixBlock.
    379392                auto guard = makeFuncGuard(
    380393                        [&](){ enclosing_control_structures.emplace_back( mutStmt, fallLabel ); },
    381394                        [this](){ enclosing_control_structures.pop_back(); }
    382                         );
     395                );
    383396
    384397                // These should already be in a block.
    385                 auto block = mutate( mutStmt->stmts.front().strict_as<CompoundStmt>() );
     398                auto block = ast::mutate( mutStmt->stmts.front().strict_as<ast::CompoundStmt>() );
    386399                block->kids = fixBlock( block->kids, true );
    387400
    388401                // Add fallthrough label if necessary.
    389                 assert( ! enclosing_control_structures.empty() );
     402                assert( !enclosing_control_structures.empty() );
    390403                Entry & entry = enclosing_control_structures.back();
    391404                if ( entry.isFallUsed() ) {
     
    394407                }
    395408        }
    396         assert( ! enclosing_control_structures.empty() );
     409        assert( !enclosing_control_structures.empty() );
    397410        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() );
     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() );
    401414        if ( mutStmt->isDefault() ) {
    402415                if ( entry.isFallDefaultUsed() ) {
    403416                        // Add fallthrough default label if necessary.
    404417                        push_front( mutStmt->stmts, labelledNullStmt(
    405                                                         stmt->location, entry.useFallDefaultExit()
    406                                                         ) );
     418                                stmt->location, entry.useFallDefaultExit()
     419                        ) );
    407420                }
    408421        }
     
    410423}
    411424
    412 void MultiLevelExitCore::previsit( const IfStmt * stmt ) {
     425void MultiLevelExitCore::previsit( const ast::IfStmt * stmt ) {
    413426        bool labeledBlock = !stmt->labels.empty();
    414427        if ( labeledBlock ) {
    415                 Label breakLabel = newLabel( "blockBreak", stmt );
     428                ast::Label breakLabel = LabelGenerator::newLabel( "blockBreak", stmt );
    416429                enclosing_control_structures.emplace_back( stmt, breakLabel );
    417430                GuardAction( [this](){ enclosing_control_structures.pop_back(); } );
     
    419432}
    420433
    421 const IfStmt * MultiLevelExitCore::postvisit( const IfStmt * stmt ) {
     434const ast::IfStmt * MultiLevelExitCore::postvisit( const ast::IfStmt * stmt ) {
    422435        bool labeledBlock = !stmt->labels.empty();
    423436        if ( labeledBlock ) {
     
    430443}
    431444
    432 bool isDefaultCase( const ptr<Stmt> & stmt ) {
    433         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>();
    434447        return caseStmt->isDefault();
    435448}
    436449
    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, "" );
     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, "" );
    446459        enclosing_control_structures.emplace_back( stmt, label, defaultLabel );
    447460        GuardAction( [this]() { enclosing_control_structures.pop_back(); } );
    448461
    449462        // 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 );
     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 );
    453466                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 ) {
     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 ) {
    457470                                fallthrough_labels.insert( l );
    458471                        }
     
    461474}
    462475
    463 const SwitchStmt * MultiLevelExitCore::postvisit( const SwitchStmt * stmt ) {
     476const ast::SwitchStmt * MultiLevelExitCore::postvisit( const ast::SwitchStmt * stmt ) {
    464477        assert( !enclosing_control_structures.empty() );
    465478        Entry & entry = enclosing_control_structures.back();
    466479        assert( entry.stmt == stmt );
    467480
    468         // Only run to generate the break label.
     481        // Only run if we need to generate the break label.
    469482        if ( entry.isBreakUsed() ) {
    470483                // To keep the switch statements uniform (all direct children of a
    471484                // SwitchStmt should be CastStmts), append the exit label and break
    472485                // to the last case, create a default case is there are no cases.
    473                 SwitchStmt * mutStmt = mutate( stmt );
     486                ast::SwitchStmt * mutStmt = ast::mutate( stmt );
    474487                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 );
     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 );
    481494                mutStmt->stmts.back() = mutCase;
    482495
    483                 Label label( mutCase->location, "breakLabel" );
    484                 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 );
    485498                branch->labels.push_back( entry.useBreakExit() );
    486499                mutCase->stmts.push_back( branch );
     
    491504}
    492505
    493 void MultiLevelExitCore::previsit( const ReturnStmt * stmt ) {
     506void MultiLevelExitCore::previsit( const ast::ReturnStmt * stmt ) {
    494507        if ( inFinally ) {
    495508                SemanticError( stmt->location, "'return' may not appear in a finally clause" );
     
    497510}
    498511
    499 void MultiLevelExitCore::previsit( const TryStmt * stmt ) {
     512void MultiLevelExitCore::previsit( const ast::TryStmt * stmt ) {
    500513        bool isLabeled = !stmt->labels.empty();
    501514        if ( isLabeled ) {
    502                 Label breakLabel = newLabel( "blockBreak", stmt );
     515                ast::Label breakLabel = LabelGenerator::newLabel( "blockBreak", stmt );
    503516                enclosing_control_structures.emplace_back( stmt, breakLabel );
    504517                GuardAction([this](){ enclosing_control_structures.pop_back(); } );
     
    506519}
    507520
    508 void MultiLevelExitCore::postvisit( const TryStmt * stmt ) {
     521void MultiLevelExitCore::postvisit( const ast::TryStmt * stmt ) {
    509522        bool isLabeled = !stmt->labels.empty();
    510523        if ( isLabeled ) {
     
    516529}
    517530
    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>();
     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>();
    523536        GuardValue( inFinally ) = true;
    524537}
    525538
    526 const Stmt * MultiLevelExitCore::mutateLoop(
    527         const Stmt * body, Entry & entry ) {
     539const ast::Stmt * MultiLevelExitCore::mutateLoop(
     540                const ast::Stmt * body, Entry & entry ) {
    528541        if ( entry.isBreakUsed() ) {
    529542                break_label = entry.useBreakExit();
    530543        }
    531544
     545        // if continue is used insert a continue label into the back of the body of the loop
    532546        if ( entry.isContUsed() ) {
    533                 CompoundStmt * new_body = new CompoundStmt( body->location );
     547                ast::CompoundStmt * new_body = new ast::CompoundStmt( body->location );
     548                // {}
    534549                new_body->kids.push_back( body );
     550                // {
     551                //  body
     552                // }
    535553                new_body->kids.push_back(
    536554                        labelledNullStmt( body->location, entry.useContExit() ) );
     555                // {
     556                //  body
     557                //  ContinueLabel: {}
     558                // }
    537559                return new_body;
    538560        }
     
    545567        // Remember is loop before going onto mutate the body.
    546568        // The labels will be folded in if they are used.
    547         Label breakLabel = newLabel( "loopBreak", loopStmt );
    548         Label contLabel = newLabel( "loopContinue", loopStmt );
     569        ast::Label breakLabel = LabelGenerator::newLabel( "loopBreak", loopStmt );
     570        ast::Label contLabel = LabelGenerator::newLabel( "loopContinue", loopStmt );
    549571        enclosing_control_structures.emplace_back( loopStmt, breakLabel, contLabel );
     572        // labels are added temporarily to see if they are used and then added permanently in postvisit if ther are used
     573        // children will tag labels as being used during their traversal which occurs before postvisit
     574
     575        // GuardAction calls the lambda after the node is done being visited
    550576        GuardAction( [this](){ enclosing_control_structures.pop_back(); } );
    551577}
     
    557583        assert( entry.stmt == loopStmt );
    558584
    559         // Now check if the labels are used and add them if so.
    560         return mutate_field(
     585        // Now we check if the labels are used and add them if so.
     586        return ast::mutate_field(
    561587                loopStmt, &LoopNode::body, mutateLoop( loopStmt->body, entry ) );
    562 }
    563 
    564 list<ptr<Stmt>> MultiLevelExitCore::fixBlock(
    565         const list<ptr<Stmt>> & kids, bool is_case_clause ) {
    566         // Unfortunately cannot use automatic error collection.
     588        // this call to mutate_field compares loopStmt->body and the result of mutateLoop
     589        //              if they are the same the node isn't mutated, if they differ then the new mutated node is returned
     590        //              the stmts will only differ if a label is used
     591}
     592
     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.
    567596        SemanticErrorException errors;
    568597
    569         list<ptr<Stmt>> ret;
     598        std::list<ast::ptr<ast::Stmt>> ret;
    570599
    571600        // Manually visit each child.
    572         for ( const ptr<Stmt> & kid : kids ) {
     601        for ( const ast::ptr<ast::Stmt> & kid : kids ) {
    573602                if ( is_case_clause ) {
    574603                        // Once a label is seen, it's no longer a valid for fallthrough.
    575                         for ( const Label & l : kid->labels ) {
     604                        for ( const ast::Label & l : kid->labels ) {
    576605                                fallthrough_labels.erase( l );
    577606                        }
     
    587616                        ret.push_back(
    588617                                labelledNullStmt( ret.back()->location, break_label ) );
    589                         break_label = Label( CodeLocation(), "" );
     618                        break_label = ast::Label( CodeLocation(), "" );
    590619                }
    591620        }
     
    597626}
    598627
    599 const CompoundStmt * multiLevelExitUpdate(
    600         const CompoundStmt * stmt,
    601         const LabelToStmt & labelTable ) {
     628} // namespace
     629
     630const ast::CompoundStmt * multiLevelExitUpdate(
     631        const ast::CompoundStmt * stmt,
     632                const LabelToStmt & labelTable ) {
    602633        // Must start in the body, so FunctionDecls can be a stopping point.
    603         Pass<MultiLevelExitCore> visitor( labelTable );
    604         const CompoundStmt * ret = stmt->accept( visitor );
     634        ast::Pass<MultiLevelExitCore> visitor( labelTable );
     635        const ast::CompoundStmt * ret = stmt->accept( visitor );
    605636        return ret;
    606637}
     638
    607639} // namespace ControlStruct
    608640
Note: See TracChangeset for help on using the changeset viewer.