Ignore:
File:
1 edited

Legend:

Unmodified
Added
Removed
  • src/ControlStruct/MultiLevelExit.cpp

    r2f52b18 rcb921d4  
    99// Author           : Andrew Beach
    1010// Created On       : Mon Nov  1 13:48:00 2021
    11 // Last Modified By : Peter A. Buhr
    12 // Last Modified On : Wed Feb  2 23:07:54 2022
    13 // Update Count     : 33
     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        }
    51   public:
    52         Entry( const ForStmt * stmt, Label breakExit, Label contExit ) :
    53                 stmt( stmt ), firstTarget( breakExit ), secondTarget( contExit ), kind( ForStmtK ) {}
    54         Entry( const WhileDoStmt * stmt, Label breakExit, Label contExit ) :
    55                 stmt( stmt ), firstTarget( breakExit ), secondTarget( contExit ), kind( WhileDoStmtK ) {}
    56         Entry( const CompoundStmt *stmt, Label breakExit ) :
    57                 stmt( stmt ), firstTarget( breakExit ), secondTarget(), kind( CompoundStmtK ) {}
    58         Entry( const IfStmt *stmt, Label breakExit ) :
    59                 stmt( stmt ), firstTarget( breakExit ), secondTarget(), kind( IfStmtK ) {}
    60         Entry( const CaseStmt *stmt, Label fallExit ) :
    61                 stmt( stmt ), firstTarget( fallExit ), secondTarget(), kind( CaseStmtK ) {}
    62         Entry( const SwitchStmt *stmt, Label breakExit, Label fallDefaultExit ) :
    63                 stmt( stmt ), firstTarget( breakExit ), secondTarget( fallDefaultExit ), kind( SwitchStmtK ) {}
    64         Entry( const TryStmt *stmt, Label breakExit ) :
    65                 stmt( stmt ), firstTarget( breakExit ), secondTarget(), kind( TryStmtK ) {}
    66 
    67         bool isContTarget() const { return kind <= WhileDoStmtK; }
    68         bool isBreakTarget() const { return kind != CaseStmtK; }
    69         bool isFallTarget() const { return kind == CaseStmtK; }
    70         bool isFallDefaultTarget() const { return kind == SwitchStmtK; }
    71 
    72         // These routines set a target as being "used" by a BranchStmt
    73         Label useContExit() { assert( kind <= WhileDoStmtK ); 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         // These routines check if a specific label for a statement is used by a BranchStmt
    79         bool isContUsed() const { assert( kind <= WhileDoStmtK ); return secondTarget.used; }
    80         bool isBreakUsed() const { assert( kind != CaseStmtK ); return firstTarget.used; }
    81         bool isFallUsed() const { assert( kind == CaseStmtK ); return firstTarget.used; }
    82         bool isFallDefaultUsed() const { assert( kind == SwitchStmtK ); return secondTarget.used; }
     52
     53public:
     54        Entry( const ast::ForStmt * stmt, ast::Label breakExit, ast::Label contExit ) :
     55                stmt( stmt ), firstTarget( breakExit ), secondTarget( contExit ), kind( ForStmt ) {}
     56        Entry( const ast::WhileStmt * stmt, ast::Label breakExit, ast::Label contExit ) :
     57                stmt( stmt ), firstTarget( breakExit ), secondTarget( contExit ), kind( WhileStmt ) {}
     58        Entry( const ast::CompoundStmt *stmt, ast::Label breakExit ) :
     59                stmt( stmt ), firstTarget( breakExit ), secondTarget(), kind( CompoundStmt ) {}
     60        Entry( const ast::IfStmt *stmt, ast::Label breakExit ) :
     61                stmt( stmt ), firstTarget( breakExit ), secondTarget(), kind( IfStmt ) {}
     62        Entry( const ast::CaseStmt *stmt, ast::Label fallExit ) :
     63                stmt( stmt ), firstTarget( fallExit ), secondTarget(), kind( CaseStmt ) {}
     64        Entry( const ast::SwitchStmt *stmt, ast::Label breakExit, ast::Label fallDefaultExit ) :
     65                stmt( stmt ), firstTarget( breakExit ), secondTarget( fallDefaultExit ), kind( SwitchStmt ) {}
     66        Entry( const ast::TryStmt *stmt, ast::Label breakExit ) :
     67                stmt( stmt ), firstTarget( breakExit ), secondTarget(), kind( TryStmt ) {}
     68
     69        bool isContTarget() const { return kind <= WhileStmt; }
     70        bool isBreakTarget() const { return CaseStmt != kind; }
     71        bool isFallTarget() const { return CaseStmt == kind; }
     72        bool isFallDefaultTarget() const { return SwitchStmt == kind; }
     73
     74        ast::Label useContExit() { assert( kind <= WhileStmt ); return useTarget(secondTarget); }
     75        ast::Label useBreakExit() { assert( CaseStmt != kind ); return useTarget(firstTarget); }
     76        ast::Label useFallExit() { assert( CaseStmt == kind );  return useTarget(firstTarget); }
     77        ast::Label useFallDefaultExit() { assert( SwitchStmt == kind ); return useTarget(secondTarget); }
     78
     79        bool isContUsed() const { assert( kind <= WhileStmt ); return secondTarget.used; }
     80        bool isBreakUsed() const { assert( CaseStmt != kind ); return firstTarget.used; }
     81        bool isFallUsed() const { assert( CaseStmt == kind ); return firstTarget.used; }
     82        bool isFallDefaultUsed() const { assert( SwitchStmt == kind ); return secondTarget.used; }
    8383        void seenDefault() { fallDefaultValid = false; }
    8484        bool isFallDefaultValid() const { return fallDefaultValid; }
    8585};
    8686
    87 // Helper predicates used in find_if calls (it doesn't take methods):
     87// Helper predicates used in std::find_if calls (it doesn't take methods):
    8888bool isBreakTarget( const Entry & entry ) {
    8989        return entry.isBreakTarget();
     
    103103
    104104struct MultiLevelExitCore final :
    105         public WithVisitorRef<MultiLevelExitCore>,
    106         public WithShortCircuiting, public WithGuards {
     105                public ast::WithVisitorRef<MultiLevelExitCore>,
     106                public ast::WithShortCircuiting, public ast::WithGuards {
    107107        MultiLevelExitCore( const LabelToStmt & lt );
    108108
    109         void previsit( const FunctionDecl * );
    110 
    111         const CompoundStmt * previsit( const CompoundStmt * );
    112         const BranchStmt * postvisit( const BranchStmt * );
    113         void previsit( const WhileDoStmt * );
    114         const WhileDoStmt * postvisit( const WhileDoStmt * );
    115         void previsit( const ForStmt * );
    116         const ForStmt * postvisit( const ForStmt * );
    117         const CaseStmt * previsit( const CaseStmt * );
    118         void previsit( const IfStmt * );
    119         const IfStmt * postvisit( const IfStmt * );
    120         void previsit( const SwitchStmt * );
    121         const SwitchStmt * postvisit( const SwitchStmt * );
    122         void previsit( const ReturnStmt * );
    123         void previsit( const TryStmt * );
    124         void postvisit( const TryStmt * );
    125         void previsit( const FinallyStmt * );
    126 
    127         const Stmt * mutateLoop( const Stmt * body, Entry& );
     109        void previsit( const ast::FunctionDecl * );
     110
     111        const ast::CompoundStmt * previsit( const ast::CompoundStmt * );
     112        const ast::BranchStmt * postvisit( const ast::BranchStmt * );
     113        void previsit( const ast::WhileStmt * );
     114        const ast::WhileStmt * postvisit( const ast::WhileStmt * );
     115        void previsit( const ast::ForStmt * );
     116        const ast::ForStmt * postvisit( const ast::ForStmt * );
     117        const ast::CaseStmt * previsit( const ast::CaseStmt * );
     118        void previsit( const ast::IfStmt * );
     119        const ast::IfStmt * postvisit( const ast::IfStmt * );
     120        void previsit( const ast::SwitchStmt * );
     121        const ast::SwitchStmt * postvisit( const ast::SwitchStmt * );
     122        void previsit( const ast::ReturnStmt * );
     123        void previsit( const ast::TryStmt * );
     124        void postvisit( const ast::TryStmt * );
     125        void previsit( const ast::FinallyStmt * );
     126
     127        const ast::Stmt * mutateLoop( const ast::Stmt * body, Entry& );
    128128
    129129        const LabelToStmt & target_table;
    130         set<Label> fallthrough_labels;
    131         vector<Entry> enclosing_control_structures;
    132         Label break_label;
     130        std::set<ast::Label> fallthrough_labels;
     131        std::vector<Entry> enclosing_control_structures;
     132        ast::Label break_label;
    133133        bool inFinally;
    134134
     
    138138        const LoopNode * posthandleLoopStmt( const LoopNode * loopStmt );
    139139
    140         list<ptr<Stmt>> fixBlock(
    141                 const list<ptr<Stmt>> & kids, bool caseClause );
     140        std::list<ast::ptr<ast::Stmt>> fixBlock(
     141                const std::list<ast::ptr<ast::Stmt>> & kids, bool caseClause );
    142142
    143143        template<typename UnaryPredicate>
    144144        auto findEnclosingControlStructure( UnaryPredicate pred ) {
    145                 return find_if( enclosing_control_structures.rbegin(),
    146                                                 enclosing_control_structures.rend(), pred );
     145                return std::find_if( enclosing_control_structures.rbegin(),
     146                        enclosing_control_structures.rend(), pred );
    147147        }
    148148};
    149149
    150 NullStmt * labelledNullStmt(
    151         const CodeLocation & cl, const Label & label ) {
    152         return new NullStmt( cl, vector<Label>{ label } );
     150ast::NullStmt * labelledNullStmt(
     151                const CodeLocation & cl, const ast::Label & label ) {
     152        return new ast::NullStmt( cl, std::vector<ast::Label>{ label } );
    153153}
    154154
     
    158158{}
    159159
    160 void MultiLevelExitCore::previsit( const FunctionDecl * ) {
     160void MultiLevelExitCore::previsit( const ast::FunctionDecl * ) {
    161161        visit_children = false;
    162162}
    163163
    164 const CompoundStmt * MultiLevelExitCore::previsit(
    165         const CompoundStmt * stmt ) {
     164const ast::CompoundStmt * MultiLevelExitCore::previsit(
     165                const ast::CompoundStmt * stmt ) {
    166166        visit_children = false;
    167 
    168         // if the stmt is labelled then generate a label to check in postvisit if the label is used
    169         bool isLabeled = ! stmt->labels.empty();
     167        bool isLabeled = !stmt->labels.empty();
    170168        if ( isLabeled ) {
    171                 Label breakLabel = newLabel( "blockBreak", stmt );
     169                ast::Label breakLabel = LabelGenerator::newLabel( "blockBreak", stmt );
    172170                enclosing_control_structures.emplace_back( stmt, breakLabel );
    173171                GuardAction( [this]() { enclosing_control_structures.pop_back(); } );
    174172        }
    175173
    176         auto mutStmt = mutate( stmt );
     174        auto mutStmt = ast::mutate( stmt );
    177175        // A child statement may set the break label.
    178         mutStmt->kids = move( fixBlock( stmt->kids, false ) );
     176        mutStmt->kids = std::move( fixBlock( stmt->kids, false ) );
    179177
    180178        if ( isLabeled ) {
    181                 assert( ! enclosing_control_structures.empty() );
     179                assert( !enclosing_control_structures.empty() );
    182180                Entry & entry = enclosing_control_structures.back();
    183                 if ( ! entry.useBreakExit().empty() ) {
     181                if ( !entry.useBreakExit().empty() ) {
    184182                        break_label = entry.useBreakExit();
    185183                }
     
    189187
    190188size_t getUnusedIndex(
    191         const Stmt * stmt, const Label & originalTarget ) {
     189                const ast::Stmt * stmt, const ast::Label & originalTarget ) {
    192190        const size_t size = stmt->labels.size();
    193191
    194         // If the label is empty, do not add unused attribute.
    195   if ( originalTarget.empty() ) return size;
     192        // If the label is empty, we can skip adding the unused attribute:
     193        if ( originalTarget.empty() ) return size;
    196194
    197195        // Search for a label that matches the originalTarget.
    198196        for ( size_t i = 0 ; i < size ; ++i ) {
    199                 const Label & label = stmt->labels[i];
     197                const ast::Label & label = stmt->labels[i];
    200198                if ( label == originalTarget ) {
    201                         for ( const Attribute * attr : label.attributes ) {
     199                        for ( const ast::Attribute * attr : label.attributes ) {
    202200                                if ( attr->name == "unused" ) return size;
    203201                        }
     
    205203                }
    206204        }
    207         assertf( false, "CFA internal error: could not find label '%s' on statement %s",
    208                          originalTarget.name.c_str(), toString( stmt ).c_str() );
    209 }
    210 
    211 const Stmt * addUnused(
    212         const Stmt * stmt, const Label & originalTarget ) {
     205        assertf( false, "Could not find label '%s' on statement %s",
     206                originalTarget.name.c_str(), toString( stmt ).c_str() );
     207}
     208
     209const ast::Stmt * addUnused(
     210                const ast::Stmt * stmt, const ast::Label & originalTarget ) {
    213211        size_t i = getUnusedIndex( stmt, originalTarget );
    214212        if ( i == stmt->labels.size() ) {
    215213                return stmt;
    216214        }
    217         Stmt * mutStmt = mutate( stmt );
    218         mutStmt->labels[i].attributes.push_back( new Attribute( "unused" ) );
     215        ast::Stmt * mutStmt = ast::mutate( stmt );
     216        mutStmt->labels[i].attributes.push_back( new ast::Attribute( "unused" ) );
    219217        return mutStmt;
    220218}
    221219
    222 // This routine updates targets on enclosing control structures to indicate which
    223 //     label is used by the BranchStmt that is passed
    224 const BranchStmt * MultiLevelExitCore::postvisit( const BranchStmt * stmt ) {
    225         vector<Entry>::reverse_iterator targetEntry =
     220const ast::BranchStmt * MultiLevelExitCore::postvisit( const ast::BranchStmt * stmt ) {
     221        std::vector<Entry>::reverse_iterator targetEntry =
    226222                enclosing_control_structures.rend();
    227 
    228         // Labels on different stmts require different approaches to access
    229223        switch ( stmt->kind ) {
    230           case BranchStmt::Goto:
     224        case ast::BranchStmt::Goto:
    231225                return stmt;
    232           case BranchStmt::Continue:
    233           case BranchStmt::Break: {
    234                   bool isContinue = stmt->kind == BranchStmt::Continue;
    235                   // Handle unlabeled break and continue.
    236                   if ( stmt->target.empty() ) {
    237                           if ( isContinue ) {
    238                                   targetEntry = findEnclosingControlStructure( isContinueTarget );
    239                           } else {
    240                                   if ( enclosing_control_structures.empty() ) {
    241                                           SemanticError( stmt->location,
    242                                                                          "'break' outside a loop, 'switch', or labelled block" );
    243                                   }
    244                                   targetEntry = findEnclosingControlStructure( isBreakTarget );
    245                           }
    246                           // Handle labeled break and continue.
    247                   } else {
    248                           // Lookup label in table to find attached control structure.
    249                           targetEntry = findEnclosingControlStructure(
    250                                   [ targetStmt = target_table.at(stmt->target) ](auto entry){
    251                                           return entry.stmt == targetStmt;
    252                                   } );
    253                   }
    254                   // Ensure that selected target is valid.
    255                   if ( targetEntry == enclosing_control_structures.rend() || ( isContinue && ! isContinueTarget( *targetEntry ) ) ) {
    256                           SemanticError( stmt->location, toString( (isContinue ? "'continue'" : "'break'"),
    257                                                         " target must be an enclosing ", (isContinue ? "loop: " : "control structure: "),
    258                                                         stmt->originalTarget ) );
    259                   }
    260                   break;
    261           }
    262           // handle fallthrough in case/switch stmts
    263           case BranchStmt::FallThrough: {
    264                   targetEntry = findEnclosingControlStructure( isFallthroughTarget );
    265                   // Check that target is valid.
    266                   if ( targetEntry == enclosing_control_structures.rend() ) {
    267                           SemanticError( stmt->location, "'fallthrough' must be enclosed in a 'switch' or 'choose'" );
    268                   }
    269                   if ( ! stmt->target.empty() ) {
    270                           // Labelled fallthrough: target must be a valid fallthough label.
    271                           if ( ! fallthrough_labels.count( stmt->target ) ) {
    272                                   SemanticError( stmt->location, toString( "'fallthrough' target must be a later case statement: ",
    273                                                                                                                    stmt->originalTarget ) );
    274                           }
    275                           return new BranchStmt( stmt->location, BranchStmt::Goto, stmt->originalTarget );
    276                   }
    277                   break;
    278           }
    279           case BranchStmt::FallThroughDefault: {
    280                   targetEntry = findEnclosingControlStructure( isFallthroughDefaultTarget );
    281 
    282                   // Check if in switch or choose statement.
    283                   if ( targetEntry == enclosing_control_structures.rend() ) {
    284                           SemanticError( stmt->location, "'fallthrough' must be enclosed in a 'switch' or 'choose'" );
    285                   }
    286 
    287                   // Check if switch or choose has default clause.
    288                   auto switchStmt = strict_dynamic_cast< const SwitchStmt * >( targetEntry->stmt );
    289                   bool foundDefault = false;
    290                   for ( auto subStmt : switchStmt->stmts ) {
    291                           const CaseStmt * caseStmt = subStmt.strict_as<CaseStmt>();
    292                           if ( caseStmt->isDefault() ) {
    293                                   foundDefault = true;
    294                                   break;
    295                           }
    296                   }
    297                   if ( ! foundDefault ) {
    298                           SemanticError( stmt->location, "'fallthrough default' must be enclosed in a 'switch' or 'choose'"
    299                                                          "control structure with a 'default' clause" );
    300                   }
    301                   break;
    302           }
    303           default:
     226        case ast::BranchStmt::Continue:
     227        case ast::BranchStmt::Break: {
     228                bool isContinue = stmt->kind == ast::BranchStmt::Continue;
     229                // Handle unlabeled break and continue.
     230                if ( stmt->target.empty() ) {
     231                        if ( isContinue ) {
     232                                targetEntry = findEnclosingControlStructure( isContinueTarget );
     233                        } else {
     234                                if ( enclosing_control_structures.empty() ) {
     235                                        SemanticError( stmt->location,
     236                                                "'break' outside a loop, 'switch', or labelled block" );
     237                                }
     238                                targetEntry = findEnclosingControlStructure( isBreakTarget );
     239                        }
     240                // Handle labeled break and continue.
     241                } else {
     242                        // Lookup label in table to find attached control structure.
     243                        targetEntry = findEnclosingControlStructure(
     244                                [ targetStmt = target_table.at(stmt->target) ](auto entry){
     245                                        return entry.stmt == targetStmt;
     246                                } );
     247                }
     248                // Ensure that selected target is valid.
     249                if ( targetEntry == enclosing_control_structures.rend() || ( isContinue && !isContinueTarget( *targetEntry ) ) ) {
     250                        SemanticError(
     251                                stmt->location,
     252                                toString( (isContinue ? "'continue'" : "'break'"),
     253                                        " target must be an enclosing ",
     254                                        (isContinue ? "loop: " : "control structure: "),
     255                                        stmt->originalTarget ) );
     256                }
     257                break;
     258        }
     259        case ast::BranchStmt::FallThrough: {
     260                targetEntry = findEnclosingControlStructure( isFallthroughTarget );
     261                // Check that target is valid.
     262                if ( targetEntry == enclosing_control_structures.rend() ) {
     263                        SemanticError( stmt->location, "'fallthrough' must be enclosed in a 'switch' or 'choose'" );
     264                }
     265                if ( !stmt->target.empty() ) {
     266                        // Labelled fallthrough: target must be a valid fallthough label.
     267                        if ( !fallthrough_labels.count( stmt->target ) ) {
     268                                SemanticError( stmt->location, toString( "'fallthrough' target must be a later case statement: ", stmt->originalTarget ) );
     269                        }
     270                        return new ast::BranchStmt(
     271                                stmt->location, ast::BranchStmt::Goto, stmt->originalTarget );
     272                }
     273                break;
     274        }
     275        case ast::BranchStmt::FallThroughDefault: {
     276                targetEntry = findEnclosingControlStructure( isFallthroughDefaultTarget );
     277
     278                // Check that this is in a switch or choose statement.
     279                if ( targetEntry == enclosing_control_structures.rend() ) {
     280                        SemanticError( stmt->location, "'fallthrough' must be enclosed in a 'switch' or 'choose'" );
     281                }
     282
     283                // Check that the switch or choose has a default clause.
     284                auto switchStmt = strict_dynamic_cast< const ast::SwitchStmt * >(
     285                        targetEntry->stmt );
     286                bool foundDefault = false;
     287                for ( auto subStmt : switchStmt->stmts ) {
     288                        const ast::CaseStmt * caseStmt = subStmt.strict_as<ast::CaseStmt>();
     289                        if ( caseStmt->isDefault() ) {
     290                                foundDefault = true;
     291                                break;
     292                        }
     293                }
     294                if ( !foundDefault ) {
     295                        SemanticError( stmt->location, "'fallthrough default' must be enclosed in a 'switch' or 'choose' control structure with a 'default' clause" );
     296                }
     297                break;
     298        }
     299        default:
    304300                assert( false );
    305301        }
    306302
    307         // Branch error checks: get the appropriate label name, which is always replaced.
    308         Label exitLabel( CodeLocation(), "" );
     303        // Branch error checks: get the appropriate label name:
     304        // (This label will always be replaced.)
     305        ast::Label exitLabel( CodeLocation(), "" );
    309306        switch ( stmt->kind ) {
    310           case BranchStmt::Break:
    311                 assert( ! targetEntry->useBreakExit().empty() );
     307        case ast::BranchStmt::Break:
     308                assert( !targetEntry->useBreakExit().empty() );
    312309                exitLabel = targetEntry->useBreakExit();
    313310                break;
    314           case BranchStmt::Continue:
    315                 assert( ! targetEntry->useContExit().empty() );
     311        case ast::BranchStmt::Continue:
     312                assert( !targetEntry->useContExit().empty() );
    316313                exitLabel = targetEntry->useContExit();
    317314                break;
    318           case BranchStmt::FallThrough:
    319                 assert( ! targetEntry->useFallExit().empty() );
     315        case ast::BranchStmt::FallThrough:
     316                assert( !targetEntry->useFallExit().empty() );
    320317                exitLabel = targetEntry->useFallExit();
    321318                break;
    322           case BranchStmt::FallThroughDefault:
    323                 assert( ! targetEntry->useFallDefaultExit().empty() );
     319        case ast::BranchStmt::FallThroughDefault:
     320                assert( !targetEntry->useFallDefaultExit().empty() );
    324321                exitLabel = targetEntry->useFallDefaultExit();
    325322                // Check that fallthrough default comes before the default clause.
    326                 if ( ! targetEntry->isFallDefaultValid() ) {
    327                         SemanticError( stmt->location, "'fallthrough default' must precede the 'default' clause" );
     323                if ( !targetEntry->isFallDefaultValid() ) {
     324                        SemanticError( stmt->location,
     325                                "'fallthrough default' must precede the 'default' clause" );
    328326                }
    329327                break;
    330           default:
     328        default:
    331329                assert(0);
    332330        }
     
    335333        targetEntry->stmt = addUnused( targetEntry->stmt, stmt->originalTarget );
    336334
    337         // Replace with goto to make later passes more uniform.
    338         return new BranchStmt( stmt->location, BranchStmt::Goto, exitLabel );
    339 }
    340 
    341 void MultiLevelExitCore::previsit( const WhileDoStmt * stmt ) {
     335        // Replace this with a goto to make later passes more uniform.
     336        return new ast::BranchStmt( stmt->location, ast::BranchStmt::Goto, exitLabel );
     337}
     338
     339void MultiLevelExitCore::previsit( const ast::WhileStmt * stmt ) {
    342340        return prehandleLoopStmt( stmt );
    343341}
    344342
    345 const WhileDoStmt * MultiLevelExitCore::postvisit( const WhileDoStmt * stmt ) {
     343const ast::WhileStmt * MultiLevelExitCore::postvisit( const ast::WhileStmt * stmt ) {
    346344        return posthandleLoopStmt( stmt );
    347345}
    348346
    349 void MultiLevelExitCore::previsit( const ForStmt * stmt ) {
     347void MultiLevelExitCore::previsit( const ast::ForStmt * stmt ) {
    350348        return prehandleLoopStmt( stmt );
    351349}
    352350
    353 const ForStmt * MultiLevelExitCore::postvisit( const ForStmt * stmt ) {
     351const ast::ForStmt * MultiLevelExitCore::postvisit( const ast::ForStmt * stmt ) {
    354352        return posthandleLoopStmt( stmt );
    355353}
     
    357355// Mimic what the built-in push_front would do anyways. It is O(n).
    358356void push_front(
    359         vector<ptr<Stmt>> & vec, const Stmt * element ) {
     357                std::vector<ast::ptr<ast::Stmt>> & vec, const ast::Stmt * element ) {
    360358        vec.emplace_back( nullptr );
    361359        for ( size_t i = vec.size() - 1 ; 0 < i ; --i ) {
    362                 vec[ i ] = move( vec[ i - 1 ] );
     360                vec[ i ] = std::move( vec[ i - 1 ] );
    363361        }
    364362        vec[ 0 ] = element;
    365363}
    366364
    367 const CaseStmt * MultiLevelExitCore::previsit( const CaseStmt * stmt ) {
     365const ast::CaseStmt * MultiLevelExitCore::previsit( const ast::CaseStmt * stmt ) {
    368366        visit_children = false;
    369367
    370         // If default, mark seen.
     368        // If it is the default, mark the default as seen.
    371369        if ( stmt->isDefault() ) {
    372                 assert( ! enclosing_control_structures.empty() );
     370                assert( !enclosing_control_structures.empty() );
    373371                enclosing_control_structures.back().seenDefault();
    374372        }
    375373
    376374        // The cond may not exist, but if it does update it now.
    377         visitor->maybe_accept( stmt, &CaseStmt::cond );
     375        visitor->maybe_accept( stmt, &ast::CaseStmt::cond );
    378376
    379377        // Just save the mutated node for simplicity.
    380         CaseStmt * mutStmt = mutate( stmt );
    381 
    382         Label fallLabel = newLabel( "fallThrough", stmt );
    383         if ( ! mutStmt->stmts.empty() ) {
     378        ast::CaseStmt * mutStmt = ast::mutate( stmt );
     379
     380        ast::Label fallLabel = LabelGenerator::newLabel( "fallThrough", stmt );
     381        if ( !mutStmt->stmts.empty() ) {
    384382                // Ensure that the stack isn't corrupted by exceptions in fixBlock.
    385383                auto guard = makeFuncGuard(
    386384                        [&](){ enclosing_control_structures.emplace_back( mutStmt, fallLabel ); },
    387385                        [this](){ enclosing_control_structures.pop_back(); }
    388                         );
     386                );
    389387
    390388                // These should already be in a block.
    391                 auto block = mutate( mutStmt->stmts.front().strict_as<CompoundStmt>() );
     389                auto block = ast::mutate( mutStmt->stmts.front().strict_as<ast::CompoundStmt>() );
    392390                block->kids = fixBlock( block->kids, true );
    393391
    394392                // Add fallthrough label if necessary.
    395                 assert( ! enclosing_control_structures.empty() );
     393                assert( !enclosing_control_structures.empty() );
    396394                Entry & entry = enclosing_control_structures.back();
    397395                if ( entry.isFallUsed() ) {
    398                         mutStmt->stmts.push_back( labelledNullStmt( mutStmt->location, entry.useFallExit() ) );
    399                 }
    400         }
    401         assert( ! enclosing_control_structures.empty() );
     396                        mutStmt->stmts.push_back(
     397                                labelledNullStmt( mutStmt->location, entry.useFallExit() ) );
     398                }
     399        }
     400        assert( !enclosing_control_structures.empty() );
    402401        Entry & entry = enclosing_control_structures.back();
    403         assertf( dynamic_cast< const SwitchStmt * >( entry.stmt ),
    404                          "CFA internal error: control structure enclosing a case clause must be a switch, but is: %s",
    405                          toString( entry.stmt ).c_str() );
     402        assertf( dynamic_cast< const ast::SwitchStmt * >( entry.stmt ),
     403                "Control structure enclosing a case clause must be a switch, but is: %s",
     404                toString( entry.stmt ).c_str() );
    406405        if ( mutStmt->isDefault() ) {
    407406                if ( entry.isFallDefaultUsed() ) {
    408407                        // Add fallthrough default label if necessary.
    409                         push_front( mutStmt->stmts, labelledNullStmt( stmt->location, entry.useFallDefaultExit() ) );
     408                        push_front( mutStmt->stmts, labelledNullStmt(
     409                                stmt->location, entry.useFallDefaultExit()
     410                        ) );
    410411                }
    411412        }
     
    413414}
    414415
    415 void MultiLevelExitCore::previsit( const IfStmt * stmt ) {
    416         bool labeledBlock = ! stmt->labels.empty();
     416void MultiLevelExitCore::previsit( const ast::IfStmt * stmt ) {
     417        bool labeledBlock = !stmt->labels.empty();
    417418        if ( labeledBlock ) {
    418                 Label breakLabel = newLabel( "blockBreak", stmt );
     419                ast::Label breakLabel = LabelGenerator::newLabel( "blockBreak", stmt );
    419420                enclosing_control_structures.emplace_back( stmt, breakLabel );
    420421                GuardAction( [this](){ enclosing_control_structures.pop_back(); } );
     
    422423}
    423424
    424 const IfStmt * MultiLevelExitCore::postvisit( const IfStmt * stmt ) {
    425         bool labeledBlock = ! stmt->labels.empty();
     425const ast::IfStmt * MultiLevelExitCore::postvisit( const ast::IfStmt * stmt ) {
     426        bool labeledBlock = !stmt->labels.empty();
    426427        if ( labeledBlock ) {
    427428                auto this_label = enclosing_control_structures.back().useBreakExit();
    428                 if ( ! this_label.empty() ) {
     429                if ( !this_label.empty() ) {
    429430                        break_label = this_label;
    430431                }
     
    433434}
    434435
    435 bool isDefaultCase( const ptr<Stmt> & stmt ) {
    436         const CaseStmt * caseStmt = stmt.strict_as<CaseStmt>();
     436bool isDefaultCase( const ast::ptr<ast::Stmt> & stmt ) {
     437        const ast::CaseStmt * caseStmt = stmt.strict_as<ast::CaseStmt>();
    437438        return caseStmt->isDefault();
    438439}
    439440
    440 void MultiLevelExitCore::previsit( const SwitchStmt * stmt ) {
    441         Label label = newLabel( "switchBreak", stmt );
    442         auto it = find_if( stmt->stmts.rbegin(), stmt->stmts.rend(), isDefaultCase );
    443 
    444         const CaseStmt * defaultCase = it != stmt->stmts.rend() ? (it)->strict_as<CaseStmt>() : nullptr;
    445         Label defaultLabel = defaultCase ? newLabel( "fallThroughDefault", defaultCase ) : Label( stmt->location, "" );
     441void MultiLevelExitCore::previsit( const ast::SwitchStmt * stmt ) {
     442        ast::Label label = LabelGenerator::newLabel( "switchBreak", stmt );
     443        auto it = std::find_if( stmt->stmts.rbegin(), stmt->stmts.rend(), isDefaultCase );
     444
     445        const ast::CaseStmt * defaultCase = it != stmt->stmts.rend()
     446                ? (it)->strict_as<ast::CaseStmt>() : nullptr;
     447        ast::Label defaultLabel = defaultCase
     448                ? LabelGenerator::newLabel( "fallThroughDefault", defaultCase )
     449                : ast::Label( stmt->location, "" );
    446450        enclosing_control_structures.emplace_back( stmt, label, defaultLabel );
    447451        GuardAction( [this]() { enclosing_control_structures.pop_back(); } );
    448452
    449         // Collect valid labels for fallthrough. It starts with all labels at this level, then remove as each is seen during
    450         // traversal.
    451         for ( const Stmt * stmt : stmt->stmts ) {
    452                 auto * caseStmt = strict_dynamic_cast< const CaseStmt * >( stmt );
     453        // Collect valid labels for fallthrough. It starts with all labels at
     454        // this level, then removed as we see them in traversal.
     455        for ( const ast::Stmt * stmt : stmt->stmts ) {
     456                auto * caseStmt = strict_dynamic_cast< const ast::CaseStmt * >( stmt );
    453457                if ( caseStmt->stmts.empty() ) continue;
    454                 auto block = caseStmt->stmts.front().strict_as<CompoundStmt>();
    455                 for ( const Stmt * stmt : block->kids ) {
    456                         for ( const Label & l : stmt->labels ) {
     458                auto block = caseStmt->stmts.front().strict_as<ast::CompoundStmt>();
     459                for ( const ast::Stmt * stmt : block->kids ) {
     460                        for ( const ast::Label & l : stmt->labels ) {
    457461                                fallthrough_labels.insert( l );
    458462                        }
     
    461465}
    462466
    463 const SwitchStmt * MultiLevelExitCore::postvisit( const SwitchStmt * stmt ) {
    464         assert( ! enclosing_control_structures.empty() );
     467const ast::SwitchStmt * MultiLevelExitCore::postvisit( const ast::SwitchStmt * stmt ) {
     468        assert( !enclosing_control_structures.empty() );
    465469        Entry & entry = enclosing_control_structures.back();
    466470        assert( entry.stmt == stmt );
    467471
    468         // Only run to generate the break label.
     472        // Only run if we need to generate the break label.
    469473        if ( entry.isBreakUsed() ) {
    470                 // To keep the switch statements uniform (all direct children of a SwitchStmt should be CastStmts), append the
    471                 // exit label and break to the last case, create a default case if no cases.
    472                 SwitchStmt * mutStmt = mutate( stmt );
     474                // To keep the switch statements uniform (all direct children of a
     475                // SwitchStmt should be CastStmts), append the exit label and break
     476                // to the last case, create a default case is there are no cases.
     477                ast::SwitchStmt * mutStmt = ast::mutate( stmt );
    473478                if ( mutStmt->stmts.empty() ) {
    474                         mutStmt->stmts.push_back( new CaseStmt( mutStmt->location, nullptr, {} ) );
    475                 }
    476 
    477                 auto caseStmt = mutStmt->stmts.back().strict_as<CaseStmt>();
    478                 auto mutCase = mutate( caseStmt );
     479                        mutStmt->stmts.push_back( new ast::CaseStmt(
     480                                mutStmt->location, nullptr, {} ));
     481                }
     482
     483                auto caseStmt = mutStmt->stmts.back().strict_as<ast::CaseStmt>();
     484                auto mutCase = ast::mutate( caseStmt );
    479485                mutStmt->stmts.back() = mutCase;
    480486
    481                 Label label( mutCase->location, "breakLabel" );
    482                 auto branch = new BranchStmt( mutCase->location, BranchStmt::Break, label );
     487                ast::Label label( mutCase->location, "breakLabel" );
     488                auto branch = new ast::BranchStmt( mutCase->location, ast::BranchStmt::Break, label );
    483489                branch->labels.push_back( entry.useBreakExit() );
    484490                mutCase->stmts.push_back( branch );
     
    489495}
    490496
    491 void MultiLevelExitCore::previsit( const ReturnStmt * stmt ) {
     497void MultiLevelExitCore::previsit( const ast::ReturnStmt * stmt ) {
    492498        if ( inFinally ) {
    493499                SemanticError( stmt->location, "'return' may not appear in a finally clause" );
     
    495501}
    496502
    497 void MultiLevelExitCore::previsit( const TryStmt * stmt ) {
    498         bool isLabeled = ! stmt->labels.empty();
     503void MultiLevelExitCore::previsit( const ast::TryStmt * stmt ) {
     504        bool isLabeled = !stmt->labels.empty();
    499505        if ( isLabeled ) {
    500                 Label breakLabel = newLabel( "blockBreak", stmt );
     506                ast::Label breakLabel = LabelGenerator::newLabel( "blockBreak", stmt );
    501507                enclosing_control_structures.emplace_back( stmt, breakLabel );
    502508                GuardAction([this](){ enclosing_control_structures.pop_back(); } );
     
    504510}
    505511
    506 void MultiLevelExitCore::postvisit( const TryStmt * stmt ) {
    507         bool isLabeled = ! stmt->labels.empty();
     512void MultiLevelExitCore::postvisit( const ast::TryStmt * stmt ) {
     513        bool isLabeled = !stmt->labels.empty();
    508514        if ( isLabeled ) {
    509515                auto this_label = enclosing_control_structures.back().useBreakExit();
    510                 if ( ! this_label.empty() ) {
     516                if ( !this_label.empty() ) {
    511517                        break_label = this_label;
    512518                }
     
    514520}
    515521
    516 void MultiLevelExitCore::previsit( const FinallyStmt * ) {
    517         GuardAction([this, old = move( enclosing_control_structures)](){ enclosing_control_structures = move(old); });
    518         enclosing_control_structures = vector<Entry>();
     522void MultiLevelExitCore::previsit( const ast::FinallyStmt * ) {
     523        GuardAction([this, old = std::move(enclosing_control_structures)](){
     524                enclosing_control_structures = std::move(old);
     525        });
     526        enclosing_control_structures = std::vector<Entry>();
    519527        GuardValue( inFinally ) = true;
    520528}
    521529
    522 const Stmt * MultiLevelExitCore::mutateLoop(
    523         const Stmt * body, Entry & entry ) {
     530const ast::Stmt * MultiLevelExitCore::mutateLoop(
     531                const ast::Stmt * body, Entry & entry ) {
    524532        if ( entry.isBreakUsed() ) {
    525533                break_label = entry.useBreakExit();
    526534        }
    527535
    528         // if continue is used insert a continue label into the back of the body of the loop
    529536        if ( entry.isContUsed() ) {
    530                 CompoundStmt * new_body = new CompoundStmt( body->location );
    531                 // {}
     537                ast::CompoundStmt * new_body = new ast::CompoundStmt( body->location );
    532538                new_body->kids.push_back( body );
    533                 // {
    534                 //  body
    535                 // }
    536539                new_body->kids.push_back(
    537540                        labelledNullStmt( body->location, entry.useContExit() ) );
    538                 // {
    539                 //  body
    540                 //  ContinueLabel: {}
    541                 // }
    542541                return new_body;
    543542        }
     
    550549        // Remember is loop before going onto mutate the body.
    551550        // The labels will be folded in if they are used.
    552         Label breakLabel = newLabel( "loopBreak", loopStmt );
    553         Label contLabel = newLabel( "loopContinue", loopStmt );
     551        ast::Label breakLabel = LabelGenerator::newLabel( "loopBreak", loopStmt );
     552        ast::Label contLabel = LabelGenerator::newLabel( "loopContinue", loopStmt );
    554553        enclosing_control_structures.emplace_back( loopStmt, breakLabel, contLabel );
    555         // labels are added temporarily to see if they are used and then added permanently in postvisit if ther are used
    556         // children will tag labels as being used during their traversal which occurs before postvisit
    557 
    558         // GuardAction calls the lambda after the node is done being visited
    559554        GuardAction( [this](){ enclosing_control_structures.pop_back(); } );
    560555}
     
    562557template<typename LoopNode>
    563558const LoopNode * MultiLevelExitCore::posthandleLoopStmt( const LoopNode * loopStmt ) {
    564         assert( ! enclosing_control_structures.empty() );
     559        assert( !enclosing_control_structures.empty() );
    565560        Entry & entry = enclosing_control_structures.back();
    566561        assert( entry.stmt == loopStmt );
    567562
    568         // Now check if the labels are used and add them if so.
    569         return mutate_field( loopStmt, &LoopNode::body, mutateLoop( loopStmt->body, entry ) );
    570         // this call to mutate_field compares loopStmt->body and the result of mutateLoop
    571         //              if they are the same the node isn't mutated, if they differ then the new mutated node is returned
    572         //              the stmts will only differ if a label is used
    573 }
    574 
    575 list<ptr<Stmt>> MultiLevelExitCore::fixBlock(
    576         const list<ptr<Stmt>> & kids, bool is_case_clause ) {
    577         // Unfortunately cannot use automatic error collection.
     563        // Now we check if the labels are used and add them if so.
     564        return ast::mutate_field(
     565                loopStmt, &LoopNode::body, mutateLoop( loopStmt->body, entry ) );
     566}
     567
     568std::list<ast::ptr<ast::Stmt>> MultiLevelExitCore::fixBlock(
     569                const std::list<ast::ptr<ast::Stmt>> & kids, bool is_case_clause ) {
     570        // Unfortunately we can't use the automatic error collection.
    578571        SemanticErrorException errors;
    579572
    580         list<ptr<Stmt>> ret;
     573        std::list<ast::ptr<ast::Stmt>> ret;
    581574
    582575        // Manually visit each child.
    583         for ( const ptr<Stmt> & kid : kids ) {
     576        for ( const ast::ptr<ast::Stmt> & kid : kids ) {
    584577                if ( is_case_clause ) {
    585578                        // Once a label is seen, it's no longer a valid for fallthrough.
    586                         for ( const Label & l : kid->labels ) {
     579                        for ( const ast::Label & l : kid->labels ) {
    587580                                fallthrough_labels.erase( l );
    588581                        }
     
    595588                }
    596589
    597                 if ( ! break_label.empty() ) {
    598                         ret.push_back( labelledNullStmt( ret.back()->location, break_label ) );
    599                         break_label = Label( CodeLocation(), "" );
    600                 }
    601         }
    602 
    603         if ( ! errors.isEmpty() ) {
     590                if ( !break_label.empty() ) {
     591                        ret.push_back(
     592                                labelledNullStmt( ret.back()->location, break_label ) );
     593                        break_label = ast::Label( CodeLocation(), "" );
     594                }
     595        }
     596
     597        if ( !errors.isEmpty() ) {
    604598                throw errors;
    605599        }
     
    607601}
    608602
    609 const CompoundStmt * multiLevelExitUpdate(
    610         const CompoundStmt * stmt,
    611         const LabelToStmt & labelTable ) {
     603} // namespace
     604
     605const ast::CompoundStmt * multiLevelExitUpdate(
     606        const ast::CompoundStmt * stmt,
     607                const LabelToStmt & labelTable ) {
    612608        // Must start in the body, so FunctionDecls can be a stopping point.
    613         Pass<MultiLevelExitCore> visitor( labelTable );
    614         const CompoundStmt * ret = stmt->accept( visitor );
     609        ast::Pass<MultiLevelExitCore> visitor( labelTable );
     610        const ast::CompoundStmt * ret = stmt->accept( visitor );
    615611        return ret;
    616612}
     613
    617614} // namespace ControlStruct
    618615
Note: See TracChangeset for help on using the changeset viewer.