9 #define TRACE_VAR_LOOKUPS 0
10 #define TRACE_NODE_RETURNS 0
13 extern tSpiderFunction *gpExports_First;
16 void Object_Dereference(tSpiderValue *Object);
17 void Object_Reference(tSpiderValue *Object);
18 tSpiderValue *SpiderScript_CreateInteger(uint64_t Value);
19 tSpiderValue *SpiderScript_CreateReal(double Value);
20 tSpiderValue *SpiderScript_CreateString(int Length, const char *Data);
21 tSpiderValue *SpiderScript_CastValueTo(int Type, tSpiderValue *Source);
22 int SpiderScript_IsValueTrue(tSpiderValue *Value);
23 void SpiderScript_FreeValue(tSpiderValue *Value);
24 char *SpiderScript_DumpValue(tSpiderValue *Value);
26 tSpiderValue *AST_ExecuteNode(tAST_BlockState *Block, tAST_Node *Node);
27 tSpiderValue *AST_ExecuteNode_BinOp(tAST_BlockState *Block, tAST_Node *Node, int Operation, tSpiderValue *Left, tSpiderValue *Right);
28 tSpiderValue *AST_ExecuteNode_UniOp(tAST_BlockState *Block, tAST_Node *Node, int Operation, tSpiderValue *Value);
30 tAST_Variable *Variable_Define(tAST_BlockState *Block, int Type, const char *Name, tSpiderValue *Value);
31 int Variable_SetValue(tAST_BlockState *Block, tAST_Node *VarNode, tSpiderValue *Value);
32 tSpiderValue *Variable_GetValue(tAST_BlockState *Block, tAST_Node *VarNode);
33 void Variable_Destroy(tAST_Variable *Variable);
35 void AST_RuntimeMessage(tAST_Node *Node, const char *Type, const char *Format, ...);
36 void AST_RuntimeError(tAST_Node *Node, const char *Format, ...);
39 int giNextBlockIdent = 1;
43 * \brief Dereference a created object
45 void Object_Dereference(tSpiderValue *Object)
48 if(Object == ERRPTR) return ;
49 Object->ReferenceCount --;
50 // printf("%p Dereferenced (%i)\n", Object, Object->ReferenceCount);
51 if( Object->ReferenceCount == 0 ) {
52 switch( (enum eSpiderScript_DataTypes) Object->Type )
54 case SS_DATATYPE_OBJECT:
55 Object->Object->Type->Destructor( Object->Object );
57 case SS_DATATYPE_OPAQUE:
58 Object->Opaque.Destroy( Object->Opaque.Data );
67 void Object_Reference(tSpiderValue *Object)
70 Object->ReferenceCount ++;
71 // printf("%p Referenced (%i)\n", Object, Object->ReferenceCount);
75 * \brief Allocate and initialise a SpiderScript object
77 tSpiderObject *SpiderScript_AllocateObject(tSpiderObjectDef *Class, int ExtraBytes)
79 int size = sizeof(tSpiderObject) + Class->NAttributes * sizeof(tSpiderValue*) + ExtraBytes;
80 tSpiderObject *ret = malloc(size);
83 ret->ReferenceCount = 1;
84 ret->OpaqueData = &ret->Attributes[ Class->NAttributes ];
85 memset( ret->Attributes, 0, Class->NAttributes * sizeof(tSpiderValue*) );
91 * \brief Create an integer object
93 tSpiderValue *SpiderScript_CreateInteger(uint64_t Value)
95 tSpiderValue *ret = malloc( sizeof(tSpiderValue) );
96 ret->Type = SS_DATATYPE_INTEGER;
97 ret->ReferenceCount = 1;
103 * \brief Create an real number object
105 tSpiderValue *SpiderScript_CreateReal(double Value)
107 tSpiderValue *ret = malloc( sizeof(tSpiderValue) );
108 ret->Type = SS_DATATYPE_REAL;
109 ret->ReferenceCount = 1;
115 * \brief Create an string object
117 tSpiderValue *SpiderScript_CreateString(int Length, const char *Data)
119 tSpiderValue *ret = malloc( sizeof(tSpiderValue) + Length + 1 );
120 ret->Type = SS_DATATYPE_STRING;
121 ret->ReferenceCount = 1;
122 ret->String.Length = Length;
124 memcpy(ret->String.Data, Data, Length);
126 memset(ret->String.Data, 0, Length);
127 ret->String.Data[Length] = '\0';
132 * \brief Concatenate two strings
134 tSpiderValue *Object_StringConcat(const tSpiderValue *Str1, const tSpiderValue *Str2)
138 if(Str1) newLen += Str1->String.Length;
139 if(Str2) newLen += Str2->String.Length;
140 ret = malloc( sizeof(tSpiderValue) + newLen + 1 );
141 ret->Type = SS_DATATYPE_STRING;
142 ret->ReferenceCount = 1;
143 ret->String.Length = newLen;
145 memcpy(ret->String.Data, Str1->String.Data, Str1->String.Length);
148 memcpy(ret->String.Data+Str1->String.Length, Str2->String.Data, Str2->String.Length);
150 memcpy(ret->String.Data, Str2->String.Data, Str2->String.Length);
152 ret->String.Data[ newLen ] = '\0';
157 * \brief Cast one object to another
158 * \brief Type Destination type
159 * \brief Source Input data
161 tSpiderValue *SpiderScript_CastValueTo(int Type, tSpiderValue *Source)
163 tSpiderValue *ret = ERRPTR;
170 case SS_DATATYPE_INTEGER: return SpiderScript_CreateInteger(0);
171 case SS_DATATYPE_REAL: return SpiderScript_CreateReal(0);
172 case SS_DATATYPE_STRING: return SpiderScript_CreateString(4, "null");
177 // Check if anything needs to be done
178 if( Source->Type == Type ) {
179 Object_Reference(Source);
185 printf("Casting %i ", Source->Type);
188 case SS_DATATYPE_INTEGER: printf("0x%lx", Source->Integer); break;
189 case SS_DATATYPE_STRING: printf("\"%s\"", Source->String.Data); break;
190 case SS_DATATYPE_REAL: printf("%f", Source->Real); break;
193 printf(" to %i\n", Type);
198 if( Source->Type == SS_DATATYPE_OBJECT )
200 const char *name = NULL;
203 case SS_DATATYPE_INTEGER: name = "cast Integer"; break;
204 case SS_DATATYPE_REAL: name = "cast Real"; break;
205 case SS_DATATYPE_STRING: name = "cast String"; break;
206 case SS_DATATYPE_ARRAY: name = "cast Array"; break;
208 AST_RuntimeError(NULL, "Invalid cast to %i from Object", Type);
213 ret = Object_ExecuteMethod(Left->Object, fcnname, Right);
216 // Fall through and try casting (which will usually fail)
221 switch( (enum eSpiderScript_DataTypes)Type )
223 case SS_DATATYPE_UNDEF:
224 case SS_DATATYPE_ARRAY:
225 case SS_DATATYPE_OPAQUE:
226 case SS_DATATYPE_OBJECT:
227 AST_RuntimeError(NULL, "Invalid cast to %i", Type);
230 case SS_DATATYPE_INTEGER:
231 ret = malloc(sizeof(tSpiderValue));
232 ret->Type = SS_DATATYPE_INTEGER;
233 ret->ReferenceCount = 1;
236 case SS_DATATYPE_INTEGER: break; // Handled above
237 case SS_DATATYPE_STRING: ret->Integer = atoi(Source->String.Data); break;
238 case SS_DATATYPE_REAL: ret->Integer = Source->Real; break;
240 AST_RuntimeError(NULL, "Invalid cast from %i to Integer", Source->Type);
247 case SS_DATATYPE_REAL:
248 ret = malloc(sizeof(tSpiderValue));
249 ret->Type = SS_DATATYPE_REAL;
250 ret->ReferenceCount = 1;
253 case SS_DATATYPE_STRING: ret->Real = atof(Source->String.Data); break;
254 case SS_DATATYPE_INTEGER: ret->Real = Source->Integer; break;
256 AST_RuntimeError(NULL, "Invalid cast from %i to Real", Source->Type);
263 case SS_DATATYPE_STRING:
266 case SS_DATATYPE_INTEGER: len = snprintf(NULL, 0, "%li", Source->Integer); break;
267 case SS_DATATYPE_REAL: len = snprintf(NULL, 0, "%g", Source->Real); break;
270 ret = malloc(sizeof(tSpiderValue) + len + 1);
271 ret->Type = SS_DATATYPE_STRING;
272 ret->ReferenceCount = 1;
273 ret->String.Length = len;
276 case SS_DATATYPE_INTEGER: sprintf(ret->String.Data, "%li", Source->Integer); break;
277 case SS_DATATYPE_REAL:
278 sprintf(ret->String.Data, "%g", Source->Real); break;
280 AST_RuntimeError(NULL, "Invalid cast from %i to String", Source->Type);
288 AST_RuntimeError(NULL, "BUG - BUG REPORT: Unimplemented cast target %i", Type);
297 * \brief Condenses a value down to a boolean
299 int SpiderScript_IsValueTrue(tSpiderValue *Value)
301 if( Value == ERRPTR ) return 0;
302 if( Value == NULL ) return 0;
304 switch( (enum eSpiderScript_DataTypes)Value->Type )
306 case SS_DATATYPE_UNDEF:
309 case SS_DATATYPE_INTEGER:
310 return !!Value->Integer;
312 case SS_DATATYPE_REAL:
313 return (-.5f < Value->Real && Value->Real < 0.5f);
315 case SS_DATATYPE_STRING:
316 return Value->String.Length > 0;
318 case SS_DATATYPE_OBJECT:
319 return Value->Object != NULL;
321 case SS_DATATYPE_OPAQUE:
322 return Value->Opaque.Data != NULL;
324 case SS_DATATYPE_ARRAY:
325 return Value->Array.Length > 0;
327 AST_RuntimeError(NULL, "Unknown type %i in SpiderScript_IsValueTrue", Value->Type);
334 * \brief Free a value
335 * \note Just calls Object_Dereference
337 void SpiderScript_FreeValue(tSpiderValue *Value)
339 Object_Dereference(Value);
343 * \brief Dump a value into a string
344 * \return Heap string
346 char *SpiderScript_DumpValue(tSpiderValue *Value)
349 if( Value == ERRPTR )
350 return strdup("ERRPTR");
352 return strdup("null");
354 switch( (enum eSpiderScript_DataTypes)Value->Type )
356 case SS_DATATYPE_UNDEF: return strdup("undefined");
358 case SS_DATATYPE_INTEGER:
359 ret = malloc( sizeof(Value->Integer)*2 + 3 );
360 sprintf(ret, "0x%lx", Value->Integer);
363 case SS_DATATYPE_REAL:
364 ret = malloc( sprintf(NULL, "%f", Value->Real) + 1 );
365 sprintf(ret, "%f", Value->Real);
368 case SS_DATATYPE_STRING:
369 ret = malloc( Value->String.Length + 3 );
371 strcpy(ret+1, Value->String.Data);
372 ret[Value->String.Length+1] = '"';
373 ret[Value->String.Length+2] = '\0';
376 case SS_DATATYPE_OBJECT:
377 ret = malloc( sprintf(NULL, "{%s *%p}", Value->Object->Type->Name, Value->Object) + 1 );
378 sprintf(ret, "{%s *%p}", Value->Object->Type->Name, Value->Object);
381 case SS_DATATYPE_OPAQUE:
382 ret = malloc( sprintf(NULL, "*%p", Value->Opaque.Data) + 1 );
383 sprintf(ret, "*%p", Value->Opaque.Data);
386 case SS_DATATYPE_ARRAY:
387 return strdup("Array");
390 AST_RuntimeError(NULL, "Unknown type %i in Object_Dump", Value->Type);
397 * \brief Execute a script function
398 * \param Script Script context to execute in
399 * \param Namespace Namespace to search for the function
400 * \param Function Function name to execute
401 * \param NArguments Number of arguments to pass
402 * \param Arguments Arguments passed
404 tSpiderValue *SpiderScript_ExecuteFunction(tSpiderScript *Script,
405 tSpiderNamespace *Namespace, const char *Function,
406 int NArguments, tSpiderValue **Arguments)
408 int bFound = 0; // Used to keep nesting levels down
409 tSpiderValue *ret = ERRPTR;
410 tSpiderFunction *fcn;
412 // First: Find the function in the script
414 tAST_Function *astFcn;
415 for( astFcn = Script->Script->Functions; astFcn; astFcn = astFcn->Next )
417 if( strcmp(astFcn->Name, Function) == 0 )
427 // Build a block State
431 bs.BaseNamespace = &Script->Variant->RootNamespace;
432 bs.CurNamespace = NULL;
434 bs.Ident = giNextBlockIdent ++;
437 for( arg = astFcn->Arguments; arg; arg = arg->NextSibling, i++ )
439 if( i >= NArguments ) break; // TODO: Return gracefully
442 arg->DefVar.DataType, arg->DefVar.Name,
447 ret = AST_ExecuteNode(&bs, astFcn->Code);
450 Object_Dereference(ret); // Dereference output of last block statement
451 ret = bs.RetVal; // Set to return value of block
457 tAST_Variable *nextVar = bs.FirstVar->Next;
458 Variable_Destroy( bs.FirstVar );
459 bs.FirstVar = nextVar;
464 // Didn't find it in script?
467 fcn = NULL; // Just to allow the below code to be neat
469 // Second: Scan current namespace
470 if( !fcn && Namespace )
472 for( fcn = Namespace->Functions; fcn; fcn = fcn->Next )
474 if( strcmp( fcn->Name, Function ) == 0 )
479 // Third: Search the variant's global exports
482 for( fcn = Script->Variant->Functions; fcn; fcn = fcn->Next )
484 if( strcmp( fcn->Name, Function ) == 0 )
489 // Fourth: Search language exports
492 for( fcn = gpExports_First; fcn; fcn = fcn->Next )
494 if( strcmp( fcn->Name, Function ) == 0 )
502 // TODO: Type Checking
503 ret = fcn->Handler( Script, NArguments, Arguments );
511 fprintf(stderr, "Undefined reference to function '%s' (ns='%s')\n",
512 Function, Namespace->Name);
520 * \brief Execute an object method function
521 * \param Script Script context to execute in
522 * \param Object Object in which to find the method
523 * \param MethodName Name of method to call
524 * \param NArguments Number of arguments to pass
525 * \param Arguments Arguments passed
527 tSpiderValue *SpiderScript_ExecuteMethod(tSpiderScript *Script,
528 tSpiderObject *Object, const char *MethodName,
529 int NArguments, tSpiderValue **Arguments)
531 tSpiderFunction *fcn;
533 tSpiderValue *newargs[NArguments+1];
536 // TODO: Support program defined objects
538 // Search for the function
539 for( fcn = Object->Type->Methods; fcn; fcn = fcn->Next )
541 if( strcmp(fcn->Name, MethodName) == 0 )
547 AST_RuntimeError(NULL, "Class '%s' does not have a method '%s'",
548 Object->Type->Name, MethodName);
552 // Create the "this" argument
553 this.Type = SS_DATATYPE_OBJECT;
554 this.ReferenceCount = 1;
555 this.Object = Object;
557 memcpy(&newargs[1], Arguments, NArguments*sizeof(tSpiderValue*));
559 // Check the type of the arguments
560 for( i = 0; fcn->ArgTypes[i]; i ++ )
562 if( i >= NArguments ) {
563 for( ; fcn->ArgTypes[i]; i ++ ) ;
564 AST_RuntimeError(NULL, "Argument count mismatch (%i passed, %i expected)",
568 if( Arguments[i] && Arguments[i]->Type != fcn->ArgTypes[i] )
570 AST_RuntimeError(NULL, "Argument type mismatch (%i, expected %i)",
571 Arguments[i]->Type, fcn->ArgTypes[i]);
577 return fcn->Handler(Script, NArguments+1, newargs);
581 * \brief Execute a script function
582 * \param Script Script context to execute in
583 * \param Function Function name to execute
584 * \param NArguments Number of arguments to pass
585 * \param Arguments Arguments passed
587 tSpiderValue *SpiderScript_CreateObject(tSpiderScript *Script,
588 tSpiderNamespace *Namespace, const char *ClassName,
589 int NArguments, tSpiderValue **Arguments)
591 int bFound = 0; // Used to keep nesting levels down
592 tSpiderValue *ret = ERRPTR;
593 tSpiderObjectDef *class;
595 // First: Find the function in the script
596 // TODO: Implement script-defined classes
599 tAST_Function *astClass;
600 for( astClass = Script->Script->Classes; astClass; astClass = astClass->Next )
602 if( strcmp(astClass->Name, ClassName) == 0 )
612 // Build a block State
616 bs.BaseNamespace = &Script->Variant->RootNamespace;
617 bs.CurNamespace = NULL;
619 bs.Ident = giNextBlockIdent ++;
621 for( arg = astFcn->Arguments; arg; arg = arg->NextSibling, i++ )
623 if( i >= NArguments ) break; // TODO: Return gracefully
626 arg->DefVar.DataType, arg->DefVar.Name,
631 ret = AST_ExecuteNode(&bs, astFcn->Code);
634 Object_Dereference(ret); // Dereference output of last block statement
635 ret = bs.RetVal; // Set to return value of block
641 tAST_Variable *nextVar = bs.FirstVar->Next;
642 Variable_Destroy( bs.FirstVar );
643 bs.FirstVar = nextVar;
649 // Didn't find it in script?
652 class = NULL; // Just to allow the below code to be neat
655 // Namespace = &Script->Variant->RootNamespace;
657 // Second: Scan current namespace
658 if( !class && Namespace )
660 for( class = Namespace->Classes; class; class = class->Next )
662 if( strcmp( class->Name, ClassName ) == 0 )
668 // Third: Search the variant's global exports
671 for( class = Script->Variant->Classes; class; class = fcn->Next )
673 if( strcmp( class->Name, Function ) == 0 )
680 // Fourth: Search language exports
683 for( class = gpExports_First; class; class = fcn->Next )
685 if( strcmp( class->Name, ClassName ) == 0 )
695 // TODO: Type Checking
698 obj = class->Constructor( NArguments, Arguments );
699 if( obj == NULL || obj == ERRPTR )
702 // Creatue return object
703 ret = malloc( sizeof(tSpiderValue) );
704 ret->Type = SS_DATATYPE_OBJECT;
705 ret->ReferenceCount = 1;
714 fprintf(stderr, "Undefined reference to class '%s'\n", ClassName);
723 * \brief Execute an AST node and return its value
724 * \param Block Execution context
725 * \param Node Node to execute
727 tSpiderValue *AST_ExecuteNode(tAST_BlockState *Block, tAST_Node *Node)
730 tSpiderValue *ret = NULL, *tmpobj;
731 tSpiderValue *op1, *op2; // Binary operations
732 int cmp; // Used in comparisons
745 tAST_BlockState blockInfo;
746 blockInfo.Parent = Block;
747 blockInfo.Script = Block->Script;
748 blockInfo.FirstVar = NULL;
749 blockInfo.RetVal = NULL;
750 blockInfo.BaseNamespace = Block->BaseNamespace;
751 blockInfo.CurNamespace = NULL;
752 blockInfo.Ident = giNextBlockIdent ++;
754 // Loop over all nodes, or until the return value is set
755 for(node = Node->Block.FirstChild; node && !blockInfo.RetVal; node = node->NextSibling )
757 ret = AST_ExecuteNode(&blockInfo, node);
758 if(ret == ERRPTR) break; // Error check
759 if(ret != NULL) Object_Dereference(ret); // Free unused value
761 // Clean up variables
762 while(blockInfo.FirstVar)
764 tAST_Variable *nextVar = blockInfo.FirstVar->Next;
765 Variable_Destroy( blockInfo.FirstVar );
766 blockInfo.FirstVar = nextVar;
768 // Clear ret if not an error
769 if(ret != ERRPTR) ret = NULL;
771 // Set parent's return value if needed
772 if( blockInfo.RetVal )
773 Block->RetVal = blockInfo.RetVal;
779 case NODETYPE_ASSIGN:
780 // TODO: Support assigning to object attributes
781 if( Node->Assign.Dest->Type != NODETYPE_VARIABLE ) {
782 AST_RuntimeError(Node, "LVALUE of assignment is not a variable");
785 ret = AST_ExecuteNode(Block, Node->Assign.Value);
786 if(ret == ERRPTR) return ERRPTR;
788 // Perform assignment operation
789 if( Node->Assign.Operation != NODETYPE_NOP )
791 tSpiderValue *varVal = Variable_GetValue(Block, Node->Assign.Dest);
793 value = AST_ExecuteNode_BinOp(Block, Node, Node->Assign.Operation, varVal, ret);
794 if(value == ERRPTR) return ERRPTR;
795 if(ret) Object_Dereference(ret);
796 if(varVal) Object_Dereference(varVal);
800 // Set the variable value
801 if( Variable_SetValue( Block, Node->Assign.Dest, ret ) ) {
802 Object_Dereference( ret );
807 // Post increment/decrement
808 case NODETYPE_POSTINC:
809 case NODETYPE_POSTDEC:
811 tSpiderValue *varVal, *value;
812 static tSpiderValue one = {
813 .Type = SS_DATATYPE_INTEGER,
818 // TODO: Support assigning to object attributes
819 if( Node->UniOp.Value->Type != NODETYPE_VARIABLE ) {
820 AST_RuntimeError(Node, "LVALUE of assignment is not a variable");
824 // Get values (current variable contents and a static one)
825 varVal = Variable_GetValue(Block, Node->UniOp.Value);
827 if( Node->Type == NODETYPE_POSTDEC )
828 value = AST_ExecuteNode_BinOp(Block, Node, NODETYPE_SUBTRACT, varVal, &one);
830 value = AST_ExecuteNode_BinOp(Block, Node, NODETYPE_ADD, varVal, &one);
831 if( value == ERRPTR )
836 if( Variable_SetValue( Block, Node->UniOp.Value, value ) ) {
837 Object_Dereference( ret );
840 Object_Dereference( value );
845 case NODETYPE_METHODCALL:
846 case NODETYPE_FUNCTIONCALL:
847 case NODETYPE_CREATEOBJECT:
848 // Logical block (used to allocate `params`)
850 tSpiderNamespace *ns = Block->CurNamespace;
851 tSpiderValue *params[Node->FunctionCall.NumArgs];
853 for(node = Node->FunctionCall.FirstArg; node; node = node->NextSibling)
855 params[i] = AST_ExecuteNode(Block, node);
856 if( params[i] == ERRPTR ) {
857 while(i--) Object_Dereference(params[i]);
864 if( !ns ) ns = Block->BaseNamespace;
867 if( Node->Type == NODETYPE_CREATEOBJECT )
869 ret = SpiderScript_CreateObject(Block->Script,
871 Node->FunctionCall.Name,
872 Node->FunctionCall.NumArgs, params
875 else if( Node->Type == NODETYPE_METHODCALL )
877 tSpiderValue *obj = AST_ExecuteNode(Block, Node->FunctionCall.Object);
878 if( !obj || obj == ERRPTR || obj->Type != SS_DATATYPE_OBJECT ) {
879 AST_RuntimeError(Node->FunctionCall.Object,
880 "Type Mismatch - Required SS_DATATYPE_OBJECT for method call");
881 while(i--) Object_Dereference(params[i]);
885 ret = SpiderScript_ExecuteMethod(Block->Script,
886 obj->Object, Node->FunctionCall.Name,
887 Node->FunctionCall.NumArgs, params
889 Object_Dereference(obj);
893 ret = SpiderScript_ExecuteFunction(Block->Script,
894 ns, Node->FunctionCall.Name,
895 Node->FunctionCall.NumArgs, params
900 // Dereference parameters
901 while(i--) Object_Dereference(params[i]);
909 ret = AST_ExecuteNode(Block, Node->If.Condition);
910 if( ret == ERRPTR ) break;
911 if( SpiderScript_IsValueTrue(ret) ) {
912 tmpobj = AST_ExecuteNode(Block, Node->If.True);
915 tmpobj = AST_ExecuteNode(Block, Node->If.False);
917 Object_Dereference(ret);
918 if( tmpobj == ERRPTR ) return ERRPTR;
919 Object_Dereference(tmpobj);
925 ret = AST_ExecuteNode(Block, Node->For.Init);
926 if(ret == ERRPTR) break;
927 if( Node->For.bCheckAfter )
930 Object_Dereference(ret);
931 ret = AST_ExecuteNode(Block, Node->For.Code);
932 if(ret == ERRPTR) return ERRPTR;
933 Object_Dereference(ret);
934 ret = AST_ExecuteNode(Block, Node->For.Increment);
935 if(ret == ERRPTR) return ERRPTR;
936 Object_Dereference(ret);
937 ret = AST_ExecuteNode(Block, Node->For.Condition);
938 if(ret == ERRPTR) return ERRPTR;
939 } while( SpiderScript_IsValueTrue(ret) );
943 Object_Dereference(ret);
944 ret = AST_ExecuteNode(Block, Node->For.Condition);
945 if(ret == ERRPTR) return ERRPTR;
946 while( SpiderScript_IsValueTrue(ret) ) {
947 Object_Dereference(ret);
948 ret = AST_ExecuteNode(Block, Node->For.Code);
949 if(ret == ERRPTR) return ERRPTR;
950 Object_Dereference(ret);
951 ret = AST_ExecuteNode(Block, Node->For.Increment);
952 if(ret == ERRPTR) return ERRPTR;
953 Object_Dereference(ret);
954 ret = AST_ExecuteNode(Block, Node->For.Condition);
955 if(ret == ERRPTR) return ERRPTR;
958 Object_Dereference(ret);
963 case NODETYPE_RETURN:
964 ret = AST_ExecuteNode(Block, Node->UniOp.Value);
965 if(ret == ERRPTR) break;
966 Block->RetVal = ret; // Return value set
967 ret = NULL; // the `return` statement does not return a value
971 case NODETYPE_DEFVAR:
972 if( Node->DefVar.InitialValue ) {
973 tmpobj = AST_ExecuteNode(Block, Node->DefVar.InitialValue);
974 if(tmpobj == ERRPTR) return ERRPTR;
980 if( Variable_Define(Block, Node->DefVar.DataType, Node->DefVar.Name, tmpobj) == ERRPTR )
982 Object_Dereference(tmpobj);
988 tSpiderNamespace *ns;
990 // Set current namespace if unset
991 if( !Block->CurNamespace )
992 Block->CurNamespace = Block->BaseNamespace;
994 // Empty string means use the root namespace
995 if( Node->Scope.Name[0] == '\0' )
997 ns = &Block->Script->Variant->RootNamespace;
1001 // Otherwise scan the current namespace for the element
1002 for( ns = Block->CurNamespace->FirstChild; ns; ns = ns->Next )
1004 if( strcmp(ns->Name, Node->Scope.Name) == 0 )
1009 AST_RuntimeError(Node, "Unknown namespace '%s'", Node->Scope.Name);
1013 Block->CurNamespace = ns;
1015 ret = AST_ExecuteNode(Block, Node->Scope.Element);
1020 case NODETYPE_VARIABLE:
1021 ret = Variable_GetValue( Block, Node );
1024 // Element of an Object
1025 case NODETYPE_ELEMENT:
1026 tmpobj = AST_ExecuteNode( Block, Node->Scope.Element );
1027 if(tmpobj == ERRPTR) return ERRPTR;
1028 if( !tmpobj || tmpobj->Type != SS_DATATYPE_OBJECT )
1030 AST_RuntimeError(Node->Scope.Element, "Unable to dereference a non-object");
1035 for( i = 0; i < tmpobj->Object->Type->NAttributes; i ++ )
1037 if( strcmp(Node->Scope.Name, tmpobj->Object->Type->AttributeDefs[i].Name) == 0 )
1039 ret = tmpobj->Object->Attributes[i];
1040 Object_Reference(ret);
1044 if( i == tmpobj->Object->Type->NAttributes )
1046 AST_RuntimeError(Node->Scope.Element, "Unknown attribute '%s' of class '%s'",
1047 Node->Scope.Name, tmpobj->Object->Type->Name);
1052 // Cast a value to another
1055 tmpobj = AST_ExecuteNode(Block, Node->Cast.Value);
1056 if(tmpobj == ERRPTR) return ERRPTR;
1057 ret = SpiderScript_CastValueTo( Node->Cast.DataType, tmpobj );
1058 Object_Dereference(tmpobj);
1062 // Index into an array
1063 case NODETYPE_INDEX:
1064 op1 = AST_ExecuteNode(Block, Node->BinOp.Left); // Array
1065 if(op1 == ERRPTR) return ERRPTR;
1066 op2 = AST_ExecuteNode(Block, Node->BinOp.Right); // Offset
1068 Object_Dereference(op1);
1072 if( !op1 || op1->Type != SS_DATATYPE_ARRAY )
1074 // TODO: Implement "operator []" on objects
1075 AST_RuntimeError(Node, "Indexing non-array");
1080 if( (!op2 || op2->Type != SS_DATATYPE_INTEGER) && !Block->Script->Variant->bImplicitCasts ) {
1081 AST_RuntimeError(Node, "Array index is not an integer");
1086 if( !op2 || op2->Type != SS_DATATYPE_INTEGER )
1088 tmpobj = SpiderScript_CastValueTo(SS_DATATYPE_INTEGER, op2);
1089 Object_Dereference(op2);
1093 if( op2->Integer >= op1->Array.Length ) {
1094 AST_RuntimeError(Node, "Array index out of bounds %i >= %i",
1095 op2->Integer, op1->Array.Length);
1100 ret = op1->Array.Items[ op2->Integer ];
1101 Object_Reference(ret);
1103 Object_Dereference(op1);
1104 Object_Dereference(op2);
1107 // TODO: Implement runtime constants
1108 case NODETYPE_CONSTANT:
1109 // TODO: Scan namespace for function
1110 AST_RuntimeError(Node, "TODO - Runtime Constants");
1115 case NODETYPE_STRING:
1116 case NODETYPE_INTEGER:
1118 ret = &Node->Constant;
1119 Object_Reference(ret);
1122 // --- Operations ---
1123 // Boolean Operations
1124 case NODETYPE_LOGICALNOT: // Logical NOT (!)
1125 op1 = AST_ExecuteNode(Block, Node->UniOp.Value);
1126 if(op1 == ERRPTR) return ERRPTR;
1127 ret = SpiderScript_CreateInteger( !SpiderScript_IsValueTrue(op1) );
1128 Object_Dereference(op1);
1130 case NODETYPE_LOGICALAND: // Logical AND (&&)
1131 case NODETYPE_LOGICALOR: // Logical OR (||)
1132 case NODETYPE_LOGICALXOR: // Logical XOR (^^)
1133 op1 = AST_ExecuteNode(Block, Node->BinOp.Left);
1134 if(op1 == ERRPTR) return ERRPTR;
1135 op2 = AST_ExecuteNode(Block, Node->BinOp.Right);
1137 Object_Dereference(op1);
1141 switch( Node->Type )
1143 case NODETYPE_LOGICALAND:
1144 ret = SpiderScript_CreateInteger( SpiderScript_IsValueTrue(op1) && SpiderScript_IsValueTrue(op2) );
1146 case NODETYPE_LOGICALOR:
1147 ret = SpiderScript_CreateInteger( SpiderScript_IsValueTrue(op1) || SpiderScript_IsValueTrue(op2) );
1149 case NODETYPE_LOGICALXOR:
1150 ret = SpiderScript_CreateInteger( SpiderScript_IsValueTrue(op1) ^ SpiderScript_IsValueTrue(op2) );
1155 // Free intermediate objects
1156 Object_Dereference(op1);
1157 Object_Dereference(op2);
1161 case NODETYPE_EQUALS:
1162 case NODETYPE_LESSTHAN:
1163 case NODETYPE_GREATERTHAN:
1164 case NODETYPE_LESSTHANEQUAL:
1165 case NODETYPE_GREATERTHANEQUAL:
1166 op1 = AST_ExecuteNode(Block, Node->BinOp.Left);
1167 if(op1 == ERRPTR) return ERRPTR;
1168 op2 = AST_ExecuteNode(Block, Node->BinOp.Right);
1170 Object_Dereference(op1);
1175 if( !op1 || !op2 ) {
1176 AST_RuntimeError(Node, "NULL Comparison (%p and %p)", op1, op2);
1177 if(op1) Object_Dereference(op1);
1178 if(op2) Object_Dereference(op2);
1179 ret = SpiderScript_CreateInteger( !op1 && !op2 );
1184 if( op1->Type != op2->Type ) {
1185 // If dynamically typed, convert op2 to op1's type
1186 if(Block->Script->Variant->bImplicitCasts)
1189 op2 = SpiderScript_CastValueTo(op1->Type, op2);
1190 Object_Dereference(tmpobj);
1192 Object_Dereference(op1);
1196 // If statically typed, this should never happen, but catch it anyway
1198 AST_RuntimeError(Node, "Statically typed implicit cast %i <op> %i",
1199 op1->Type, op2->Type);
1207 // - String Compare (does a strcmp, well memcmp)
1208 case SS_DATATYPE_STRING:
1209 // Call memcmp to do most of the work
1211 op1->String.Data, op2->String.Data,
1212 (op1->String.Length < op2->String.Length) ? op1->String.Length : op2->String.Length
1214 // Handle reaching the end of the string
1216 if( op1->String.Length == op2->String.Length )
1218 else if( op1->String.Length < op2->String.Length )
1225 // - Integer Comparisons
1226 case SS_DATATYPE_INTEGER:
1227 if( op1->Integer == op2->Integer )
1229 else if( op1->Integer < op2->Integer )
1234 // - Real Number Comparisons
1235 case SS_DATATYPE_REAL:
1236 cmp = (op1->Real - op2->Real) / op2->Real * 10000; // < 0.1% difference is equality
1239 AST_RuntimeError(Node, "TODO - Comparison of type %i", op1->Type);
1244 // Free intermediate objects
1245 Object_Dereference(op1);
1246 Object_Dereference(op2);
1255 case NODETYPE_EQUALS: ret = SpiderScript_CreateInteger(cmp == 0); break;
1256 case NODETYPE_LESSTHAN: ret = SpiderScript_CreateInteger(cmp < 0); break;
1257 case NODETYPE_GREATERTHAN: ret = SpiderScript_CreateInteger(cmp > 0); break;
1258 case NODETYPE_LESSTHANEQUAL: ret = SpiderScript_CreateInteger(cmp <= 0); break;
1259 case NODETYPE_GREATERTHANEQUAL: ret = SpiderScript_CreateInteger(cmp >= 0); break;
1261 AST_RuntimeError(Node, "Exec,CmpOp unknown op %i", Node->Type);
1267 // General Unary Operations
1268 case NODETYPE_BWNOT: // Bitwise NOT (~)
1269 case NODETYPE_NEGATE: // Negation (-)
1270 op1 = AST_ExecuteNode(Block, Node->UniOp.Value);
1271 if(op1 == ERRPTR) return ERRPTR;
1272 ret = AST_ExecuteNode_UniOp(Block, Node, Node->Type, op1);
1273 Object_Dereference(op1);
1276 // General Binary Operations
1278 case NODETYPE_SUBTRACT:
1279 case NODETYPE_MULTIPLY:
1280 case NODETYPE_DIVIDE:
1281 case NODETYPE_MODULO:
1282 case NODETYPE_BWAND:
1284 case NODETYPE_BWXOR:
1285 case NODETYPE_BITSHIFTLEFT:
1286 case NODETYPE_BITSHIFTRIGHT:
1287 case NODETYPE_BITROTATELEFT:
1289 op1 = AST_ExecuteNode(Block, Node->BinOp.Left);
1290 if(op1 == ERRPTR) return ERRPTR;
1291 op2 = AST_ExecuteNode(Block, Node->BinOp.Right);
1293 Object_Dereference(op1);
1297 ret = AST_ExecuteNode_BinOp(Block, Node, Node->Type, op1, op2);
1299 // Free intermediate objects
1300 Object_Dereference(op1);
1301 Object_Dereference(op2);
1306 // AST_RuntimeError(Node, "BUG - SpiderScript AST_ExecuteNode Unimplemented %i", Node->Type);
1310 // Reset namespace when no longer needed
1311 if( Node->Type != NODETYPE_SCOPE )
1312 Block->CurNamespace = NULL;
1314 #if TRACE_NODE_RETURNS
1315 if(ret && ret != ERRPTR) {
1316 AST_RuntimeError(Node, "Ret type of %p %i is %i", Node, Node->Type, ret->Type);
1319 AST_RuntimeError(Node, "Ret type of %p %i is %p", Node, Node->Type, ret);
1326 tSpiderValue *AST_ExecuteNode_UniOp(tAST_BlockState *Block, tAST_Node *Node, int Operation, tSpiderValue *Value)
1330 if( Value->Type == SS_DATATYPE_OBJECT )
1332 const char *fcnname;
1335 case NODETYPE_NEGATE: fcnname = "-ve"; break;
1336 case NODETYPE_BWNOT: fcnname = "~"; break;
1337 default: fcnname = NULL; break;
1342 ret = Object_ExecuteMethod(Value->Object, fcnname, );
1345 // Fall through and try casting (which will usually fail)
1351 // Integer Operations
1352 case SS_DATATYPE_INTEGER:
1355 case NODETYPE_NEGATE: ret = SpiderScript_CreateInteger( -Value->Integer ); break;
1356 case NODETYPE_BWNOT: ret = SpiderScript_CreateInteger( ~Value->Integer ); break;
1358 AST_RuntimeError(Node, "SpiderScript internal error: Exec,UniOP,Integer unknown op %i", Operation);
1363 // Real number Operations
1364 case SS_DATATYPE_REAL:
1367 case NODETYPE_NEGATE: ret = SpiderScript_CreateInteger( -Value->Real ); break;
1369 AST_RuntimeError(Node, "SpiderScript internal error: Exec,UniOP,Real unknown op %i", Operation);
1376 AST_RuntimeError(NULL, "Invalid operation (%i) on type (%i)", Operation, Value->Type);
1384 tSpiderValue *AST_ExecuteNode_BinOp(tAST_BlockState *Block, tAST_Node *Node, int Operation, tSpiderValue *Left, tSpiderValue *Right)
1386 tSpiderValue *preCastValue = Right;
1390 if( Left && Right && Left->Type != Right->Type )
1394 // - Operator overload functions
1395 if( Left->Type == SS_DATATYPE_OBJECT )
1397 const char *fcnname;
1400 case NODETYPE_ADD: fcnname = "+"; break;
1401 case NODETYPE_SUBTRACT: fcnname = "-"; break;
1402 case NODETYPE_MULTIPLY: fcnname = "*"; break;
1403 case NODETYPE_DIVIDE: fcnname = "/"; break;
1404 case NODETYPE_MODULO: fcnname = "%"; break;
1405 case NODETYPE_BWAND: fcnname = "&"; break;
1406 case NODETYPE_BWOR: fcnname = "|"; break;
1407 case NODETYPE_BWXOR: fcnname = "^"; break;
1408 case NODETYPE_BITSHIFTLEFT: fcnname = "<<"; break;
1409 case NODETYPE_BITSHIFTRIGHT:fcnname = ">>"; break;
1410 case NODETYPE_BITROTATELEFT:fcnname = "<<<"; break;
1411 default: fcnname = NULL; break;
1416 ret = Object_ExecuteMethod(Left->Object, fcnname, Right);
1419 // Fall through and try casting (which will usually fail)
1424 // If implicit casts are allowed, convert Right to Left's type
1425 if(Block->Script->Variant->bImplicitCasts)
1427 Right = SpiderScript_CastValueTo(Left->Type, Right);
1431 // If statically typed, this should never happen, but catch it anyway
1433 AST_RuntimeError(Node, "Implicit cast not allowed (from %i to %i)", Right->Type, Left->Type);
1439 if( Left == NULL || Right == NULL ) {
1440 if(Right && Right != preCastValue) free(Right);
1447 // String Concatenation
1448 case SS_DATATYPE_STRING:
1451 case NODETYPE_ADD: // Concatenate
1452 ret = Object_StringConcat(Left, Right);
1455 AST_RuntimeError(Node, "SpiderScript internal error: Exec,BinOP,String unknown op %i", Operation);
1460 // Integer Operations
1461 case SS_DATATYPE_INTEGER:
1464 case NODETYPE_ADD: ret = SpiderScript_CreateInteger( Left->Integer + Right->Integer ); break;
1465 case NODETYPE_SUBTRACT: ret = SpiderScript_CreateInteger( Left->Integer - Right->Integer ); break;
1466 case NODETYPE_MULTIPLY: ret = SpiderScript_CreateInteger( Left->Integer * Right->Integer ); break;
1467 case NODETYPE_DIVIDE: ret = SpiderScript_CreateInteger( Left->Integer / Right->Integer ); break;
1468 case NODETYPE_MODULO: ret = SpiderScript_CreateInteger( Left->Integer % Right->Integer ); break;
1469 case NODETYPE_BWAND: ret = SpiderScript_CreateInteger( Left->Integer & Right->Integer ); break;
1470 case NODETYPE_BWOR: ret = SpiderScript_CreateInteger( Left->Integer | Right->Integer ); break;
1471 case NODETYPE_BWXOR: ret = SpiderScript_CreateInteger( Left->Integer ^ Right->Integer ); break;
1472 case NODETYPE_BITSHIFTLEFT: ret = SpiderScript_CreateInteger( Left->Integer << Right->Integer ); break;
1473 case NODETYPE_BITSHIFTRIGHT:ret = SpiderScript_CreateInteger( Left->Integer >> Right->Integer ); break;
1474 case NODETYPE_BITROTATELEFT:
1475 ret = SpiderScript_CreateInteger( (Left->Integer << Right->Integer) | (Left->Integer >> (64-Right->Integer)) );
1478 AST_RuntimeError(Node, "SpiderScript internal error: Exec,BinOP,Integer unknown op %i", Operation);
1485 case SS_DATATYPE_REAL:
1488 case NODETYPE_ADD: ret = SpiderScript_CreateReal( Left->Real + Right->Real ); break;
1489 case NODETYPE_SUBTRACT: ret = SpiderScript_CreateReal( Left->Real - Right->Real ); break;
1490 case NODETYPE_MULTIPLY: ret = SpiderScript_CreateReal( Left->Real * Right->Real ); break;
1491 case NODETYPE_DIVIDE: ret = SpiderScript_CreateReal( Left->Real / Right->Real ); break;
1493 AST_RuntimeError(Node, "SpiderScript internal error: Exec,BinOP,Real unknown op %i", Operation);
1500 AST_RuntimeError(Node, "BUG - Invalid operation (%i) on type (%i)", Operation, Left->Type);
1505 if(Right && Right != preCastValue) free(Right);
1511 * \brief Define a variable
1512 * \param Block Current block state
1513 * \param Type Type of the variable
1514 * \param Name Name of the variable
1515 * \return Boolean Failure
1517 tAST_Variable *Variable_Define(tAST_BlockState *Block, int Type, const char *Name, tSpiderValue *Value)
1519 tAST_Variable *var, *prev = NULL;
1521 for( var = Block->FirstVar; var; prev = var, var = var->Next )
1523 if( strcmp(var->Name, Name) == 0 ) {
1524 AST_RuntimeError(NULL, "Redefinition of variable '%s'", Name);
1529 var = malloc( sizeof(tAST_Variable) + strlen(Name) + 1 );
1532 var->Object = Value;
1533 if(Value) Object_Reference(Value);
1534 strcpy(var->Name, Name);
1536 if(prev) prev->Next = var;
1537 else Block->FirstVar = var;
1539 //printf("Defined variable %s (%i)\n", Name, Type);
1544 tAST_Variable *Variable_Lookup(tAST_BlockState *Block, tAST_Node *VarNode, int CreateType)
1546 tAST_Variable *var = NULL;
1549 if( VarNode->BlockState == Block && VarNode->BlockIdent == Block->Ident ) {
1550 var = VarNode->ValueCache;
1551 #if TRACE_VAR_LOOKUPS
1552 AST_RuntimeMessage(VarNode, "debug", "Fast var fetch on '%s' %p (%p:%i)",
1553 VarNode->Variable.Name, var,
1554 VarNode->BlockState, VarNode->BlockIdent
1560 tAST_BlockState *bs;
1561 for( bs = Block; bs; bs = bs->Parent )
1563 for( var = bs->FirstVar; var; var = var->Next )
1565 if( strcmp(var->Name, VarNode->Variable.Name) == 0 )
1573 if( Block->Script->Variant->bDyamicTyped && CreateType != SS_DATATYPE_UNDEF ) {
1575 var = Variable_Define(Block, CreateType, VarNode->Variable.Name, NULL);
1579 AST_RuntimeError(VarNode, "Variable '%s' is undefined", VarNode->Variable.Name);
1584 #if TRACE_VAR_LOOKUPS
1585 AST_RuntimeMessage(VarNode, "debug", "Saved variable lookup of '%s' %p (%p:%i)",
1586 VarNode->Variable.Name, var,
1587 Block, Block->Ident);
1590 VarNode->ValueCache = var;
1591 VarNode->BlockState = Block;
1592 VarNode->BlockIdent = Block->Ident;
1599 * \brief Set the value of a variable
1600 * \return Boolean Failure
1602 int Variable_SetValue(tAST_BlockState *Block, tAST_Node *VarNode, tSpiderValue *Value)
1604 tAST_Variable *var = Variable_Lookup(Block, VarNode, Value->Type);
1606 if( !var ) return -1;
1608 if( !Block->Script->Variant->bDyamicTyped && (Value && var->Type != Value->Type) )
1610 AST_RuntimeError(VarNode, "Type mismatch assigning to '%s'",
1611 VarNode->Variable.Name);
1615 // printf("Assign %p to '%s'\n", Value, var->Name);
1616 Object_Reference(Value);
1617 Object_Dereference(var->Object);
1618 var->Object = Value;
1623 * \brief Get the value of a variable
1625 tSpiderValue *Variable_GetValue(tAST_BlockState *Block, tAST_Node *VarNode)
1627 tAST_Variable *var = Variable_Lookup(Block, VarNode, 0);
1629 if( !var ) return ERRPTR;
1631 Object_Reference(var->Object);
1636 * \brief Destorys a variable
1638 void Variable_Destroy(tAST_Variable *Variable)
1640 // printf("Variable_Destroy: (%p'%s')\n", Variable, Variable->Name);
1641 Object_Dereference(Variable->Object);
1645 void AST_RuntimeMessage(tAST_Node *Node, const char *Type, const char *Format, ...)
1650 fprintf(stderr, "%s:%i: ", Node->File, Node->Line);
1652 fprintf(stderr, "%s: ", Type);
1653 va_start(args, Format);
1654 vfprintf(stderr, Format, args);
1656 fprintf(stderr, "\n");
1658 void AST_RuntimeError(tAST_Node *Node, const char *Format, ...)
1663 fprintf(stderr, "%s:%i: ", Node->File, Node->Line);
1665 fprintf(stderr, "error: ");
1666 va_start(args, Format);
1667 vfprintf(stderr, Format, args);
1669 fprintf(stderr, "\n");