src/compiler/SemanticAnalysis.h
author David Anderson <dvander@alliedmods.net>
Wed Dec 26 17:14:12 2012 -0800 (2012-12-26)
changeset 241 18f3010a358c
parent 236 072f1114ea5d
child 245 9371f058625a
permissions -rw-r--r--
Implement |const| keyword.
     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     void visitEnumStatement(EnumStatement *node);
    52 
    53     void visitCallExpression(CallExpression *node);
    54     void visitNameProxy(NameProxy *name);
    55     void visitIntegerLiteral(IntegerLiteral *node);
    56     void visitFloatLiteral(FloatLiteral *node);
    57     void visitVariableDeclaration(VariableDeclaration *node);
    58     void visitForStatement(ForStatement *node);
    59     void visitWhileStatement(WhileStatement *node);
    60     void visitAssignment(Assignment *node);
    61     void visitBinaryExpression(BinaryExpression *node);
    62     void visitBreakStatement(BreakStatement *node);
    63     void visitContinueStatement(ContinueStatement *node);
    64     void visitIfStatement(IfStatement *node);
    65     void visitIndexExpression(IndexExpression *node);
    66     void visitIncDecExpression(IncDecExpression *node);
    67     void visitStringLiteral(StringLiteral *node);
    68 #if 0
    69     void visitFunctionTypeStatement(FunctionTypeStatement *node);
    70     void visitImportStatement(ImportStatement *node);
    71     void visitStructureStatement(StructureStatement *node);
    72     void visitSwitchStatement(SwitchStatement *node);
    73 
    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_Decl,
    89         Coerce_Assign
    90     };
    91 
    92     // For a given control flow path, whether it returns.
    93     enum ReturnStatus
    94     {
    95         Returns_Never,
    96         Returns_Sometimes,
    97         Returns_Always
    98     };
    99 
   100     // For a given control flow path, whether it terminates,
   101     // and if it terminates, whether it returns.
   102     class ControlStatus
   103     {
   104         bool terminates_;
   105         ReturnStatus returns_;
   106 
   107       public:
   108         ControlStatus()
   109         {
   110         }
   111         ControlStatus(bool terminates, ReturnStatus returns)
   112           : terminates_(terminates),
   113             returns_(returns)
   114         {
   115         }
   116 
   117         bool terminates() const {
   118             return terminates_;
   119         }
   120         ReturnStatus returns() const {
   121             return returns_;
   122         }
   123     };
   124 
   125     class ControlScope
   126     {
   127         ReturnStatus returns_;
   128         ControlScope **prevp_;
   129         ControlScope *prev_;
   130         bool terminates_;
   131 
   132       public:
   133         ControlScope(ControlScope **prevp)
   134           : returns_(Returns_Never),
   135             prevp_(prevp),
   136             prev_(*prevp),
   137             terminates_(false)
   138         {
   139             *prevp_ = this;
   140         }
   141         ~ControlScope() {
   142             *prevp_ = prev_;
   143         }
   144         ControlStatus status() {
   145             return ControlStatus(terminates_, returns_);
   146         }
   147 
   148         void returns(ReturnStatus status) {
   149             // We allow multiple terminates, but only the first one takes
   150             // effect. For example, |break; continue;| is legal, but the
   151             // continue is unreachable.
   152             if (terminates_)
   153                 return;
   154             if (status > returns_)
   155                 returns_ = status;
   156         }
   157         void terminate(ReturnStatus status) {
   158             if (terminates_)
   159                 return;
   160             terminates_ = true;
   161             returns_ = status;
   162         }
   163         void merge(const ControlStatus &left, const ControlStatus &right);
   164         void inherit(const ControlStatus &other);
   165     };
   166 
   167 
   168     void requireLifoStack();
   169     ControlStatus visitForControl(Statement *statement);
   170     ControlStatus visitLoopBody(Statement *stmt);
   171     void visitForTest(Expression *expr,
   172                       BytecodeEmitter::Label *trueBranch,
   173                       BytecodeEmitter::Label *falseBranch,
   174                       BytecodeEmitter::Label *fallthrough);
   175     void set(VariableSymbol *sym);
   176     HIR *eval(Expression *expr);
   177     HIR *binary(AstNode *node, TokenKind token, HIR *left, HIR *right);
   178     HIR *coerce(HIR *from, Handle<Type> to, CoercionKind kind);
   179     Type *coercionType(TokenKind token, HIR *left, HIR *right);
   180     HLValue *lvalue(Expression *expr);
   181     void discharge(HIR *hir);
   182     HIR *typeFailure(const SourcePosition &pos, Handle<Type> from, Handle<Type> to);
   183 
   184     HIR *typeCheckArray(const SourcePosition &pos,
   185                         HIR *from,
   186                         Handle<ArrayType> argActual,
   187                         CoercionKind kind);
   188 
   189   private:
   190     // Used to target break/catch statements.
   191     class LoopScope
   192     {
   193         Scope *scope_;
   194         BytecodeEmitter::Label *bk_;
   195         BytecodeEmitter::Label *ct_;
   196         LoopScope **prevp_;
   197         LoopScope *prev_;
   198         bool usesLifoStack_;
   199         bool breaks_;
   200 
   201       public:
   202         LoopScope(Scope *scope, BytecodeEmitter::Label *bk, BytecodeEmitter::Label *ct,
   203                   LoopScope **prevp)
   204           : scope_(scope),
   205             bk_(bk),
   206             ct_(ct),
   207             prevp_(prevp),
   208             prev_(*prevp),
   209             usesLifoStack_(false),
   210             breaks_(false)
   211         {
   212             *prevp_ = this;
   213         }
   214 
   215         ~LoopScope()
   216         {
   217             *prevp_ = prev_;
   218         }
   219 
   220         BytecodeEmitter::Label *break_() {
   221             return bk_;
   222         }
   223         BytecodeEmitter::Label *continue_() {
   224             return ct_;
   225         }
   226         Scope *scope() {
   227             return scope_;
   228         }
   229         void setUsesLifoStack() {
   230             usesLifoStack_ = true;
   231         }
   232         bool usesLifoStack() const {
   233             return usesLifoStack_;
   234         }
   235         void setBreaks() {
   236             breaks_ = true;
   237         }
   238         bool breaks() const {
   239             return breaks_;
   240         }
   241     };
   242     
   243   private:
   244     Zone *zone_;
   245     PoolAllocator &pool_;
   246     CompileContext &cc_;
   247     TranslationUnit *unit_;
   248     HIR *hir_;
   249     Scope *scope_;
   250     BytecodeEmitter emitter_;
   251     ScopedRoot<Module> module_;
   252     ScopedRoot<FunctionType> fun_;
   253     LoopScope *loop_;
   254     ControlScope *control_;
   255 };
   256 
   257 } // namespace ke
   258 
   259 #endif // _include_sp2_sema_h_