src/compiler/SemanticAnalysis.h
author David Anderson <dvander@alliedmods.net>
Sat Dec 22 19:48:43 2012 -0800 (2012-12-22)
changeset 232 2b8512340180
parent 230 fb3cd08bc7fb
child 233 bbb498ccb4ac
permissions -rw-r--r--
Re-introduce definite return analysis.
     1 /*
     2  * Copyright (C) 2012 David Anderson
     3  *
     4  * This file is part of SourcePawn.
     5  *
     6  * SourcePawn is free software: you can redistribute it and/or modify it under
     7  * the terms of the GNU General Public License as published by the Free
     8  * Software Foundation, either version 3 of the License, or (at your option)
     9  * any later version.
    10  * 
    11  * SourcePawn is distributed in the hope that it will be useful, but WITHOUT ANY
    12  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
    13  * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
    14  *
    15  * You should have received a copy of the GNU General Public License along with
    16  * SourcePawn. If not, see http://www.gnu.org/licenses/.
    17  */
    18 #ifndef _include_sp2_sema_h_
    19 #define _include_sp2_sema_h_
    20 
    21 #include "AST.h"
    22 #include "HIR.h"
    23 #include "Scopes.h"
    24 #include "BytecodeEmitter.h"
    25 
    26 namespace ke {
    27 
    28 // Semantic analysis occurs after all names and types have been bound. It
    29 // performs the important task of validating the semantics and type safety
    30 // of a parse tree.
    31 // 
    32 // The semantic analysis phase also produces bytecode. This occurs on a
    33 // statement-by-statement basis. The result of analyzing an expression is a
    34 // tree of operations which is then flattened.
    35 class SemanticAnalysis : public AstVisitor
    36 {
    37   public:
    38     SemanticAnalysis(Zone *zone, CompileContext &cc, TranslationUnit *unit);
    39 
    40     void analyze();
    41 
    42   private:
    43     SemanticAnalysis(SemanticAnalysis *parent, Handle<FunctionType> fun);
    44     Function *compile(FunctionStatement *stmt);
    45 
    46   public:
    47     void visitFunctionStatement(FunctionStatement *node);
    48     void visitBlockStatement(BlockStatement *node);
    49     void visitExpressionStatement(ExpressionStatement *node);
    50     void visitReturnStatement(ReturnStatement *node);
    51 
    52     void visitCallExpression(CallExpression *node);
    53     void visitNameProxy(NameProxy *name);
    54     void visitIntegerLiteral(IntegerLiteral *node);
    55     void visitFloatLiteral(FloatLiteral *node);
    56     void visitVariableDeclaration(VariableDeclaration *node);
    57     void visitForStatement(ForStatement *node);
    58     void visitWhileStatement(WhileStatement *node);
    59     void visitAssignment(Assignment *node);
    60     void visitBinaryExpression(BinaryExpression *node);
    61     void visitBreakStatement(BreakStatement *node);
    62     void visitContinueStatement(ContinueStatement *node);
    63     void visitIfStatement(IfStatement *node);
    64     void visitIndexExpression(IndexExpression *node);
    65     void visitIncDecExpression(IncDecExpression *node);
    66 #if 0
    67     void visitFunctionTypeStatement(FunctionTypeStatement *node);
    68     void visitImportStatement(ImportStatement *node);
    69     void visitEnumStatement(EnumStatement *node);
    70     void visitStructureStatement(StructureStatement *node);
    71     void visitSwitchStatement(SwitchStatement *node);
    72 
    73     void visitStringLiteral(StringLiteral *node);
    74     void visitUnaryExpression(UnaryExpression *node);
    75     void visitTernaryExpression(TernaryExpression *node);
    76     void visitBooleanLiteral(BooleanLiteral *node);
    77     void visitFieldExpression(FieldExpression *node);
    78     void visitArrayLiteral(ArrayLiteral *node);
    79 #endif
    80 
    81   private:
    82     bool checkArgumentCount(Handle<FunctionType> type, unsigned actual);
    83 
    84   private:
    85     enum CoercionKind {
    86         Coerce_Arg,
    87         Coerce_Return,
    88         Coerce_Assign
    89     };
    90 
    91     // For a given control flow path, whether it returns.
    92     enum ReturnStatus
    93     {
    94         Returns_Never,
    95         Returns_Sometimes,
    96         Returns_Always
    97     };
    98 
    99     // For a given control flow path, whether it terminates,
   100     // and if it terminates, whether it returns.
   101     class ControlStatus
   102     {
   103         bool terminates_;
   104         ReturnStatus returns_;
   105 
   106       public:
   107         ControlStatus()
   108         {
   109         }
   110         ControlStatus(bool terminates, ReturnStatus returns)
   111           : terminates_(terminates),
   112             returns_(returns)
   113         {
   114         }
   115 
   116         bool terminates() const {
   117             return terminates_;
   118         }
   119         ReturnStatus returns() const {
   120             return returns_;
   121         }
   122     };
   123 
   124     class ControlScope
   125     {
   126         ReturnStatus returns_;
   127         ControlScope **prevp_;
   128         ControlScope *prev_;
   129         bool terminates_;
   130 
   131       public:
   132         ControlScope(ControlScope **prevp)
   133           : returns_(Returns_Never),
   134             prevp_(prevp),
   135             prev_(*prevp),
   136             terminates_(false)
   137         {
   138             *prevp_ = this;
   139         }
   140         ~ControlScope() {
   141             *prevp_ = prev_;
   142         }
   143         ControlStatus status() {
   144             return ControlStatus(terminates_, returns_);
   145         }
   146 
   147         void returns(ReturnStatus status) {
   148             // We allow multiple terminates, but only the first one takes
   149             // effect. For example, |break; continue;| is legal, but the
   150             // continue is unreachable.
   151             if (terminates_)
   152                 return;
   153             if (status > returns_)
   154                 returns_ = status;
   155         }
   156         void terminate(ReturnStatus status) {
   157             if (terminates_)
   158                 return;
   159             terminates_ = true;
   160             returns_ = status;
   161         }
   162         void merge(const ControlStatus &left, const ControlStatus &right);
   163         void inherit(const ControlStatus &other);
   164     };
   165 
   166 
   167     void requireLifoStack();
   168     ControlStatus visitForControl(Statement *statement);
   169     ControlStatus visitLoopBody(Statement *stmt);
   170     void visitForTest(Expression *expr,
   171                       BytecodeEmitter::Label *trueBranch,
   172                       BytecodeEmitter::Label *falseBranch,
   173                       BytecodeEmitter::Label *fallthrough);
   174     void set(VariableSymbol *sym);
   175     HIR *eval(Expression *expr);
   176     HIR *binary(AstNode *node, TokenKind token, HIR *left, HIR *right);
   177     HIR *coerce(HIR *from, Handle<Type> to, CoercionKind kind);
   178     Type *coercionType(TokenKind token, HIR *left, HIR *right);
   179     HLValue *lvalue(Expression *expr);
   180     void discharge(HIR *hir);
   181 
   182     bool typeCheckArray(const SourcePosition &pos,
   183                         Handle<Type> argGiven,
   184                         Handle<Type> argActual,
   185                         CoercionKind kind);
   186 
   187   private:
   188     // Used to target break/catch statements.
   189     class LoopScope
   190     {
   191         Scope *scope_;
   192         BytecodeEmitter::Label *bk_;
   193         BytecodeEmitter::Label *ct_;
   194         LoopScope **prevp_;
   195         LoopScope *prev_;
   196         bool usesLifoStack_;
   197         bool breaks_;
   198 
   199       public:
   200         LoopScope(Scope *scope, BytecodeEmitter::Label *bk, BytecodeEmitter::Label *ct,
   201                   LoopScope **prevp)
   202           : scope_(scope),
   203             bk_(bk),
   204             ct_(ct),
   205             prevp_(prevp),
   206             prev_(*prevp),
   207             usesLifoStack_(false),
   208             breaks_(false)
   209         {
   210             *prevp_ = this;
   211         }
   212 
   213         ~LoopScope()
   214         {
   215             *prevp_ = prev_;
   216         }
   217 
   218         BytecodeEmitter::Label *break_() {
   219             return bk_;
   220         }
   221         BytecodeEmitter::Label *continue_() {
   222             return ct_;
   223         }
   224         Scope *scope() {
   225             return scope_;
   226         }
   227         void setUsesLifoStack() {
   228             usesLifoStack_ = true;
   229         }
   230         bool usesLifoStack() const {
   231             return usesLifoStack_;
   232         }
   233         void setBreaks() {
   234             breaks_ = true;
   235         }
   236         bool breaks() const {
   237             return breaks_;
   238         }
   239     };
   240     
   241   private:
   242     Zone *zone_;
   243     PoolAllocator &pool_;
   244     CompileContext &cc_;
   245     TranslationUnit *unit_;
   246     HIR *hir_;
   247     Scope *scope_;
   248     BytecodeEmitter emitter_;
   249     ScopedRoot<Module> module_;
   250     ScopedRoot<FunctionType> fun_;
   251     LoopScope *loop_;
   252     ControlScope *control_;
   253 };
   254 
   255 } // namespace ke
   256 
   257 #endif // _include_sp2_sema_h_