-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathJetContext.cpp
2185 lines (1957 loc) · 53.8 KB
/
JetContext.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#ifdef _DEBUG
#ifndef DBG_NEW
#define DBG_NEW new ( _NORMAL_BLOCK , __FILE__ , __LINE__ )
#define new DBG_NEW
#endif
#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#endif
#include <jetscript/JetContext.h>
#include <jetscript/UniquePtr.h>
#include <stack>
#include <fstream>
#include <memory>
#undef Yield
using namespace Jet;
#define JET_BAD_INSTRUCTION 123456789
Value Jet::gc(JetContext* context,Value* args, int numargs)
{
context->RunGC();
return Value();
}
Value Jet::tostring(JetContext* context, Value* args, int numargs)
{
if (numargs >= 1)
{
auto str = context->NewString(args->ToString().c_str(), true);
return str;
}
throw RuntimeException("Invalid tostring call");
}
Value JetContext::Callstack(JetContext* context, Value* args, int numargs)
{
context->StackTrace(JET_BAD_INSTRUCTION, 0);
return Value();
}
Value Jet::print(JetContext* context,Value* args, int numargs)
{
for (int i = 0; i < numargs; i++)
{
printf("%s", args[i].ToString().c_str());
}
printf("\n");
return Value();
};
Value& JetContext::operator[](const std::string& id)
{
auto iter = variables.find(id);
if (iter == variables.end())
{
//add it
variables[id] = vars.size();
vars.push_back(Value());
return vars[variables[id]];
}
else
{
return vars[(*iter).second];
}
}
Value JetContext::Get(const std::string& name)
{
auto iter = variables.find(name);
if (iter == variables.end())
{
return Value();//return null
}
else
{
return vars[(*iter).second];
}
}
void JetContext::Set(const std::string& name, const Value& value)
{
auto iter = variables.find(name);
if (iter == variables.end())
{
//add it
variables[name] = variables.size();
vars.push_back(value);
}
else
{
vars[(*iter).second] = value;
}
}
Value JetContext::NewObject()
{
auto v = this->gc.New<JetObject>(this);
v->refcount = 0;
v->type = ValueType::Object;
v->grey = v->mark = false;
return Value(v);
}
Value JetContext::NewPrototype(const char* Typename)
{
auto v = new JetObject(this);//this->gc.New<JetObject>(this);//auto v = new JetObject(this);
v->refcount = 0;
v->type = ValueType::Object;
v->grey = v->mark = false;
this->prototypes.push_back(v);
return v;
}
Value JetContext::NewArray()
{
auto a = gc.New<JetArray>();//new JetArray;
a->refcount = 0;
a->grey = a->mark = false;
a->type = ValueType::Array;
a->context = this;
return Value(a);
}
Value JetContext::NewUserdata(void* data, const Value& proto)
{
if (proto.type != ValueType::Object)
throw RuntimeException("NewUserdata: Prototype supplied was not of the type 'object'\n");
auto ud = gc.New<JetUserdata>(data, proto._object);
ud->grey = ud->mark = false;
ud->refcount = 0;
ud->type = ValueType::Userdata;
return Value(ud, proto._object);
}
Value JetContext::NewString(const char* string, bool copy)
{
if (copy)
{
size_t len = strlen(string);
auto temp = new char[len+1];
memcpy(temp, string, len);
temp[len] = 0;
string = temp;
}
auto str = gc.New<GCVal<char*>>((char*)string);
str->grey = str->mark = false;
str->refcount = 0;
str->type = ValueType::String;
return Value(str);
}
#include "Libraries/File.h"
#include "Libraries/Math.h"
JetContext::JetContext() : gc(this), stack(500000), callstack(JET_MAX_CALLDEPTH, "Exceeded Max Call Depth!")
{
this->sptr = this->localstack;//initialize stack pointer
this->curframe = 0;
//add more functions and junk
(*this)["print"] = print;
(*this)["gc"] = ::gc;
(*this)["callstack"] = JetContext::Callstack;
(*this)["tostring"] = ::tostring;
(*this)["pcall"] = [](JetContext* context, Value* args, int argc)
{
if (argc == 0)
throw RuntimeException("Invalid argument count to pcall!");
try
{
if (argc > 1)
return context->Call(args, &args[1], argc-1);
else if (argc == 1)
return context->Call(args);
}
catch(RuntimeException e)
{
printf("PCall got exception: %s", e.reason.c_str());
return Value(0);
}
};
(*this)["error"] = [](JetContext* context, Value* args, int argc)
{
if (argc > 0)
throw RuntimeException(args->ToString());
else
throw RuntimeException("User Error Thrown!");
return Value();
};
/*this should probably be an instruction ...
(*this)["unpack"] = [](JetContext* context, Value* args, int argc)
{
if (argc < 1 || args->type != ValueType::Array || args->_array->data.size() == 0)
throw RuntimeException("Cannot unpack non or empty array!");
for (int i = 0; i < args[0]._array->data.size()-1; i++)
context->stack.Push(args[0]._array->data[i]);
return args[0]._array->data[args[0]._array->data.size()-1];
};*/
(*this)["loadstring"] = [](JetContext* context, Value* args, int argc)
{
if (argc < 1 || args[0].type != ValueType::String)
throw RuntimeException("Cannot load non string");
return context->Assemble(context->Compile(args[0]._string->data, "loadstring"));
};
//tiny test for "async" like functionality
/*(*this)["createServer"] = [](JetContext* context, Value* v, int args)
{
Value object = context->NewObject();
if (v->IsGenerator())
{
//make use of this for a simple tcp server
Value iterator = v->Call();
iterator.Call();//run until it yields
Value test = 52;
iterator.Call(&test, 1);
test = context->NewString("Hello world");
iterator.Call(&test, 1);
}
return object;
};*/
(*this)["setprototype"] = [](JetContext* context, Value* v, int args)
{
if (args != 2)
throw RuntimeException("Invalid Call, Improper Arguments!");
if (v->type == ValueType::Object && v[1].type == ValueType::Object)
{
Value val = v[0];
val._object->prototype = v[1]._object;
return val;
}
else
{
throw RuntimeException("Improper arguments!");
}
};
(*this)["require"] = [](JetContext* context, Value* v, int args)
{
if (args != 1 || v->type != ValueType::String)
throw RuntimeException("Invalid Call, Improper Arguments!");
auto iter = context->require_cache.find(v->_string->data);
if (iter == context->require_cache.end())
{
//check from list of libraries
auto lib = context->libraries.find(v->_string->data);
if (lib != context->libraries.end())
return lib->second;
//else load from file
std::ifstream t(v->_string->data, std::ios::in | std::ios::binary);
if (t)
{
int length;
t.seekg(0, std::ios::end); // go to the end
length = t.tellg(); // report location (this is the length)
t.seekg(0, std::ios::beg); // go back to the beginning
UniquePtr<char[]> buffer(new char[length+1]); // allocate memory for a buffer of appropriate dimension
t.read(buffer, length); // read the whole file into the buffer
buffer[length] = 0;
t.close();
auto out = context->Compile(buffer, v->_string->data);
auto fun = context->Assemble(out);
auto temp = context->NewObject();
context->require_cache[v->_string->data] = temp;
auto obj = context->Call(&fun);
if (obj.type == ValueType::Object)
{
for (auto ii: *obj._object)//copy stuff into the temporary object
temp[ii.first] = ii.second;
return temp;
}
else
{
context->require_cache[v->_string->data] = obj;//just use what was returned
return obj;
}
}
else
{
throw RuntimeException("Require could not find include: '" + (std::string)v->_string->data + "'");
}
}
else
{
return Value(iter->second);
}
};
(*this)["getprototype"] = [](JetContext* context, Value* v, int args)
{
if (args == 1 && (v->type == ValueType::Object || v->type == ValueType::Userdata))
return Value(v->GetPrototype());
else
throw RuntimeException("getprototype expected an object or userdata value!");
};
//setup the string and array tables
this->string = new JetObject(this);
this->string->prototype = 0;
(*this->string)["append"] = Value([](JetContext* context, Value* v, int args)
{
if (args == 2 && v[0].type == ValueType::String && v[1].type == ValueType::String)
{
size_t len = v[0].length + v[1].length + 1;
char* text = new char[len];
memcpy(text, v[0]._string->data, v[0].length);
memcpy(text+v[0].length, v[1]._string->data, v[1].length);
text[len-1] = 0;
return context->NewString(text, false);
}
else
throw RuntimeException("bad append call!");
});
(*this->string)["lower"] = Value([](JetContext* context, Value* v, int args)
{
if (args && v->type == ValueType::String)
{
char* str = new char[v->length+1];
memcpy(str, v->_string->data, v->length);
for (unsigned int i = 0; i < v->length; i++)
str[i] = tolower(str[i]);
str[v->length] = 0;
return context->NewString(str, false);
}
throw RuntimeException("bad lower call");
});
(*this->string)["upper"] = Value([](JetContext* context, Value* v, int args)
{
if (args && v->type == ValueType::String)
{
char* str = new char[v->length+1];
memcpy(str, v->_string->data, v->length);
for (unsigned int i = 0; i < v->length; i++)
str[i] = toupper(str[i]);
str[v->length] = 0;
return context->NewString(str, false);
}
throw RuntimeException("bad upper call");
});
//figure out how to get this working with strings
(*this->string)["_add"] = Value([](JetContext* context, Value* v, int args)
{
if (args == 2 && v[0].type == ValueType::String && v[1].type == ValueType::String)
{
size_t len = v[0].length + v[1].length + 1;
char* text = new char[len];
memcpy(text, v[1]._string->data, v[1].length);
memcpy(text+v[1].length, v[0]._string->data, v[0].length);
text[len-1] = 0;
return context->NewString(text, false);
}
else
throw RuntimeException("bad string::append() call!");
});
(*this->string)["length"] = Value([](JetContext* context, Value* v, int args)
{
if (args == 1 && v->type == ValueType::String)
return Value((double)v->length);
else
throw RuntimeException("bad string:length() call!");
});
(*this->string)["sub"] = [](JetContext* context, Value* v, int args)
{
if (args == 2)
{
if (v[0].type != ValueType::String)
throw RuntimeException("must be a string");
int len = v[0].length-(int)v[1];
if (len < 0)
throw RuntimeException("Invalid string index");
char* str = new char[len+1];
strncpy(str, &v[0]._string->data[(int)v[1]], len);
str[len] = 0;
return context->NewString(str, false);
}
else if (args == 3)
{
throw RuntimeException("Not Implemented!");
}
else
throw RuntimeException("bad sub call");
};
this->Array = new JetObject(this);
this->Array->prototype = 0;
(*this->Array)["add"] = Value([](JetContext* context, Value* v, int args)
{
if (args == 2)
v->_array->data.push_back(v[1]);
else
throw RuntimeException("Invalid add call!!");
return Value();
});
(*this->Array)["size"] = Value([](JetContext* context, Value* v, int args)
{
if (args == 1)
return Value((int)v->_array->data.size());
else
throw RuntimeException("Invalid size call!!");
});
(*this->Array)["resize"] = Value([](JetContext* context, Value* v, int args)
{
if (args == 2)
v->_array->data.resize((int)v[1]);
else
throw RuntimeException("Invalid resize call!!");
return Value();
});
(*this->Array)["remove"] = Value([](JetContext* context, Value* v, int args)
{
if (args == 2)
v->_array->data.erase(v->_array->data.begin()+(int)v[1]);
else
throw RuntimeException("Invalid remove call!!");
return Value();
});
struct arrayiter
{
JetArray* container;
Value current;
std::vector<Value>::iterator iterator;
};
//ok iterators need to hold a reference to their underlying data structure somehow
(*this->Array)["iterator"] = Value([](JetContext* context, Value* v, int args)
{
if (args == 1)
{
auto it = new arrayiter;
it->container = v->_array;
v->AddRef();
it->iterator = v->_array->data.begin();
return Value(context->NewUserdata(it, context->arrayiter));
}
throw RuntimeException("Bad call to getIterator");
});
this->object = new JetObject(this);
this->object->prototype = 0;
(*this->object)["size"] = Value([](JetContext* context, Value* v, int args)
{
//how do I get access to the array from here?
if (args == 1)
return Value((int)v->_object->size());
else
throw RuntimeException("Invalid size call!!");
});
struct objiter
{
JetObject* container;
Value current;
JetObject::Iterator iterator;
};
(*this->object)["iterator"] = Value([](JetContext* context, Value* v, int args)
{
if (args == 1)
{
auto it = new objiter;
it->container = v->_object;
v->AddRef();
it->iterator = v->_object->begin();
return (context->NewUserdata(it, context->objectiter));
}
throw RuntimeException("Bad call to getIterator");
});
this->objectiter = new JetObject(this);
this->objectiter->prototype = 0;
(*this->objectiter)["current"] = Value([](JetContext* context, Value* v, int args)
{
auto iterator = v->GetUserdata<objiter>();
return iterator->current;
});
(*this->objectiter)["advance"] = Value([](JetContext* context, Value* v, int args)
{
auto iterator = v->GetUserdata<objiter>();
if (iterator->iterator == iterator->container->end())
return Value(0);
iterator->current = iterator->iterator->second;
++iterator->iterator;
return Value(1);
});
(*this->objectiter)["_gc"] = Value([](JetContext* context, Value* v, int args)
{
auto iter = v->GetUserdata<objiter>();
Value(iter->container).Release();
delete iter;
return Value();
});
this->arrayiter = new JetObject(this);
this->arrayiter->prototype = 0;
(*this->arrayiter)["current"] = Value([](JetContext* context, Value* v, int args)
{
auto iterator = v->GetUserdata<arrayiter>();
return iterator->current;
});
(*this->arrayiter)["advance"] = Value([](JetContext* context, Value* v, int args)
{
auto iterator = v->GetUserdata<arrayiter>();
if (iterator->iterator == iterator->container->data.end())
return Value(0);
iterator->current = *iterator->iterator;
++iterator->iterator;
return Value(1);
});
(*this->arrayiter)["_gc"] = Value([](JetContext* context, Value* v, int args)
{
auto iter = v->GetUserdata<arrayiter>();
Value(iter->container).Release();
delete iter;
return Value();
});
this->function = new JetObject(this);
this->function->prototype = 0;
(*this->function)["done"] = Value([](JetContext* context, Value* v, int args)
{
if (args >= 1 && v->type == ValueType::Function && v->_function->generator)
{
if (v->_function->generator->state == Generator::GeneratorState::Dead)
return Value(1);
else
return Value(0);
}
throw RuntimeException("Cannot index a non generator or table");
});
/*ok get new iterator interface working
add an iterator function to containers and function, that returns an iterator
or a generator in the case of a yielding function
match iterator functions for iteration on generators*/
//for each loop needs current, next and advance
//only work on functions
(*this->function)["iterator"] = Value([](JetContext* context, Value* v, int args)
{
if (args >= 1 && v->type == ValueType::Function && v->_function->prototype->generator)
{
if (v->_function->generator)
{
if (v->_function->generator->state == Generator::GeneratorState::Dead)
return Value();
else
return *v;//hack for foreach loops
}
Closure* closure = new Closure;
closure->refcount = 0;
closure->grey = closure->mark = false;
closure->prev = v->_function->prev;
closure->numupvals = v->_function->numupvals;
closure->generator = new Generator(context, v->_function, 0);
if (closure->numupvals)
closure->upvals = new Capture*[closure->numupvals];
closure->prototype = v->_function->prototype;
context->gc.AddObject((GarbageCollector::gcval*)closure);
if (closure->generator->state == Generator::GeneratorState::Dead)
return Value();
else
return Value(closure);
}
throw RuntimeException("Cannot index non generator");
});
//these only work on generators
(*this->function)["current"] = Value([](JetContext* context, Value* v, int args)
{
if (args >= 1 && v->type == ValueType::Function && v->_function->generator)
{
//return last yielded value
return v->_function->generator->lastyielded;
}
throw RuntimeException("");
});
(*this->function)["advance"] = Value([](JetContext* context, Value* v, int args)
{
if (args >= 1 && v->type == ValueType::Function && v->_function->generator)
{
//execute generator here
context->Call(v);//todo add second arg if we have it
if (v->_function->generator->state == Generator::GeneratorState::Dead)
return Value(0);
else
return Value(1);
}
throw RuntimeException("");
});
//load default libraries
RegisterFileLibrary(this);
RegisterMathLibrary(this);
};
JetContext::~JetContext()
{
this->gc.Cleanup();
for (auto ii: this->functions)
delete ii.second;
for (auto ii: this->entrypoints)
delete ii;
for (auto ii: this->prototypes)
delete ii;
delete this->string;
delete this->Array;
delete this->object;
delete this->arrayiter;
delete this->objectiter;
delete this->function;
}
#ifndef _WIN32
typedef signed long long INT64;
#endif
//INT64 rate;
std::vector<IntermediateInstruction> JetContext::Compile(const char* code, const char* filename)
{
#ifdef JET_TIME_EXECUTION
INT64 start, end, rate;
QueryPerformanceFrequency( (LARGE_INTEGER *)&rate );
QueryPerformanceCounter( (LARGE_INTEGER *)&start );
#endif
Lexer lexer = Lexer(code, filename);
Parser parser = Parser(&lexer);
//printf("In: %s\n\nResult:\n", code);
BlockExpression* result = parser.parseAll();
//result->print();
//printf("\n\n");
std::vector<IntermediateInstruction> out = compiler.Compile(result, filename);
delete result;
#ifdef JET_TIME_EXECUTION
QueryPerformanceCounter( (LARGE_INTEGER *)&end );
INT64 diff = end - start;
double dt = ((double)diff)/((double)rate);
printf("Took %lf seconds to compile\n\n", dt);
#endif
return std::move(out);
}
class StackProfile
{
char* name;
INT64 start;
public:
StackProfile(char* name)
{
this->name = name;
#ifdef JET_TIME_EXECUTION
#ifdef _WIN32
//QueryPerformanceFrequency( (LARGE_INTEGER *)&rate );
QueryPerformanceCounter( (LARGE_INTEGER *)&start );
#endif
#endif
};
~StackProfile()
{
#ifdef JET_TIME_EXECUTION
#ifdef _WIN32
INT64 end,rate;
QueryPerformanceCounter( (LARGE_INTEGER *)&end );
QueryPerformanceFrequency( (LARGE_INTEGER*)&rate);
char o[100];
INT64 diff = end - start;
float dt = ((float)diff)/((float)rate);
printf("%s took %f seconds\n", name, dt);
#endif
#endif
}
};
void JetContext::RunGC()
{
this->gc.Run();
}
unsigned int JetContext::Call(const Value* fun, unsigned int iptr, unsigned int args)
{
if (fun->type == ValueType::Function)
{
//let generators be called
if (fun->_function->generator)
{
callstack.Push(std::pair<unsigned int, Closure*>(iptr, curframe));
sptr += curframe->prototype->locals;
if ((sptr - localstack) >= JET_STACK_SIZE)
throw RuntimeException("Stack Overflow!");
curframe = fun->_function;
if (args == 0)
stack.Push(Value());
else if (args > 1)
for (unsigned int i = 1; i < args; i++)
stack.Pop();
return fun->_function->generator->Resume(this)-1;
}
if (fun->_function->prototype->generator)
{
//create generator and return it
Closure* closure = new Closure;
closure->grey = closure->mark = false;
closure->prev = fun->_function->prev;
closure->numupvals = fun->_function->numupvals;
closure->refcount = 0;
closure->generator = new Generator(this, fun->_function, args);
if (closure->numupvals)
closure->upvals = new Capture*[closure->numupvals];
closure->prototype = fun->_function->prototype;
closure->type = ValueType::Function;
this->gc.AddObject((GarbageCollector::gcval*)closure);
this->stack.Push(Value(closure));
return iptr;
}
//manipulate frame pointer
callstack.Push(std::pair<unsigned int, Closure*>(iptr, curframe));
sptr += curframe->prototype->locals;
//clean out the new stack for the gc
for (unsigned int i = 0; i < fun->_function->prototype->locals; i++)
sptr[i] = Value();
if ((sptr - localstack) >= JET_STACK_SIZE)
throw RuntimeException("Stack Overflow!");
curframe = fun->_function;
/*if (false)//curframe->closed)
{
//allocate new local frame here
Closure* closure = new Closure;
closure->grey = closure->mark = false;
closure->prev = curframe->prev;
closure->numupvals = curframe->numupvals;
closure->closed = false;
closure->refcount = 0;
closure->generator = 0;
closure->type = ValueType::Function;
if (closure->numupvals)
{
closure->upvals = new Value*[closure->numupvals];
for (int i = 0; i < closure->numupvals; i++)
closure->upvals[i] = (Value*)0xcdcdcdcd;
}
closure->prototype = curframe->prototype;
gc.AddObject((GarbageCollector::gcval*)closure);
curframe = closure;
if (gc.allocationCounter++%GC_INTERVAL == 0)
this->RunGC();
}*/
//printf("ECall: Stack Ptr At: %d\n", sptr - localstack);
Function* func = curframe->prototype;
//set all the locals
if (args <= func->args)
{
for (int i = func->args-1; i >= 0; i--)
{
if (i < args)
sptr[i] = stack.Pop();
else
sptr[i] = Value();
}
}
else if (func->vararg)
{
sptr[func->locals-1] = this->NewArray();
auto arr = &sptr[func->locals-1]._array->data;
arr->resize(args - func->args);
for (int i = args-1; i >= 0; i--)
{
if (i < func->args)
sptr[i] = stack.Pop();
else
(*arr)[i] = stack.Pop();
}
}
else
{
for (int i = args-1; i >= 0; i--)
{
if (i < func->args)
sptr[i] = stack.Pop();
else
stack.Pop();
}
}
//go to function
return -1;
}
else if (fun->type == ValueType::NativeFunction)
{
Value* tmp = &stack.mem[stack.size()-args];
//ok fix this to be cleaner and resolve stack printing
//should just push a value to indicate that we are in a native function call
callstack.Push(std::pair<unsigned int, Closure*>(iptr, curframe));
callstack.Push(std::pair<unsigned int, Closure*>(JET_BAD_INSTRUCTION, 0));
Closure* temp = curframe;
sptr += temp->prototype->locals;
curframe = 0;
Value ret = (*fun->func)(this,tmp,args);
stack.QuickPop(args);
sptr -= temp->prototype->locals;
curframe = temp;
callstack.QuickPop(2);
stack.Push(ret);
return iptr;
}
else if (fun->type == ValueType::Object)
{
Value* tmp = &stack.mem[stack.size()-args];
Value ret;
if(fun->TryCallMetamethod("_call", tmp, args, &ret))
{
stack.QuickPop(args);
stack.Push(ret);
return iptr;
}
stack.QuickPop(args);
}
throw RuntimeException("Cannot call non function type " + std::string(fun->Type()) + "!!!");
}
Value JetContext::Execute(int iptr, Closure* frame)
{
#ifdef JET_TIME_EXECUTION
INT64 start, rate, end;
QueryPerformanceFrequency( (LARGE_INTEGER *)&rate );
QueryPerformanceCounter( (LARGE_INTEGER *)&start );
#endif
//frame and stack pointer reset
unsigned int startcallstack = this->callstack.size();
unsigned int startstack = this->stack.size();
auto startlocalstack = this->sptr;
callstack.Push(std::pair<unsigned int, Closure*>(JET_BAD_INSTRUCTION, 0));//bad value to get it to return;
curframe = frame;
//printf("Execute: Stack Ptr At: %d\n", sptr - localstack);
try
{
while(curframe && iptr < curframe->prototype->instructions.size() && iptr >= 0)
{
Instruction in = curframe->prototype->instructions[iptr];
switch(in.instruction)
{
case InstructionType::Add:
{
Value one = stack.Pop();
Value two = stack.Pop();
stack.Push(two+one);
break;
}
case InstructionType::Sub:
{
Value one = stack.Pop();
Value two = stack.Pop();
stack.Push(two-one);
break;
}
case InstructionType::Mul:
{
Value one = stack.Pop();
Value two = stack.Pop();
stack.Push(two*one);
break;
}
case InstructionType::Div:
{
Value one = stack.Pop();
Value two = stack.Pop();
stack.Push(two/one);
break;
}
case InstructionType::Modulus:
{
Value one = stack.Pop();
Value two = stack.Pop();
stack.Push(two%one);
break;
}
case InstructionType::BAnd:
{
Value one = stack.Pop();
Value two = stack.Pop();
stack.Push(two&one);
break;
}
case InstructionType::BOr:
{
Value one = stack.Pop();
Value two = stack.Pop();
stack.Push(two|one);
break;
}
case InstructionType::Xor:
{
Value one = stack.Pop();
Value two = stack.Pop();
stack.Push(two^one);
break;
}
case InstructionType::BNot:
{
Value one = stack.Pop();
stack.Push(~one);
break;
}
case InstructionType::LeftShift:
{
Value one = stack.Pop();
Value two = stack.Pop();
stack.Push(two<<one);
break;
}
case InstructionType::RightShift:
{
Value one = stack.Pop();
Value two = stack.Pop();
stack.Push(two>>one);
break;
}
case InstructionType::Incr:
{
Value one = stack.Pop();
stack.Push(one+Value(1));
break;
}
case InstructionType::Decr:
{
Value one = stack.Pop();
stack.Push(one-Value(1));
break;
}
case InstructionType::Negate:
{
Value one = stack.Pop();
stack.Push(-one);
break;
}
case InstructionType::Eq:
{
Value one = stack.Pop();
Value two = stack.Pop();
if (one == two)
stack.Push(Value(1));