-
Notifications
You must be signed in to change notification settings - Fork 0
/
bang.cpp
4905 lines (4252 loc) · 168 KB
/
bang.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
/////////////////////////////////////////////////////////////////
// Bang! language interpreter
// (C) 2015 David M. Placek
// All rights reserved, see accompanying [license.txt] file
//////////////////////////////////////////////////////////////////
#define HAVE_MUTATION 0 // enable '|>' operator; boo
#if HAVE_MUTATION
# if __GNUC__
// "Making something variable is easy. Controlling duration of constancy is the trick" - Alan Perlis
# include <pthread.h>
# warning Mutation enabled: You have strayed from the true and blessed path.
#endif
#endif
#define HAVE_DOT_OPERATOR 1
#define DOT_OPERATOR_INLINE 1
#define LCFG_KEEP_PROFILING_STATS 0
#define LCFG_OPTIMIZE_OPVV2V_WITHLIT 1
#define LCFG_USE_INDEX_OPERATOR 1
#define LCFG_HAVE_TAV_SWAP 0
#define LCFG_TRYJIT 0
#define LCFG_INTLITERAL_OPTIMIZATION LCFG_TRYJIT
/*
Keywords
fun fun! as
lookup -- (does not require apply!!!)
import
try catch
keyword-like-primitives/primitive-like-keywords
require crequire
coroutine!
yield! yield-nil!
And there are some built-in operators:
Operators
! -- apply
? -- conditional / if
: -- conditional / else
~ /not -- logical not
+ - * / -- the usual suspects for numbers
< > = <= >= -- comparison- less than, greater than, equal, lte, gte, ne
=~ <> -- not equal
<~ >~ -- gte (less than not), lte (greater than not)
# -- get stack length
/and /or -- logical and / or
. [] -- Index operator / Object message
Delimiters
; -- close current program scope
{} -- open / close matched program scope
And syntactic sugar
And there are primitives, until a better library / module system is in place.
Primitives
drop! swap! dup! nth! save-stack!
floor! random! -- these really belong in a math library
Literals
true false
*/
#include <iostream>
#include <algorithm>
#include <iterator>
#include <map>
//#include <mutex> // for threadsafe upvalue allocator
#include <stdio.h>
#include <ctype.h>
#include <limits.h>
#if defined(_WIN32)
# include <windows.h> // for load library
# if !__GNUC__
# include <codecvt> // to convert to wstring
# endif
#else
# include <dlfcn.h>
#endif
#include "bang.h"
#if HAVE_BUILTIN_ARRAY
# include "arraylib.h"
#endif
#if HAVE_BUILTIN_HASH
# include "hashlib.h"
#endif
#if HAVE_BUILTIN_MATH
# include "mathlib.h"
#endif
//~~~temporary #define for refactoring
#define TMPFACT_PROG_TO_RUNPROG(p) &((p)->getAst()->front())
#define FRIENDOF_RUNPROG friend DLLEXPORT void Bang::RunProgram( Thread* pThread, const Ast::Program* inprog, SHAREDUPVALUE inupvalues );
#define FRIENDOF_OPTIMIZE friend void Bang::OptimizeAst( std::vector<Ast::Base*>& ast, const Bang::Ast::CloseValue* upvalueChain, bool notco );
#if LCFG_TRYJIT
extern "C" {
#include "lightning.h"
}
static jit_state_t *_jit;
typedef double (*pifi)(double); /* Pointer to Int Function of Int */
class MyJitter
{
public:
MyJitter()
{
init_jit("/m/n2proj/bang//bang.exe");
}
};
static MyJitter& initjitter()
{
static MyJitter jitter;
return jitter;
}
//int main(int argc, char *argv[])
pifi jitit_increment( double constval, Bang::EOperators eop )
{
jit_node_t *in;
pifi incr;
initjitter();
_jit = jit_new_state();
jit_prolog(); /* prolog */
in = jit_arg_d(); /* in = arg */
jit_getarg_d(JIT_F0, in); /* getarg R0 */
switch( eop ) {
case Bang::kOpPlus: jit_addi_d(JIT_F0, JIT_F0, constval); break;
case Bang::kOpMinus: jit_subi_d(JIT_F0, JIT_F0, constval); break;
case Bang::kOpMult: jit_muli_d(JIT_F0, JIT_F0, constval); break;
case Bang::kOpDiv: jit_divi_d(JIT_F0, JIT_F0, constval); break;
}
jit_retr_d(JIT_F0); /* retr R0 */
incr = reinterpret_cast<pifi>(jit_emit());
jit_clear_state();
/* call the generated code, passing 5 as an argument */
//printf("%d + 1 = %d\n", 5, incr(5));
// jit_destroy_state();
// finish_jit();
return incr;
}
typedef double (*pifi_up)(void* upvals ); // , void* thread ); /* Pointer to Int Function of Int */
typedef void (*pifi_up_void)(void* pthread, void* upvals ); // , void* thread ); /* Pointer to Int Function of Int */
pifi_up jitit_increment_uv0( double constval, Bang::EOperators eop, int uvnum, bool isreg )
{
jit_node_t *in;
// jit_node_t *in2;
pifi_up incr;
initjitter();
_jit = jit_new_state();
jit_prolog(); /* prolog */
in = jit_arg(); /* in = arg */
// in2 = jit_arg(); /* in = arg */
jit_getarg(JIT_R0, in); /* getarg R0 */
// jit_getarg(JIT_R1, in2); /* getarg R0 */
if (isreg)
{
const size_t BVOffset = offsetof(Bang::Thread,r0_.v_.num); // ( &(((Bang::Upvalue*)0)->v_.v_.num) - &(*((Bang::Upvalue*)0)) );
jit_ldxi_d( JIT_F0, JIT_R0, BVOffset );
}
else
{
for ( ; uvnum > 0; --uvnum)
{
// std::cerr << "uvnum=" << uvnum << "\n";
const size_t parentOffset = offsetof( Bang::Upvalue, parent_ );
jit_ldxi( JIT_R0, JIT_R0, parentOffset );
}
const size_t BVOffset = offsetof(Bang::Upvalue,v_.v_.num); // ( &(((Bang::Upvalue*)0)->v_.v_.num) - &(*((Bang::Upvalue*)0)) );
jit_ldxi_d( JIT_F0, JIT_R0, BVOffset );
}
switch( eop ) {
case Bang::kOpPlus: jit_addi_d(JIT_F0, JIT_F0, constval); break;
case Bang::kOpMinus: jit_subi_d(JIT_F0, JIT_F0, constval); break;
case Bang::kOpMult: jit_muli_d(JIT_F0, JIT_F0, constval); break;
case Bang::kOpDiv: jit_divi_d(JIT_F0, JIT_F0, constval); break;
}
jit_retr_d(JIT_F0); /* retr R0 */
incr = reinterpret_cast<pifi_up>(jit_emit());
// // // std::cout << "disassemble; reg=" << isreg << " uvnum=" << uvnum << "\n";
// // // jit_disassemble();
// // // std::cout << "=================================\n";
jit_clear_state();
/* call the generated code, passing 5 as an argument */
//printf("%d + 1 = %d\n", 5, incr(5));
// jit_destroy_state();
// finish_jit();
return incr;
}
class Litnumop2reg
{
public:
void addOperation( double constval, Bang::EOperators eop )
{
switch( eop ) {
case Bang::kOpPlus: jit_addi_d(JIT_F0, JIT_F0, constval); break;
case Bang::kOpMinus: jit_subi_d(JIT_F0, JIT_F0, constval); break;
case Bang::kOpMult: jit_muli_d(JIT_F0, JIT_F0, constval); break;
case Bang::kOpDiv: jit_divi_d(JIT_F0, JIT_F0, constval); break;
}
}
void addReverseOperation( double constval, Bang::EOperators eop )
{
switch( eop ) {
case Bang::kOpPlus: jit_addi_d(JIT_F0, constval, JIT_F0); break;
case Bang::kOpMult: jit_muli_d(JIT_F0, constval, JIT_F0); break;
case Bang::kOpMinus:
jit_movi_d( JIT_F1, constval );
jit_subr_d(JIT_F0, JIT_F1, JIT_F0);
break;
case Bang::kOpDiv:
jit_movi_d( JIT_F1, constval );
jit_divr_d(JIT_F0, JIT_F1, JIT_F0);
break;
}
}
void loadFromUpval( Bang::NthParent uvnumP )
{
const size_t parentOffset = offsetof( Bang::Upvalue, parent_ );
jit_movr( JIT_R2, JIT_R1 );
for ( int uvnum = uvnumP.toint() ; uvnum > 0; --uvnum)
{
jit_ldxi( JIT_R2, JIT_R2, parentOffset );
}
const size_t BVOffset = offsetof(Bang::Upvalue,v_.v_.num); // ( &(((Bang::Upvalue*)0)->v_.v_.num) - &(*((Bang::Upvalue*)0)) );
jit_ldxi_d( JIT_F0, JIT_R2, BVOffset );
}
void addUpvalOp( Bang::NthParent uvnumP, Bang::EOperators eop )
{
const size_t parentOffset = offsetof( Bang::Upvalue, parent_ );
jit_movr( JIT_R2, JIT_R1 );
for ( int uvnum = uvnumP.toint() ; uvnum > 0; --uvnum)
{
jit_ldxi( JIT_R2, JIT_R2, parentOffset );
}
const size_t BVOffset = offsetof(Bang::Upvalue,v_.v_.num); // ( &(((Bang::Upvalue*)0)->v_.v_.num) - &(*((Bang::Upvalue*)0)) );
jit_ldxi_d( JIT_F1, JIT_R2, BVOffset );
switch( eop ) {
case Bang::kOpPlus: jit_addr_d(JIT_F0, JIT_F0, JIT_F1); break;
case Bang::kOpMinus: jit_subr_d(JIT_F0, JIT_F0, JIT_F1); break;
case Bang::kOpMult: jit_mulr_d(JIT_F0, JIT_F0, JIT_F1); break;
case Bang::kOpDiv: jit_divr_d(JIT_F0, JIT_F0, JIT_F1); break;
}
}
void loadFromRegister()
{
const size_t BVOffset = offsetof(Bang::Thread,r0_.v_.num); // ( &(((Bang::Upvalue*)0)->v_.v_.num) - &(*((Bang::Upvalue*)0)) );
jit_ldxi_d( JIT_F0, JIT_R0, BVOffset );
}
// R0 is pthread, R1 is Upvalue*
Litnumop2reg()
{
jit_node_t *in;
jit_node_t *in2;
initjitter();
_jit = jit_new_state();
jit_prolog(); /* prolog */
in = jit_arg(); /* in = arg */
in2 = jit_arg(); /* in = arg */
jit_getarg(JIT_R0, in); /* getarg R0 */
jit_getarg(JIT_R1, in2); /* getarg R0 */
// // // std::cout << "disassemble PROLOG AND ARGS\n";
// // // jit_disassemble();
// // // std::cout << "=================================\n";
// // //
//jit_retr_d(JIT_F0); /* retr R0 */
}
pifi_up_void closeitup() // store to pThread->r0_.v_.num
{
const size_t BVOffset = offsetof(Bang::Thread,r0_.v_.num); // ( &(((Bang::Upvalue*)0)->v_.v_.num) - &(*((Bang::Upvalue*)0)) );
jit_stxi_d( BVOffset, JIT_R0, JIT_F0 );
jit_ret();
pifi_up_void incr = reinterpret_cast<pifi_up_void>(jit_emit());
// // // std::cout << "disassemble; reg=" << isreg << " uvnum=" << uvnum << "\n";
// // // jit_disassemble();
// // // std::cout << "=================================\n";
// // //
jit_clear_state();
/* call the generated code, passing 5 as an argument */
//printf("%d + 1 = %d\n", 5, incr(5));
// jit_destroy_state();
// finish_jit();
return incr;
{
const size_t BVOffset = offsetof(Bang::Thread,r0_.v_.num); // ( &(((Bang::Upvalue*)0)->v_.v_.num) - &(*((Bang::Upvalue*)0)) );
jit_stxi_d( BVOffset, JIT_R0, JIT_F0 );
}
jit_ret();
incr = reinterpret_cast<pifi_up_void>(jit_emit());
// // // std::cout << "disassemble; reg=" << isreg << " uvnum=" << uvnum << "\n";
// // // jit_disassemble();
// // // std::cout << "=================================\n";
jit_clear_state();
/* call the generated code, passing 5 as an argument */
//printf("%d + 1 = %d\n", 5, incr(5));
// jit_destroy_state();
// finish_jit();
return incr;
}
};
pifi_up_void jitit_increment_uv0_2reg( double constval, Bang::EOperators eop, int uvnum, bool isreg )
{
}
#endif
namespace {
bool gDumpMode(false);
}
namespace Bang {
void OptimizeAst( std::vector<Bang::Ast::Base*>& ast, const Bang::Ast::CloseValue* upvalueChain, bool notco );
template< class Tp >
struct FcStack
{
FcStack<Tp>* prev;
static FcStack<Tp>* head;
};
template <class Tp>
FcStack<Tp>* FcStack<Tp>::head(nullptr);
// static int gAllocated;
template <class Tp>
struct SimpleAllocator
{
typedef Tp value_type;
SimpleAllocator(/*ctor args*/) {}
template <class T> SimpleAllocator(const SimpleAllocator<T>& other){}
template <class U> struct rebind { typedef SimpleAllocator<U> other; };
Tp* allocate(std::size_t n)
{
FcStack<Tp>* hdr;
if (FcStack<Tp>::head)
{
hdr = FcStack<Tp>::head;
FcStack<Tp>::head = hdr->prev;
}
else
{
hdr = static_cast<FcStack<Tp>*>( malloc( n * (sizeof(Tp) + sizeof(FcStack<Tp>)) ) );
// ++gAllocated;
}
Tp* mem = reinterpret_cast<Tp*>( hdr + 1 );
return mem;
}
void deallocate(Tp* p, std::size_t n)
{
FcStack<Tp>* hdr = reinterpret_cast<FcStack<Tp>*>(p);
--hdr;
static char freeOne;
if ((++freeOne & 0xF) == 0)
{
// std::cerr << "DEALLOCATE=" << gAllocated << "\n"; // FunctionClosure p=" << p << " size=" << n << " sizeof<shptr>=" <<
// sizeof(std::shared_ptr<FunctionClosure>) << " sizeof Tp=" << sizeof(Tp) << std::endl;
// --gAllocated;
free( hdr );
}
else
{
hdr->prev = FcStack<Tp>::head;
FcStack<Tp>::head = hdr;
}
}
void construct( Tp* p, const Tp& val ) { new (p) Tp(val); }
void destroy(Tp* p) { p->~Tp(); }
};
template <class T, class U>
bool operator==(const SimpleAllocator<T>& a, const SimpleAllocator<U>& b)
{
return &a == &b;
}
template <class T, class U>
bool operator!=(const SimpleAllocator<T>& a, const SimpleAllocator<U>& b)
{
return &a != &b;
}
#if LCFG_MT_SAFEISH
template <class Tp>
struct SimplestAllocator
{
typedef Tp value_type;
SimplestAllocator(/*ctor args*/) {}
template <class T> SimplestAllocator(const SimplestAllocator<T>& other){}
template <class U> struct rebind { typedef SimplestAllocator<U> other; };
Tp* allocate(std::size_t n)
{
Tp* mem = reinterpret_cast<Tp*>( ::operator new(n*sizeof(Tp)) );
return mem;
}
void deallocate(Tp* p, std::size_t n)
{
::operator delete(p);
}
void construct( Tp* p, const Tp& val ) { new (p) Tp(val); }
void destroy(Tp* p) { p->~Tp(); }
};
#endif
#if LCFG_MT_SAFEISH
SimplestAllocator< Upvalue > gUpvalAlloc;
#else
SimpleAllocator< Upvalue > gUpvalAlloc;
#endif
#if LCFG_GCPTR_STD
# define NEW_UPVAL(c,p,v) std::allocate_shared<Upvalue>( gUpvalAlloc, c, p, v )
#elif LCFG_UPVAL_SIMPLEALLOC
# if 1
# define NEW_UPVAL(c,p,v) gcptrupval( new (gUpvalAlloc.allocate(1)) Upvalue( c, p, v ) )
DLLEXPORT void GCDellocator<Upvalue>::freemem(Upvalue* p)
{
// ::operator delete(p);
gUpvalAlloc.deallocate(p, 1);
}
#endif
#else
// # define NEW_UPVAL(c,p,v) gcptrupval( new Upvalue( c, p, v ) )
# define NEW_UPVAL(c,p,v,thr) gcptrupval( new (::operator new (sizeof(Upvalue))) Upvalue( c, p, v ) )
DLLEXPORT void GCDellocator<Upvalue>::freemem(Upvalue* p)
{
::operator delete(p);
// gUpvalAlloc.deallocate(p, sizeof(Upvalue));
}
#endif
std::map<std::string,bangstring> gProgStrings;
typedef std::pair<std::string,bangstring> itsval_t;
bangstring internstring( const std::string& s )
{
if (s.length() > 32)
return bangstring(s);
auto it_interned = gProgStrings.find(s);
if (it_interned == gProgStrings.end())
{
bangstring newbs( s );
itsval_t pair( s, newbs );
gProgStrings.insert( pair );
return newbs;
}
else
{
return it_interned->second;
}
}
static const NthParent kNoParent=NthParent(INT_MAX);
namespace Ast { class CloseValue; }
namespace {
template<class T>
unsigned PtrToHash( const T& ptr )
{
return (reinterpret_cast<uintptr_t>(ptr)&0xFFF0) >> 4;
}
}
void Value::tostring( std::ostream& o ) const
{
if (type_ == kNum)
o << v_.num;
else if (type_ == kBool)
o << (v_.b ? "true" : "false");
else if (type_ == kStr)
{
o << this->tostr(); // << " :" << std::hex << this->tostr().gethash() << std::dec;
}
else if (type_ == kFun)
{
auto f = this->tofun().get();
o << "<cfun="
<< this->tofun().get()
<< ' '
<< typeid(*f).name() // dynamic type information is nice here
<< '>';
}
else if (type_ == kBoundFun)
o << "<bangfun=" << this->toboundfun()->program_ << ">";
else if (type_ == kFunPrimitive)
o << "<prim.function>";
else if (type_ == kThread)
o << "<thread=" << this->tothread().get() << ">";
else
o << "<?Value?>";
}
void Value::dump( std::ostream& o ) const
{
this->tostring(o);
}
DLLEXPORT void Stack::dump( std::ostream& o ) const
{
std::for_each
( stack_.begin(), stack_.end(),
[&]( const Value& v ) { v.dump( o ); o << "\n"; }
);
}
void indentlevel( int level, std::ostream& o )
{
if (level > 0)
{
o << " ";
indentlevel( level - 1, o );
}
}
namespace Ast { class Base; }
RunContext::RunContext()
: thread(nullptr), prev(nullptr), ppInstr(nullptr)
#if LCFG_HAVE_TRY_CATCH
,catcher(nullptr)
#endif
{}
void RunContext::rebind( const Ast::Base* const * inppInstr, SHAREDUPVALUE_CREF uv )
{
ppInstr = inppInstr;
upvalues_ = uv;
}
void RunContext::rebind( const Ast::Base* const * inppInstr )
{
ppInstr = inppInstr;
}
namespace Primitives
{
void stacklen( Stack& s, const RunContext& ctx)
{
s.push(double(s.size()));
}
void pushtype( Stack& s, const RunContext& ctx )
{
const Value& v = s.pop();
const auto t = v.type();
s.push
( t == Value::kBool ? "bool"
: t == Value::kNum ? "number"
: t == Value::kStr ? "string"
: t == Value::kFun ? "function"
: t == Value::kBoundFun ? "bangfun"
: t == Value::kFunPrimitive ? "primitive"
: "unknown"
);
}
void isfun( Stack& s, const RunContext&)
{
const Value& v = s.loc_top();
bool rc = v.isfunprim() || v.isfun() || v.isboundfun();
// s.pop_back();
s.push( rc );
}
void swap( Stack& s, const RunContext& ctx)
{
const Value& v1 = s.pop();
const Value& v2 = s.pop();
s.push( v1 );
s.push( v2 );
}
void drop( Stack& s, const RunContext& ctx)
{
s.pop_back();
}
void nth( Stack& s, const RunContext& ctx)
{
const Value& ndx = s.pop();
if (ndx.isnum())
{
const Value& found = s.nth(int(ndx.tonum()));
s.push( found );
}
}
void dup( Stack& s, const RunContext& ctx)
{
s.push( s.loc_top() );
}
void tostring( Stack& s, const RunContext& ctx )
{
const Value& v1 = s.pop();
std::ostringstream os;
v1.tostring( os );
s.push( os.str() );
}
void format2ostream( Stack& s, std::ostream& strout )
{
const Value& vfmt = s.pop();
const std::string fmt = vfmt.tostr();
const int fmtlen = fmt.size();
std::function<void(size_t)> subpar;
subpar = [&]( size_t pos ) {
using namespace std;
auto found_x = fmt.rfind( "%@", pos );
auto found_s = fmt.rfind( "%s", pos );
// auto found_u = fmt.rfind( "%u", pos );
auto found =
( found_x != string::npos ?
( found_s != string::npos
? max( found_x, found_s )
: found_x
)
: found_s
);
if (found == string::npos)
{
if (pos == string::npos)
strout << fmt;
else
strout << fmt.substr( 0, pos + 1 );
}
else
{
const Value& v = s.pop();
if (found > 0)
subpar( found - 1 );
v.tostring(strout); // << v.tostring(); // "XXX";
size_t afterParam = found + 2;
if (pos==std::string::npos)
strout << fmt.substr( afterParam ); //
else
strout << fmt.substr( afterParam, pos - afterParam + 1 );
}
};
subpar( std::string::npos );
}
void print( Stack& s, const RunContext& ctx )
{
format2ostream( s, std::cout );
}
void format( Stack& s, const RunContext& ctx )
{
std::ostringstream oss;
format2ostream( s, oss );
s.push( oss.str() );
}
void beginStackBound( Stack& s, const RunContext& ctx )
{
s.beginBound();
}
void endStackBound( Stack& s, const RunContext& ctx )
{
s.endBound();
}
} // end, namespace Primitives
DLLEXPORT void Operators::invalidOperator(const Value& v, Stack&)
{
bangerr() << "Invalid operator applied";
}
DLLEXPORT Value Operators::opThingAndValue2Value_noop( const Value& thing, const Value& other )
{
bangerr() << "Invalid/unsupported operator applied";
}
namespace { using namespace Bang;
struct NumberOps : public Bang::Operators
{
static Value gt( const Value& thing, const Value& other ) { return Bang::Value( other.tonum() > thing.tonum() ); }
static Value lt( const Value& thing, const Value& other ) { return Bang::Value( other.tonum() < thing.tonum() ); }
static Value eq( const Value& thing, const Value& other ) { return Bang::Value( other.tonum() == thing.tonum() ); }
static Value plus( const Value& thing, const Value& other ) { return Bang::Value( other.tonum() + thing.tonum() ); }
static Value mult( const Value& thing, const Value& other ) { return Bang::Value( other.tonum() * thing.tonum() ); }
static Value div( const Value& thing, const Value& other ) { return Bang::Value( other.tonum() / thing.tonum() ); }
static Value minus( const Value& thing, const Value& other ) { return Bang::Value( other.tonum() - thing.tonum() ); }
static Value modulo( const Value& thing, const Value& other ) { return Bang::Value( double((int)other.tonum() % (int)thing.tonum()) ); }
NumberOps()
{
opPlus = +
opMult = &mult;
opLt = <
opGt = >
opMinus = −
opDiv = ÷
opEq = &eq;
opModulo = &modulo;
}
} gNumberOperators; }
struct BoolOps : public Bang::Operators
{
static Bang::Value and_( const Bang::Value& thing, const Bang::Value& other ) { return Bang::Value( other.tobool() && thing.tobool() ); }
static Bang::Value or_( const Bang::Value& thing, const Bang::Value& other ) { return Bang::Value( other.tobool() || thing.tobool() ); }
BoolOps()
{
opAnd = &and_;
opOr = &or_;
}
} gBoolOperators;
struct StringOps : public Bang::Operators
{
static Bang::Value eq( const Bang::Value& sThing, const Bang::Value& sOther )
{
const bangstring& sLt = sOther.tostr();
return Value ( sLt == sThing.tostr() );
}
static Bang::Value gt( const Bang::Value& sThing, const Bang::Value& sOther )
{
const bangstring& sLt = sOther.tostr();
const bangstring& sRt = sThing.tostr();
return Value( !(sLt == sRt) && !(sLt < sRt) );
}
static Bang::Value lt( const Bang::Value& sThing, const Bang::Value& sOther )
{
const bangstring& sLt = sOther.tostr();
return Value ( sLt < sThing.tostr() );
}
static Bang::Value plus( const Bang::Value& sThing, const Bang::Value& sOther )
{
const bangstring& v2 = sThing.tostr();
const bangstring& v1 = sOther.tostr();
return Bang::Value( v1 + v2 );
}
StringOps()
{
opEq = &eq;
opLt = <
opGt = >
opPlus = +
}
} gStringOperators;
struct FunctionOps : public Bang::Operators
{
static Bang::Value eq( const Bang::Value& sThing, const Bang::Value& sOther )
{
return Value ( *(sOther.tofun()) == *(sThing.tofun()) );
}
FunctionOps()
{
opEq = &eq;
}
} gFunctionOperators;
DLLEXPORT Bang::Function:: Function()
// : operators( &gFunctionOperators )
{}
#if LCFG_KEEP_PROFILING_STATS
unsigned operatorCounts[kOpLAST];
#endif
DLLEXPORT void dumpProfilingStats()
{
#if LCFG_KEEP_PROFILING_STATS
for (int i = 0; i < kOpLAST; ++i)
{
std::cout << "op=" << i << " count=" << operatorCounts[i] << std::endl;
}
#endif
}
static Bang::Operators* opbytype[] = {
0,
&gBoolOperators,
&gNumberOperators,
&gStringOperators,
&gFunctionOperators,
&gFunctionOperators,
0,
0, // @todo: make empty op table for these
};
tfn_opThingAndValue2Value Value::getOperator( EOperators which ) const
{
const Bang::Operators* const op = opbytype[type_];
return op->ops[which];
}
Value Value::applyAndValue2Value( EOperators which, const Value& other ) const
{
#if LCFG_KEEP_PROFILING_STATS
++operatorCounts[which];
#endif
return (this->getOperator( which ))( *this, other );
}
void Value::applyCustomOperator( const bangstring& theOperator, Stack& s ) const
{
switch (type_)
{
case kNum: bangerr() << "no custom num ops"; break;
case kStr: bangerr() << "no custom string ops"; break;
case kFun: // fall through
case kBoundFun: this->tofun()->customOperator( theOperator, s ); break;
case kFunPrimitive: bangerr() << "custom operators not supported for function primitives"; break;
case kThread: bangerr() << "custom operators not supported for threads"; break;
}
}
void Value::applyIndexOperator( const Value& theIndex, Stack& s, const RunContext& ctx ) const
{
switch (type_)
{
case kNum: bangerr() << "no index num ops"; break;
case kStr: bangerr() << "no index string ops"; break;
case kFun: // fall through
case kBoundFun: this->tofun()->indexOperator( theIndex, s, ctx ); break;
case kFunPrimitive:
{
s.push( theIndex );
this->tofunprim()( s, ctx );
}
break;
case kThread: bangerr() << "index operator not supported for threads"; break;
}
}
static tfn_primitive bangprimforchar( int c )
{
return
( c == '#' ? Primitives::stacklen
// I would prefer to see these treated in a way that user defined
// operators and these guys are "on the same footing", so to speak,
// ie, so that this is all in a library or something, or they are
// defined/imported the same way a user-defined operator would be,
// e.g., they just push functions. Or something like that.
// 'stdoperators' require! import!
// I mean, I guess pushing them directly in the Rst will be "faster" than
// doing a lookup and pushing an upvalue, so that's something - especially
// for logical / comparison operators, but I'd still like to see them not be a special case
: c == '\\' ? Primitives::drop
: c == '(' ? Primitives::beginStackBound
: c == ')' ? Primitives::endStackBound
: nullptr
);
}
namespace Ast
{
class CloseValue : public Base
{
const CloseValue* pUpvalParent_;
bangstring paramName_;
unsigned subprogUseCount_;
public:
void incUseCount() { ++subprogUseCount_; }
CloseValue( const CloseValue* parent, const bangstring& name )
: Base( kCloseValue ),
pUpvalParent_( parent ),
paramName_( name ),
subprogUseCount_(0)
{}
const bangstring& valueName() const { return paramName_; }
virtual void dump( int level, std::ostream& o ) const
{
indentlevel(level, o);
o << "CloseValue(" << paramName_ << ") #" << subprogUseCount_ << " " << std::hex << PtrToHash(this) << std::dec << "\n";
}
const NthParent FindBinding( const bangstring& varName ) const
{
if (this->paramName_ == varName)
{
return NthParent(0);
}
else
{
if (!pUpvalParent_)
return kNoParent;
auto fbp = pUpvalParent_->FindBinding(varName);
return (fbp == kNoParent ) ? fbp : ++fbp;
}
}
CloseValue& nthUpvalue( NthParent n )
{
if (n == NthParent(0))
return *this;
else
return const_cast<CloseValue*>(pUpvalParent_)->nthUpvalue( --n );
}