IPStack - Firewall cleanups and speedups (now shoudl at least work)
[tpg/acess2.git] / Usermode / Libraries / libspiderscript.so_src / exec_ast.c
index 74d6383..5355838 100644 (file)
@@ -6,6 +6,9 @@
 #include <string.h>
 #include "ast.h"
 
+#define TRACE_VAR_LOOKUPS      0
+#define TRACE_NODE_RETURNS     0
+
 // === IMPORTS ===
 extern tSpiderFunction *gpExports_First;
 
@@ -21,16 +24,20 @@ void        SpiderScript_FreeValue(tSpiderValue *Value);
 char   *SpiderScript_DumpValue(tSpiderValue *Value);
 
 tSpiderValue   *AST_ExecuteNode(tAST_BlockState *Block, tAST_Node *Node);
-tSpiderValue   *AST_ExecuteNode_BinOp(tAST_BlockState *Block, int Operation, tSpiderValue *Left, tSpiderValue *Right);
-tSpiderValue   *AST_ExecuteNode_UniOp(tAST_BlockState *Block, int Operation, tSpiderValue *Value);
+tSpiderValue   *AST_ExecuteNode_BinOp(tAST_BlockState *Block, tAST_Node *Node, int Operation, tSpiderValue *Left, tSpiderValue *Right);
+tSpiderValue   *AST_ExecuteNode_UniOp(tAST_BlockState *Block, tAST_Node *Node, int Operation, tSpiderValue *Value);
 
-tAST_Variable *Variable_Define(tAST_BlockState *Block, int Type, const char *Name);
- int   Variable_SetValue(tAST_BlockState *Block, const char *Name, tSpiderValue *Value);
-tSpiderValue   *Variable_GetValue(tAST_BlockState *Block, const char *Name);
+tAST_Variable *Variable_Define(tAST_BlockState *Block, int Type, const char *Name, tSpiderValue *Value);
+ int   Variable_SetValue(tAST_BlockState *Block, tAST_Node *VarNode, tSpiderValue *Value);
+tSpiderValue   *Variable_GetValue(tAST_BlockState *Block, tAST_Node *VarNode);
 void   Variable_Destroy(tAST_Variable *Variable);
 
+void   AST_RuntimeMessage(tAST_Node *Node, const char *Type, const char *Format, ...);
 void   AST_RuntimeError(tAST_Node *Node, const char *Format, ...);
 
+// === GLOBALS ===
+ int   giNextBlockIdent = 1;
+
 // === CODE ===
 /**
  * \brief Dereference a created object
@@ -124,7 +131,7 @@ tSpiderValue *SpiderScript_CreateString(int Length, const char *Data)
 /**
  * \brief Concatenate two strings
  */
-tSpiderValue *Object_StringConcat(tSpiderValue *Str1, tSpiderValue *Str2)
+tSpiderValue *Object_StringConcat(const tSpiderValue *Str1, const tSpiderValue *Str2)
 {
         int    newLen = 0;
        tSpiderValue    *ret;
@@ -389,6 +396,7 @@ char *SpiderScript_DumpValue(tSpiderValue *Value)
 /**
  * \brief Execute a script function
  * \param Script       Script context to execute in
+ * \param Namespace    Namespace to search for the function
  * \param Function     Function name to execute
  * \param NArguments   Number of arguments to pass
  * \param Arguments    Arguments passed
@@ -397,7 +405,6 @@ tSpiderValue *SpiderScript_ExecuteFunction(tSpiderScript *Script,
        tSpiderNamespace *Namespace, const char *Function,
        int NArguments, tSpiderValue **Arguments)
 {
-       char    *trueName = NULL;
         int    bFound = 0;     // Used to keep nesting levels down
        tSpiderValue    *ret = ERRPTR;
        tSpiderFunction *fcn;
@@ -424,20 +431,25 @@ tSpiderValue *SpiderScript_ExecuteFunction(tSpiderScript *Script,
                        bs.BaseNamespace = &Script->Variant->RootNamespace;
                        bs.CurNamespace = NULL;
                        bs.Script = Script;
+                       bs.Ident = giNextBlockIdent ++;
                        
                        // Parse arguments
                        for( arg = astFcn->Arguments; arg; arg = arg->NextSibling, i++ )
                        {
-                               // TODO: Type checks
-                               Variable_Define(&bs, arg->DefVar.DataType, arg->DefVar.Name);
                                if( i >= NArguments )   break;  // TODO: Return gracefully
-                               Variable_SetValue(&bs, arg->DefVar.Name, Arguments[i]);
+                               // TODO: Type checks
+                               Variable_Define(&bs,
+                                       arg->DefVar.DataType, arg->DefVar.Name,
+                                       Arguments[i]);
                        }
                        
                        // Execute function
                        ret = AST_ExecuteNode(&bs, astFcn->Code);
-                       Object_Dereference(ret);        // Dereference output of last block statement
-                       ret = bs.RetVal;        // Set to return value of block
+                       if(ret != ERRPTR)
+                       {
+                               Object_Dereference(ret);        // Dereference output of last block statement
+                               ret = bs.RetVal;        // Set to return value of block
+                       }
                        bFound = 1;
                        
                        while(bs.FirstVar)
@@ -496,7 +508,8 @@ tSpiderValue *SpiderScript_ExecuteFunction(tSpiderScript *Script,
        // Not found?
        if(!bFound)
        {
-               fprintf(stderr, "Undefined reference to '%s'\n", trueName);
+               fprintf(stderr, "Undefined reference to function '%s' (ns='%s')\n",
+                       Function, Namespace->Name);
                return ERRPTR;
        }
        
@@ -506,12 +519,13 @@ tSpiderValue *SpiderScript_ExecuteFunction(tSpiderScript *Script,
 /**
  * \brief Execute an object method function
  * \param Script       Script context to execute in
- * \param Function     Function name to execute
+ * \param Object       Object in which to find the method
+ * \param MethodName   Name of method to call
  * \param NArguments   Number of arguments to pass
  * \param Arguments    Arguments passed
  */
-tSpiderValue *SpiderScript_ExecuteMethod(tSpiderScript *Script, tSpiderObject *Object,
-       const char *MethodName,
+tSpiderValue *SpiderScript_ExecuteMethod(tSpiderScript *Script,
+       tSpiderObject *Object, const char *MethodName,
        int NArguments, tSpiderValue **Arguments)
 {
        tSpiderFunction *fcn;
@@ -519,12 +533,15 @@ tSpiderValue *SpiderScript_ExecuteMethod(tSpiderScript *Script, tSpiderObject *O
        tSpiderValue    *newargs[NArguments+1];
         int    i;
        
+       // TODO: Support program defined objects
+       
+       // Search for the function
        for( fcn = Object->Type->Methods; fcn; fcn = fcn->Next )
        {
                if( strcmp(fcn->Name, MethodName) == 0 )
                        break;
        }
-       
+       // Error
        if( !fcn )
        {
                AST_RuntimeError(NULL, "Class '%s' does not have a method '%s'",
@@ -532,19 +549,20 @@ tSpiderValue *SpiderScript_ExecuteMethod(tSpiderScript *Script, tSpiderObject *O
                return ERRPTR;
        }
        
+       // Create the "this" argument
        this.Type = SS_DATATYPE_OBJECT;
        this.ReferenceCount = 1;
        this.Object = Object;
-       
        newargs[0] = &this;
        memcpy(&newargs[1], Arguments, NArguments*sizeof(tSpiderValue*));
        
-       // TODO: Type Checking
+       // Check the type of the arguments
        for( i = 0; fcn->ArgTypes[i]; i ++ )
        {
                if( i >= NArguments ) {
-                       AST_RuntimeError(NULL, "Argument count mismatch (%i passed)",
-                               NArguments);
+                       for( ; fcn->ArgTypes[i]; i ++ ) ;
+                       AST_RuntimeError(NULL, "Argument count mismatch (%i passed, %i expected)",
+                               NArguments, i);
                        return ERRPTR;
                }
                if( Arguments[i] && Arguments[i]->Type != fcn->ArgTypes[i] )
@@ -555,6 +573,7 @@ tSpiderValue *SpiderScript_ExecuteMethod(tSpiderScript *Script, tSpiderObject *O
                }
        }
        
+       // Call handler
        return fcn->Handler(Script, NArguments+1, newargs);
 }
 
@@ -574,7 +593,7 @@ tSpiderValue *SpiderScript_CreateObject(tSpiderScript *Script,
        tSpiderObjectDef        *class;
        
        // First: Find the function in the script
-       // TODO: Implement scripted classes
+       // TODO: Implement script-defined classes
        #if 0
        {
                tAST_Function   *astClass;
@@ -597,20 +616,24 @@ tSpiderValue *SpiderScript_CreateObject(tSpiderScript *Script,
                        bs.BaseNamespace = &Script->Variant->RootNamespace;
                        bs.CurNamespace = NULL;
                        bs.Script = Script;
-                       
+                       bs.Ident = giNextBlockIdent ++;
                        
                        for( arg = astFcn->Arguments; arg; arg = arg->NextSibling, i++ )
                        {
-                               // TODO: Type checks
-                               Variable_Define(&bs, arg->DefVar.DataType, arg->DefVar.Name);
                                if( i >= NArguments )   break;  // TODO: Return gracefully
-                               Variable_SetValue(&bs, arg->DefVar.Name, Arguments[i]);
+                               // TODO: Type checks
+                               Variable_Define(&bs,
+                                       arg->DefVar.DataType, arg->DefVar.Name,
+                                       Arguments[i]);
                        }
                        
                        // Execute function
                        ret = AST_ExecuteNode(&bs, astFcn->Code);
-                       Object_Dereference(ret);        // Dereference output of last block statement
-                       ret = bs.RetVal;        // Set to return value of block
+                       if( ret != ERRPTR )
+                       {
+                               Object_Dereference(ret);        // Dereference output of last block statement
+                               ret = bs.RetVal;        // Set to return value of block
+                       }
                        bFound = 1;
                        
                        while(bs.FirstVar)
@@ -628,6 +651,9 @@ tSpiderValue *SpiderScript_CreateObject(tSpiderScript *Script,
        {
                class = NULL;   // Just to allow the below code to be neat
                
+               //if( !Namespace )
+               //      Namespace = &Script->Variant->RootNamespace;
+               
                // Second: Scan current namespace
                if( !class && Namespace )
                {
@@ -667,10 +693,13 @@ tSpiderValue *SpiderScript_CreateObject(tSpiderScript *Script,
                {
                        tSpiderObject   *obj;
                        // TODO: Type Checking
+                       
+                       // Call constructor
                        obj = class->Constructor( NArguments, Arguments );
                        if( obj == NULL || obj == ERRPTR )
                                return (void *)obj;
                        
+                       // Creatue return object
                        ret = malloc( sizeof(tSpiderValue) );
                        ret->Type = SS_DATATYPE_OBJECT;
                        ret->ReferenceCount = 1;
@@ -682,7 +711,7 @@ tSpiderValue *SpiderScript_CreateObject(tSpiderScript *Script,
        // Not found?
        if(!bFound)
        {
-               fprintf(stderr, "Undefined reference to '%s'\n", ClassName);
+               fprintf(stderr, "Undefined reference to class '%s'\n", ClassName);
                return ERRPTR;
        }
        
@@ -692,6 +721,8 @@ tSpiderValue *SpiderScript_CreateObject(tSpiderScript *Script,
 
 /**
  * \brief Execute an AST node and return its value
+ * \param Block        Execution context
+ * \param Node Node to execute
  */
 tSpiderValue *AST_ExecuteNode(tAST_BlockState *Block, tAST_Node *Node)
 {
@@ -704,7 +735,9 @@ tSpiderValue *AST_ExecuteNode(tAST_BlockState *Block, tAST_Node *Node)
        switch(Node->Type)
        {
        // No Operation
-       case NODETYPE_NOP:      ret = NULL;     break;
+       case NODETYPE_NOP:
+               ret = NULL;
+               break;
        
        // Code block
        case NODETYPE_BLOCK:
@@ -716,14 +749,17 @@ tSpiderValue *AST_ExecuteNode(tAST_BlockState *Block, tAST_Node *Node)
                        blockInfo.RetVal = NULL;
                        blockInfo.BaseNamespace = Block->BaseNamespace;
                        blockInfo.CurNamespace = NULL;
+                       blockInfo.BreakTarget = NULL;
+                       blockInfo.Ident = giNextBlockIdent ++;
                        ret = NULL;
-                       for(node = Node->Block.FirstChild; node && !blockInfo.RetVal; node = node->NextSibling )
+                       // Loop over all nodes, or until the return value is set
+                       for(node = Node->Block.FirstChild;
+                               node && !blockInfo.RetVal && !blockInfo.BreakTarget;
+                               node = node->NextSibling )
                        {
                                ret = AST_ExecuteNode(&blockInfo, node);
-                               if(ret == ERRPTR) {     // Error check
-                                       break ;
-                               }
-                               if(ret) Object_Dereference(ret);        // Free unused value
+                               if(ret == ERRPTR)       break;  // Error check
+                               if(ret != NULL) Object_Dereference(ret);        // Free unused value
                        }
                        // Clean up variables
                        while(blockInfo.FirstVar)
@@ -732,65 +768,81 @@ tSpiderValue *AST_ExecuteNode(tAST_BlockState *Block, tAST_Node *Node)
                                Variable_Destroy( blockInfo.FirstVar );
                                blockInfo.FirstVar = nextVar;
                        }
-                       if(ret != ERRPTR)
-                               ret = NULL;
+                       // Clear ret if not an error
+                       if(ret != ERRPTR)       ret = NULL;
+                       
+                       // Set parent's return value if needed
                        if( blockInfo.RetVal )
                                Block->RetVal = blockInfo.RetVal;
+                       if( blockInfo.BreakTarget ) {
+                               Block->BreakTarget = blockInfo.BreakTarget;
+                               Block->BreakType = blockInfo.BreakType;
+                       }
+                       
+                       // TODO: Unset break if break type deontes a block break
                }
                
                break;
        
        // Assignment
        case NODETYPE_ASSIGN:
+               // TODO: Support assigning to object attributes
                if( Node->Assign.Dest->Type != NODETYPE_VARIABLE ) {
                        AST_RuntimeError(Node, "LVALUE of assignment is not a variable");
                        return ERRPTR;
                }
                ret = AST_ExecuteNode(Block, Node->Assign.Value);
-               if(ret == ERRPTR)
-                       return ERRPTR;
+               if(ret == ERRPTR)       return ERRPTR;
                
+               // Perform assignment operation
                if( Node->Assign.Operation != NODETYPE_NOP )
                {
-                       tSpiderValue    *varVal = Variable_GetValue(Block, Node->Assign.Dest->Variable.Name);
+                       tSpiderValue    *varVal = Variable_GetValue(Block, Node->Assign.Dest);
                        tSpiderValue    *value;
-                       value = AST_ExecuteNode_BinOp(Block, Node->Assign.Operation, varVal, ret);
-                       if( value == ERRPTR )
-                               return ERRPTR;
+                       value = AST_ExecuteNode_BinOp(Block, Node, Node->Assign.Operation, varVal, ret);
+                       if(value == ERRPTR)     return ERRPTR;
                        if(ret) Object_Dereference(ret);
                        if(varVal)      Object_Dereference(varVal);
                        ret = value;
                }
                
-               if( Variable_SetValue( Block, Node->Assign.Dest->Variable.Name, ret ) ) {
+               // Set the variable value
+               if( Variable_SetValue( Block, Node->Assign.Dest, ret ) ) {
                        Object_Dereference( ret );
                        return ERRPTR;
                }
                break;
        
+       // Post increment/decrement
        case NODETYPE_POSTINC:
        case NODETYPE_POSTDEC:
                {
-                       tSpiderValue    *varVal, *value, *one;
+                       tSpiderValue    *varVal, *value;
+                       static tSpiderValue     one = {
+                               .Type = SS_DATATYPE_INTEGER,
+                               .ReferenceCount = 1,
+                               {.Integer = 1}
+                               };
+                       
+                       // TODO: Support assigning to object attributes
                        if( Node->UniOp.Value->Type != NODETYPE_VARIABLE ) {
                                AST_RuntimeError(Node, "LVALUE of assignment is not a variable");
                                return ERRPTR;
                        }
                
-                       varVal = Variable_GetValue(Block, Node->Assign.Dest->Variable.Name);
-                       one = SpiderScript_CreateInteger(1);
+                       // Get values (current variable contents and a static one)
+                       varVal = Variable_GetValue(Block, Node->UniOp.Value);
                        
                        if( Node->Type == NODETYPE_POSTDEC )
-                               value = AST_ExecuteNode_BinOp(Block, NODETYPE_SUBTRACT, varVal, one);
+                               value = AST_ExecuteNode_BinOp(Block, Node, NODETYPE_SUBTRACT, varVal, &one);
                        else
-                               value = AST_ExecuteNode_BinOp(Block, NODETYPE_ADD, varVal, one);
+                               value = AST_ExecuteNode_BinOp(Block, Node, NODETYPE_ADD, varVal, &one);
                        if( value == ERRPTR )
                                return ERRPTR;
-                       Object_Dereference(one);        // Free constant one
                        
                        ret = varVal;
                
-                       if( Variable_SetValue( Block, Node->Assign.Dest->Variable.Name, value ) ) {
+                       if( Variable_SetValue( Block, Node->UniOp.Value, value ) ) {
                                Object_Dereference( ret );
                                return ERRPTR;
                        }
@@ -804,6 +856,7 @@ tSpiderValue *AST_ExecuteNode(tAST_BlockState *Block, tAST_Node *Node)
        case NODETYPE_CREATEOBJECT:
                // Logical block (used to allocate `params`)
                {
+                       tSpiderNamespace        *ns = Block->CurNamespace;
                        tSpiderValue    *params[Node->FunctionCall.NumArgs];
                        i = 0;
                        for(node = Node->FunctionCall.FirstArg; node; node = node->NextSibling)
@@ -817,14 +870,13 @@ tSpiderValue *AST_ExecuteNode(tAST_BlockState *Block, tAST_Node *Node)
                                i ++;
                        }
                        
-                       if( !Block->CurNamespace )
-                               Block->CurNamespace = Block->BaseNamespace;
+                       if( !ns )       ns = Block->BaseNamespace;
                        
                        // Call the function
                        if( Node->Type == NODETYPE_CREATEOBJECT )
                        {
                                ret = SpiderScript_CreateObject(Block->Script,
-                                       Block->CurNamespace,
+                                       ns,
                                        Node->FunctionCall.Name,
                                        Node->FunctionCall.NumArgs, params
                                        );
@@ -832,7 +884,7 @@ tSpiderValue *AST_ExecuteNode(tAST_BlockState *Block, tAST_Node *Node)
                        else if( Node->Type == NODETYPE_METHODCALL )
                        {
                                tSpiderValue *obj = AST_ExecuteNode(Block, Node->FunctionCall.Object);
-                               if( !obj || obj->Type != SS_DATATYPE_OBJECT ) {
+                               if( !obj || obj == ERRPTR || obj->Type != SS_DATATYPE_OBJECT ) {
                                        AST_RuntimeError(Node->FunctionCall.Object,
                                                "Type Mismatch - Required SS_DATATYPE_OBJECT for method call");
                                        while(i--)      Object_Dereference(params[i]);
@@ -848,7 +900,7 @@ tSpiderValue *AST_ExecuteNode(tAST_BlockState *Block, tAST_Node *Node)
                        else
                        {
                                ret = SpiderScript_ExecuteFunction(Block->Script,
-                                       Block->CurNamespace, Node->FunctionCall.Name,
+                                       ns, Node->FunctionCall.Name,
                                        Node->FunctionCall.NumArgs, params
                                        );
                        }
@@ -864,42 +916,74 @@ tSpiderValue *AST_ExecuteNode(tAST_BlockState *Block, tAST_Node *Node)
        // Conditional
        case NODETYPE_IF:
                ret = AST_ExecuteNode(Block, Node->If.Condition);
+               if( ret == ERRPTR )     break;
                if( SpiderScript_IsValueTrue(ret) ) {
-                       Object_Dereference(AST_ExecuteNode(Block, Node->If.True));
+                       tmpobj = AST_ExecuteNode(Block, Node->If.True);
                }
                else {
-                       Object_Dereference(AST_ExecuteNode(Block, Node->If.False));
+                       tmpobj = AST_ExecuteNode(Block, Node->If.False);
                }
                Object_Dereference(ret);
+               if( tmpobj == ERRPTR )  return ERRPTR;
+               Object_Dereference(tmpobj);
                ret = NULL;
                break;
        
        // Loop
        case NODETYPE_LOOP:
+               // Initialise
                ret = AST_ExecuteNode(Block, Node->For.Init);
-               if( Node->For.bCheckAfter )
+               if(ret == ERRPTR)       break;
+               
+               // Check initial condition
+               if( !Node->For.bCheckAfter )
                {
-                       do {
-                               Object_Dereference(ret);
-                               ret = AST_ExecuteNode(Block, Node->For.Code);
-                               Object_Dereference(ret);
-                               ret = AST_ExecuteNode(Block, Node->For.Increment);
+                       Object_Dereference(ret);
+               
+                       ret = AST_ExecuteNode(Block, Node->For.Condition);
+                       if(ret == ERRPTR)       return ERRPTR;
+                       if(!SpiderScript_IsValueTrue(ret)) {
                                Object_Dereference(ret);
-                               ret = AST_ExecuteNode(Block, Node->For.Condition);
-                       } while( SpiderScript_IsValueTrue(ret) );
+                               ret = NULL;
+                               break;
+                       }
                }
-               else
+       
+               // Perform loop
+               for( ;; )
                {
                        Object_Dereference(ret);
-                       ret = AST_ExecuteNode(Block, Node->For.Condition);
-                       while( SpiderScript_IsValueTrue(ret) ) {
-                               Object_Dereference(ret);
-                               ret = AST_ExecuteNode(Block, Node->For.Code);
-                               Object_Dereference(ret);
-                               ret = AST_ExecuteNode(Block, Node->For.Increment);
-                               Object_Dereference(ret);
-                               ret = AST_ExecuteNode(Block, Node->For.Condition);
+                       
+                       // Code
+                       ret = AST_ExecuteNode(Block, Node->For.Code);
+                       if(ret == ERRPTR)       return ERRPTR;
+                       Object_Dereference(ret);
+                       
+                       if(Block->BreakTarget)
+                       {
+                               if( Block->BreakTarget[0] == '\0' || strcmp(Block->BreakTarget, Node->For.Tag) == 0 )
+                               {
+                                       // Ours
+                                       free((void*)Block->BreakTarget);        Block->BreakTarget = NULL;
+                                       if( Block->BreakType == NODETYPE_CONTINUE ) {
+                                               // Continue, just keep going
+                                       }
+                                       else
+                                               break;
+                               }
+                               else
+                                       break;  // Break out of this loop
                        }
+                       
+                       // Increment
+                       ret = AST_ExecuteNode(Block, Node->For.Increment);
+                       if(ret == ERRPTR)       return ERRPTR;
+                       Object_Dereference(ret);
+                       
+                       // Check condition
+                       ret = AST_ExecuteNode(Block, Node->For.Condition);
+                       if(ret == ERRPTR)       return ERRPTR;
+                       if(!SpiderScript_IsValueTrue(ret))      break;
                }
                Object_Dereference(ret);
                ret = NULL;
@@ -908,15 +992,30 @@ tSpiderValue *AST_ExecuteNode(tAST_BlockState *Block, tAST_Node *Node)
        // Return
        case NODETYPE_RETURN:
                ret = AST_ExecuteNode(Block, Node->UniOp.Value);
+               if(ret == ERRPTR)       break;
                Block->RetVal = ret;    // Return value set
                ret = NULL;     // the `return` statement does not return a value
                break;
        
+       case NODETYPE_BREAK:
+       case NODETYPE_CONTINUE:
+               Block->BreakTarget = strdup(Node->Variable.Name);
+               Block->BreakType = Node->Type;
+               break;
+       
        // Define a variable
        case NODETYPE_DEFVAR:
+               if( Node->DefVar.InitialValue ) {
+                       tmpobj = AST_ExecuteNode(Block, Node->DefVar.InitialValue);
+                       if(tmpobj == ERRPTR)    return ERRPTR;
+               }
+               else {
+                       tmpobj = NULL;
+               }
                ret = NULL;
-               if( Variable_Define(Block, Node->DefVar.DataType, Node->DefVar.Name) == ERRPTR )
+               if( Variable_Define(Block, Node->DefVar.DataType, Node->DefVar.Name, tmpobj) == ERRPTR )
                        ret = ERRPTR;
+               Object_Dereference(tmpobj);
                break;
        
        // Scope
@@ -955,13 +1054,14 @@ tSpiderValue *AST_ExecuteNode(tAST_BlockState *Block, tAST_Node *Node)
        
        // Variable
        case NODETYPE_VARIABLE:
-               ret = Variable_GetValue( Block, Node->Variable.Name );
+               ret = Variable_GetValue( Block, Node );
                break;
        
        // Element of an Object
        case NODETYPE_ELEMENT:
                tmpobj = AST_ExecuteNode( Block, Node->Scope.Element );
-               if( tmpobj->Type != SS_DATATYPE_OBJECT )
+               if(tmpobj == ERRPTR)    return ERRPTR;
+               if( !tmpobj || tmpobj->Type != SS_DATATYPE_OBJECT )
                {
                        AST_RuntimeError(Node->Scope.Element, "Unable to dereference a non-object");
                        ret = ERRPTR;
@@ -989,6 +1089,7 @@ tSpiderValue *AST_ExecuteNode(tAST_BlockState *Block, tAST_Node *Node)
        case NODETYPE_CAST:
                {
                tmpobj = AST_ExecuteNode(Block, Node->Cast.Value);
+               if(tmpobj == ERRPTR) return ERRPTR;
                ret = SpiderScript_CastValueTo( Node->Cast.DataType, tmpobj );
                Object_Dereference(tmpobj);
                }
@@ -997,9 +1098,14 @@ tSpiderValue *AST_ExecuteNode(tAST_BlockState *Block, tAST_Node *Node)
        // Index into an array
        case NODETYPE_INDEX:
                op1 = AST_ExecuteNode(Block, Node->BinOp.Left); // Array
+               if(op1 == ERRPTR)       return ERRPTR;
                op2 = AST_ExecuteNode(Block, Node->BinOp.Right);        // Offset
+               if(op2 == ERRPTR) {
+                       Object_Dereference(op1);
+                       return ERRPTR;
+               }
                
-               if( op1->Type != SS_DATATYPE_ARRAY )
+               if( !op1 || op1->Type != SS_DATATYPE_ARRAY )
                {
                        // TODO: Implement "operator []" on objects
                        AST_RuntimeError(Node, "Indexing non-array");
@@ -1007,13 +1113,13 @@ tSpiderValue *AST_ExecuteNode(tAST_BlockState *Block, tAST_Node *Node)
                        break;
                }
                
-               if( op2->Type != SS_DATATYPE_INTEGER && !Block->Script->Variant->bImplicitCasts ) {
+               if( (!op2 || op2->Type != SS_DATATYPE_INTEGER) && !Block->Script->Variant->bImplicitCasts ) {
                        AST_RuntimeError(Node, "Array index is not an integer");
                        ret = ERRPTR;
                        break;
                }
                
-               if( op2->Type != SS_DATATYPE_INTEGER )
+               if( !op2 || op2->Type != SS_DATATYPE_INTEGER )
                {
                        tmpobj = SpiderScript_CastValueTo(SS_DATATYPE_INTEGER, op2);
                        Object_Dereference(op2);
@@ -1042,9 +1148,12 @@ tSpiderValue *AST_ExecuteNode(tAST_BlockState *Block, tAST_Node *Node)
                break;
        
        // Constant Values
-       case NODETYPE_STRING:   ret = SpiderScript_CreateString( Node->String.Length, Node->String.Data );      break;
-       case NODETYPE_INTEGER:  ret = SpiderScript_CreateInteger( Node->Integer );      break;
-       case NODETYPE_REAL:     ret = SpiderScript_CreateReal( Node->Real );    break;
+       case NODETYPE_STRING:
+       case NODETYPE_INTEGER:
+       case NODETYPE_REAL:
+               ret = &Node->Constant;
+               Object_Reference(ret);
+               break;
        
        // --- Operations ---
        // Boolean Operations
@@ -1100,7 +1209,7 @@ tSpiderValue *AST_ExecuteNode(tAST_BlockState *Block, tAST_Node *Node)
                }
                
                if( !op1 || !op2 ) {
-                       AST_RuntimeError(Node, "NULL Comparison (%p and %p)\n", op1, op2);
+                       AST_RuntimeError(Node, "NULL Comparison (%p and %p)", op1, op2);
                        if(op1) Object_Dereference(op1);
                        if(op2) Object_Dereference(op2);
                        ret = SpiderScript_CreateInteger( !op1 && !op2 );
@@ -1110,7 +1219,7 @@ tSpiderValue *AST_ExecuteNode(tAST_BlockState *Block, tAST_Node *Node)
                // Convert types
                if( op1->Type != op2->Type ) {
                        // If dynamically typed, convert op2 to op1's type
-                       if(Block->Script->Variant->bDyamicTyped)
+                       if(Block->Script->Variant->bImplicitCasts)
                        {
                                tmpobj = op2;
                                op2 = SpiderScript_CastValueTo(op1->Type, op2);
@@ -1122,7 +1231,8 @@ tSpiderValue *AST_ExecuteNode(tAST_BlockState *Block, tAST_Node *Node)
                        }
                        // If statically typed, this should never happen, but catch it anyway
                        else {
-                               AST_RuntimeError(Node, "Statically typed implicit cast");
+                               AST_RuntimeError(Node, "Statically typed implicit cast %i <op> %i",
+                                       op1->Type, op2->Type);
                                ret = ERRPTR;
                                break;
                        }
@@ -1195,7 +1305,7 @@ tSpiderValue *AST_ExecuteNode(tAST_BlockState *Block, tAST_Node *Node)
        case NODETYPE_NEGATE:   // Negation (-)
                op1 = AST_ExecuteNode(Block, Node->UniOp.Value);
                if(op1 == ERRPTR)       return ERRPTR;
-               ret = AST_ExecuteNode_UniOp(Block, Node->Type, op1);
+               ret = AST_ExecuteNode_UniOp(Block, Node, Node->Type, op1);
                Object_Dereference(op1);
                break;
        
@@ -1220,7 +1330,7 @@ tSpiderValue *AST_ExecuteNode(tAST_BlockState *Block, tAST_Node *Node)
                        return ERRPTR;
                }
                
-               ret = AST_ExecuteNode_BinOp(Block, Node->Type, op1, op2);
+               ret = AST_ExecuteNode_BinOp(Block, Node, Node->Type, op1, op2);
                
                // Free intermediate objects
                Object_Dereference(op1);
@@ -1229,14 +1339,27 @@ tSpiderValue *AST_ExecuteNode(tAST_BlockState *Block, tAST_Node *Node)
        
        //default:
        //      ret = NULL;
-       //      AST_RuntimeError(Node, "BUG - SpiderScript AST_ExecuteNode Unimplemented %i\n", Node->Type);
+       //      AST_RuntimeError(Node, "BUG - SpiderScript AST_ExecuteNode Unimplemented %i", Node->Type);
        //      break;
        }
 _return:
+       // Reset namespace when no longer needed
+       if( Node->Type != NODETYPE_SCOPE )
+               Block->CurNamespace = NULL;
+
+       #if TRACE_NODE_RETURNS
+       if(ret && ret != ERRPTR) {
+               AST_RuntimeError(Node, "Ret type of %p %i is %i", Node, Node->Type, ret->Type);
+       }
+       else {
+               AST_RuntimeError(Node, "Ret type of %p %i is %p", Node, Node->Type, ret);
+       }
+       #endif
+
        return ret;
 }
 
-tSpiderValue *AST_ExecuteNode_UniOp(tAST_BlockState *Block, int Operation, tSpiderValue *Value)
+tSpiderValue *AST_ExecuteNode_UniOp(tAST_BlockState *Block, tAST_Node *Node, int Operation, tSpiderValue *Value)
 {
        tSpiderValue    *ret;
        #if 0
@@ -1268,7 +1391,7 @@ tSpiderValue *AST_ExecuteNode_UniOp(tAST_BlockState *Block, int Operation, tSpid
                case NODETYPE_NEGATE:   ret = SpiderScript_CreateInteger( -Value->Integer );    break;
                case NODETYPE_BWNOT:    ret = SpiderScript_CreateInteger( ~Value->Integer );    break;
                default:
-                       AST_RuntimeError(NULL, "SpiderScript internal error: Exec,UniOP,Integer unknown op %i", Operation);
+                       AST_RuntimeError(Node, "SpiderScript internal error: Exec,UniOP,Integer unknown op %i", Operation);
                        ret = ERRPTR;
                        break;
                }
@@ -1279,7 +1402,7 @@ tSpiderValue *AST_ExecuteNode_UniOp(tAST_BlockState *Block, int Operation, tSpid
                {
                case NODETYPE_NEGATE:   ret = SpiderScript_CreateInteger( -Value->Real );       break;
                default:
-                       AST_RuntimeError(NULL, "SpiderScript internal error: Exec,UniOP,Real unknown op %i", Operation);
+                       AST_RuntimeError(Node, "SpiderScript internal error: Exec,UniOP,Real unknown op %i", Operation);
                        ret = ERRPTR;
                        break;
                }
@@ -1294,7 +1417,7 @@ tSpiderValue *AST_ExecuteNode_UniOp(tAST_BlockState *Block, int Operation, tSpid
        return ret;
 }
 
-tSpiderValue *AST_ExecuteNode_BinOp(tAST_BlockState *Block, int Operation, tSpiderValue *Left, tSpiderValue *Right)
+tSpiderValue *AST_ExecuteNode_BinOp(tAST_BlockState *Block, tAST_Node *Node, int Operation, tSpiderValue *Left, tSpiderValue *Right)
 {
        tSpiderValue    *preCastValue = Right;
        tSpiderValue    *ret;
@@ -1343,7 +1466,7 @@ tSpiderValue *AST_ExecuteNode_BinOp(tAST_BlockState *Block, int Operation, tSpid
                }
                // If statically typed, this should never happen, but catch it anyway
                else {
-                       AST_RuntimeError(NULL, "Implicit cast not allowed (from %i to %i)\n", Right->Type, Left->Type);
+                       AST_RuntimeError(Node, "Implicit cast not allowed (from %i to %i)", Right->Type, Left->Type);
                        return ERRPTR;
                }
        }
@@ -1365,7 +1488,7 @@ tSpiderValue *AST_ExecuteNode_BinOp(tAST_BlockState *Block, int Operation, tSpid
                        ret = Object_StringConcat(Left, Right);
                        break;
                default:
-                       AST_RuntimeError(NULL, "SpiderScript internal error: Exec,BinOP,String unknown op %i", Operation);
+                       AST_RuntimeError(Node, "SpiderScript internal error: Exec,BinOP,String unknown op %i", Operation);
                        ret = ERRPTR;
                        break;
                }
@@ -1388,7 +1511,7 @@ tSpiderValue *AST_ExecuteNode_BinOp(tAST_BlockState *Block, int Operation, tSpid
                        ret = SpiderScript_CreateInteger( (Left->Integer << Right->Integer) | (Left->Integer >> (64-Right->Integer)) );
                        break;
                default:
-                       AST_RuntimeError(NULL, "SpiderScript internal error: Exec,BinOP,Integer unknown op %i\n", Operation);
+                       AST_RuntimeError(Node, "SpiderScript internal error: Exec,BinOP,Integer unknown op %i", Operation);
                        ret = ERRPTR;
                        break;
                }
@@ -1403,14 +1526,14 @@ tSpiderValue *AST_ExecuteNode_BinOp(tAST_BlockState *Block, int Operation, tSpid
                case NODETYPE_MULTIPLY: ret = SpiderScript_CreateReal( Left->Real * Right->Real );      break;
                case NODETYPE_DIVIDE:   ret = SpiderScript_CreateReal( Left->Real / Right->Real );      break;
                default:
-                       AST_RuntimeError(NULL, "SpiderScript internal error: Exec,BinOP,Real unknown op %i", Operation);
+                       AST_RuntimeError(Node, "SpiderScript internal error: Exec,BinOP,Real unknown op %i", Operation);
                        ret = ERRPTR;
                        break;
                }
                break;
        
        default:
-               AST_RuntimeError(NULL, "BUG - Invalid operation (%i) on type (%i)", Operation, Left->Type);
+               AST_RuntimeError(Node, "BUG - Invalid operation (%i) on type (%i)", Operation, Left->Type);
                ret = ERRPTR;
                break;
        }
@@ -1427,7 +1550,7 @@ tSpiderValue *AST_ExecuteNode_BinOp(tAST_BlockState *Block, int Operation, tSpid
  * \param Name Name of the variable
  * \return Boolean Failure
  */
-tAST_Variable *Variable_Define(tAST_BlockState *Block, int Type, const char *Name)
+tAST_Variable *Variable_Define(tAST_BlockState *Block, int Type, const char *Name, tSpiderValue *Value)
 {
        tAST_Variable   *var, *prev = NULL;
        
@@ -1442,7 +1565,8 @@ tAST_Variable *Variable_Define(tAST_BlockState *Block, int Type, const char *Nam
        var = malloc( sizeof(tAST_Variable) + strlen(Name) + 1 );
        var->Next = NULL;
        var->Type = Type;
-       var->Object = NULL;
+       var->Object = Value;
+       if(Value)       Object_Reference(Value);
        strcpy(var->Name, Name);
        
        if(prev)        prev->Next = var;
@@ -1453,74 +1577,97 @@ tAST_Variable *Variable_Define(tAST_BlockState *Block, int Type, const char *Nam
        return var;
 }
 
-/**
- * \brief Set the value of a variable
- * \return Boolean Failure
- */
-int Variable_SetValue(tAST_BlockState *Block, const char *Name, tSpiderValue *Value)
-{
-       tAST_Variable   *var;
-       tAST_BlockState *bs;
-       
-       for( bs = Block; bs; bs = bs->Parent )
+tAST_Variable *Variable_Lookup(tAST_BlockState *Block, tAST_Node *VarNode, int CreateType)
+{      
+       tAST_Variable   *var = NULL;
+       
+       // Speed hack
+       if( VarNode->BlockState == Block && VarNode->BlockIdent == Block->Ident ) {
+               var = VarNode->ValueCache;
+               #if TRACE_VAR_LOOKUPS
+               AST_RuntimeMessage(VarNode, "debug", "Fast var fetch on '%s' %p (%p:%i)",
+                       VarNode->Variable.Name, var,
+                       VarNode->BlockState, VarNode->BlockIdent
+                       );
+               #endif
+       }
+       else
        {
-               for( var = bs->FirstVar; var; var = var->Next )
+               tAST_BlockState *bs;
+               for( bs = Block; bs; bs = bs->Parent )
                {
-                       if( strcmp(var->Name, Name) == 0 )
+                       for( var = bs->FirstVar; var; var = var->Next )
                        {
-                               if( !Block->Script->Variant->bDyamicTyped
-                                && (Value && var->Type != Value->Type) )
-                               {
-                                       AST_RuntimeError(NULL, "Type mismatch assigning to '%s'", Name);
-                                       return -2;
-                               }
-//                             printf("Assign %p to '%s'\n", Value, var->Name);
-                               Object_Reference(Value);
-                               Object_Dereference(var->Object);
-                               var->Object = Value;
-                               return 0;
+                               if( strcmp(var->Name, VarNode->Variable.Name) == 0 )
+                                       break;
                        }
+                       if(var) break;
                }
+               
+               if( !var )
+               {
+                       if( Block->Script->Variant->bDyamicTyped && CreateType != SS_DATATYPE_UNDEF ) {
+                               // Define variable
+                               var = Variable_Define(Block, CreateType, VarNode->Variable.Name, NULL);
+                       }
+                       else
+                       {
+                               AST_RuntimeError(VarNode, "Variable '%s' is undefined", VarNode->Variable.Name);
+                               return NULL;
+                       }
+               }
+               
+               #if TRACE_VAR_LOOKUPS
+               AST_RuntimeMessage(VarNode, "debug", "Saved variable lookup of '%s' %p (%p:%i)",
+                       VarNode->Variable.Name, var,
+                       Block, Block->Ident);
+               #endif
+               
+               VarNode->ValueCache = var;
+               VarNode->BlockState = Block;
+               VarNode->BlockIdent = Block->Ident;
        }
        
-       if( Block->Script->Variant->bDyamicTyped )
-       {
-               // Define variable
-               var = Variable_Define(Block, Value->Type, Name);
-               Object_Reference(Value);
-               var->Object = Value;
-               return 0;
-       }
-       else
-       {
-               AST_RuntimeError(NULL, "Variable '%s' set while undefined", Name);
-               return -1;
-       }
+       return var;
 }
 
 /**
- * \brief Get the value of a variable
+ * \brief Set the value of a variable
+ * \return Boolean Failure
  */
-tSpiderValue *Variable_GetValue(tAST_BlockState *Block, const char *Name)
+int Variable_SetValue(tAST_BlockState *Block, tAST_Node *VarNode, tSpiderValue *Value)
 {
        tAST_Variable   *var;
-       tAST_BlockState *bs;
        
-       for( bs = Block; bs; bs = bs->Parent )
+       var = Variable_Lookup(Block, VarNode, (Value ? Value->Type : SS_DATATYPE_UNDEF));
+       
+       if( !var )      return -1;
+       
+       if( !Block->Script->Variant->bDyamicTyped && (Value && var->Type != Value->Type) )
        {
-               for( var = bs->FirstVar; var; var = var->Next )
-               {
-                       if( strcmp(var->Name, Name) == 0 ) {
-                               Object_Reference(var->Object);
-                               return var->Object;
-                       }
-               }
+               AST_RuntimeError(VarNode, "Type mismatch assigning to '%s'",
+                       VarNode->Variable.Name);
+               return -2;
        }
+
+//     printf("Assign %p to '%s'\n", Value, var->Name);
+       Object_Reference(Value);
+       Object_Dereference(var->Object);
+       var->Object = Value;
+       return 0;
+}
+
+/**
+ * \brief Get the value of a variable
+ */
+tSpiderValue *Variable_GetValue(tAST_BlockState *Block, tAST_Node *VarNode)
+{
+       tAST_Variable   *var = Variable_Lookup(Block, VarNode, 0);
        
+       if( !var )      return ERRPTR;
        
-       AST_RuntimeError(NULL, "Variable '%s' used undefined", Name);
-       
-       return ERRPTR;
+       Object_Reference(var->Object);
+       return var->Object;
 }
 
 /**
@@ -1533,18 +1680,29 @@ void Variable_Destroy(tAST_Variable *Variable)
        free(Variable);
 }
 
-void AST_RuntimeError(tAST_Node *Node, const char *Format, ...)
+void AST_RuntimeMessage(tAST_Node *Node, const char *Type, const char *Format, ...)
 {
        va_list args;
        
-       fprintf(stderr, "ERROR: ");
+       if(Node) {
+               fprintf(stderr, "%s:%i: ", Node->File, Node->Line);
+       }
+       fprintf(stderr, "%s: ", Type);
        va_start(args, Format);
        vfprintf(stderr, Format, args);
        va_end(args);
        fprintf(stderr, "\n");
+}
+void AST_RuntimeError(tAST_Node *Node, const char *Format, ...)
+{
+       va_list args;
        
-       if(Node)
-       {
-               fprintf(stderr, "   at %s:%i\n", Node->File, Node->Line);
+       if(Node) {
+               fprintf(stderr, "%s:%i: ", Node->File, Node->Line);
        }
+       fprintf(stderr, "error: ");
+       va_start(args, Format);
+       vfprintf(stderr, Format, args);
+       va_end(args);
+       fprintf(stderr, "\n");
 }

UCC git Repository :: git.ucc.asn.au