-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathjx9_compile.c
3671 lines (3663 loc) · 121 KB
/
jx9_compile.c
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
/*
* Symisc JX9: A Highly Efficient Embeddable Scripting Engine Based on JSON.
* Copyright (C) 2012-2013, Symisc Systems http://jx9.symisc.net/
* Version 1.7.2
* For information on licensing, redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES
* please contact Symisc Systems via:
* or visit:
* http://jx9.symisc.net/
*/
/* $SymiscID: compile.c v1.7 FreeBSD 2012-12-11 21:46 stable <[email protected]> $ */
#ifndef JX9_AMALGAMATION
#include "jx9Int.h"
#endif
/*
* This file implement a thread-safe and full-reentrant compiler for the JX9 engine.
* That is, routines defined in this file takes a stream of tokens and output
* JX9 bytecode instructions.
*/
/* Forward declaration */
typedef struct LangConstruct LangConstruct;
typedef struct JumpFixup JumpFixup;
/* Block [i.e: set of statements] control flags */
#define GEN_BLOCK_LOOP 0x001 /* Loop block [i.e: for, while, ...] */
#define GEN_BLOCK_PROTECTED 0x002 /* Protected block */
#define GEN_BLOCK_COND 0x004 /* Conditional block [i.e: if(condition){} ]*/
#define GEN_BLOCK_FUNC 0x008 /* Function body */
#define GEN_BLOCK_GLOBAL 0x010 /* Global block (always set)*/
#define GEN_BLOC_NESTED_FUNC 0x020 /* Nested function body */
#define GEN_BLOCK_EXPR 0x040 /* Expression */
#define GEN_BLOCK_STD 0x080 /* Standard block */
#define GEN_BLOCK_SWITCH 0x100 /* Switch statement */
/*
* Compilation of some JX9 constructs such as if, for, while, the logical or
* (||) and logical and (&&) operators in expressions requires the
* generation of forward jumps.
* Since the destination PC target of these jumps isn't known when the jumps
* are emitted, we record each forward jump in an instance of the following
* structure. Those jumps are fixed later when the jump destination is resolved.
*/
struct JumpFixup
{
sxi32 nJumpType; /* Jump type. Either TRUE jump, FALSE jump or Unconditional jump */
sxu32 nInstrIdx; /* Instruction index to fix later when the jump destination is resolved. */
};
/*
* Each language construct is represented by an instance
* of the following structure.
*/
struct LangConstruct
{
sxu32 nID; /* Language construct ID [i.e: JX9_TKWRD_WHILE, JX9_TKWRD_FOR, JX9_TKWRD_IF...] */
ProcLangConstruct xConstruct; /* C function implementing the language construct */
};
/* Compilation flags */
#define JX9_COMPILE_SINGLE_STMT 0x001 /* Compile a single statement */
/* Token stream synchronization macros */
#define SWAP_TOKEN_STREAM(GEN, START, END)\
pTmp = GEN->pEnd;\
pGen->pIn = START;\
pGen->pEnd = END
#define UPDATE_TOKEN_STREAM(GEN)\
if( GEN->pIn < pTmp ){\
GEN->pIn++;\
}\
GEN->pEnd = pTmp
#define SWAP_DELIMITER(GEN, START, END)\
pTmpIn = GEN->pIn;\
pTmpEnd = GEN->pEnd;\
GEN->pIn = START;\
GEN->pEnd = END
#define RE_SWAP_DELIMITER(GEN)\
GEN->pIn = pTmpIn;\
GEN->pEnd = pTmpEnd
/* Flags related to expression compilation */
#define EXPR_FLAG_LOAD_IDX_STORE 0x001 /* Set the iP2 flag when dealing with the LOAD_IDX instruction */
#define EXPR_FLAG_RDONLY_LOAD 0x002 /* Read-only load, refer to the 'JX9_OP_LOAD' VM instruction for more information */
#define EXPR_FLAG_COMMA_STATEMENT 0x004 /* Treat comma expression as a single statement (used by object attributes) */
/* Forward declaration */
static sxi32 jx9CompileExpr(
jx9_gen_state *pGen, /* Code generator state */
sxi32 iFlags, /* Control flags */
sxi32 (*xTreeValidator)(jx9_gen_state *, jx9_expr_node *) /* Node validator callback.NULL otherwise */
);
/*
* Recover from a compile-time error. In other words synchronize
* the token stream cursor with the first semi-colon seen.
*/
static sxi32 jx9ErrorRecover(jx9_gen_state *pGen)
{
/* Synchronize with the next-semi-colon and avoid compiling this erroneous statement */
while( pGen->pIn < pGen->pEnd && (pGen->pIn->nType & JX9_TK_SEMI /*';'*/) == 0){
pGen->pIn++;
}
return SXRET_OK;
}
/*
* Check if the given identifier name is reserved or not.
* Return TRUE if reserved.FALSE otherwise.
*/
static int GenStateIsReservedID(SyString *pName)
{
if( pName->nByte == sizeof("null") - 1 ){
if( SyStrnicmp(pName->zString, "null", sizeof("null")-1) == 0 ){
return TRUE;
}else if( SyStrnicmp(pName->zString, "true", sizeof("true")-1) == 0 ){
return TRUE;
}
}else if( pName->nByte == sizeof("false") - 1 ){
if( SyStrnicmp(pName->zString, "false", sizeof("false")-1) == 0 ){
return TRUE;
}
}
/* Not a reserved constant */
return FALSE;
}
/*
* Check if a given token value is installed in the literal table.
*/
static sxi32 GenStateFindLiteral(jx9_gen_state *pGen, const SyString *pValue, sxu32 *pIdx)
{
SyHashEntry *pEntry;
pEntry = SyHashGet(&pGen->hLiteral, (const void *)pValue->zString, pValue->nByte);
if( pEntry == 0 ){
return SXERR_NOTFOUND;
}
*pIdx = (sxu32)SX_PTR_TO_INT(pEntry->pUserData);
return SXRET_OK;
}
/*
* Install a given constant index in the literal table.
* In order to be installed, the jx9_value must be of type string.
*/
static sxi32 GenStateInstallLiteral(jx9_gen_state *pGen,jx9_value *pObj, sxu32 nIdx)
{
if( SyBlobLength(&pObj->sBlob) > 0 ){
SyHashInsert(&pGen->hLiteral, SyBlobData(&pObj->sBlob), SyBlobLength(&pObj->sBlob), SX_INT_TO_PTR(nIdx));
}
return SXRET_OK;
}
/*
* Generate a fatal error.
*/
static sxi32 GenStateOutOfMem(jx9_gen_state *pGen)
{
jx9GenCompileError(pGen,E_ERROR,1,"Fatal, Jx9 compiler is running out of memory");
/* Abort compilation immediately */
return SXERR_ABORT;
}
/*
* Fetch a block that correspond to the given criteria from the stack of
* compiled blocks.
* Return a pointer to that block on success. NULL otherwise.
*/
static GenBlock * GenStateFetchBlock(GenBlock *pCurrent, sxi32 iBlockType, sxi32 iCount)
{
GenBlock *pBlock = pCurrent;
for(;;){
if( pBlock->iFlags & iBlockType ){
iCount--; /* Decrement nesting level */
if( iCount < 1 ){
/* Block meet with the desired criteria */
return pBlock;
}
}
/* Point to the upper block */
pBlock = pBlock->pParent;
if( pBlock == 0 || (pBlock->iFlags & (GEN_BLOCK_PROTECTED|GEN_BLOCK_FUNC)) ){
/* Forbidden */
break;
}
}
/* No such block */
return 0;
}
/*
* Initialize a freshly allocated block instance.
*/
static void GenStateInitBlock(
jx9_gen_state *pGen, /* Code generator state */
GenBlock *pBlock, /* Target block */
sxi32 iType, /* Block type [i.e: loop, conditional, function body, etc.]*/
sxu32 nFirstInstr, /* First instruction to compile */
void *pUserData /* Upper layer private data */
)
{
/* Initialize block fields */
pBlock->nFirstInstr = nFirstInstr;
pBlock->pUserData = pUserData;
pBlock->pGen = pGen;
pBlock->iFlags = iType;
pBlock->pParent = 0;
pBlock->bPostContinue = 0;
SySetInit(&pBlock->aJumpFix, &pGen->pVm->sAllocator, sizeof(JumpFixup));
SySetInit(&pBlock->aPostContFix, &pGen->pVm->sAllocator, sizeof(JumpFixup));
}
/*
* Allocate a new block instance.
* Return SXRET_OK and write a pointer to the new instantiated block
* on success.Otherwise generate a compile-time error and abort
* processing on failure.
*/
static sxi32 GenStateEnterBlock(
jx9_gen_state *pGen, /* Code generator state */
sxi32 iType, /* Block type [i.e: loop, conditional, function body, etc.]*/
sxu32 nFirstInstr, /* First instruction to compile */
void *pUserData, /* Upper layer private data */
GenBlock **ppBlock /* OUT: instantiated block */
)
{
GenBlock *pBlock;
/* Allocate a new block instance */
pBlock = (GenBlock *)SyMemBackendPoolAlloc(&pGen->pVm->sAllocator, sizeof(GenBlock));
if( pBlock == 0 ){
/* If the supplied memory subsystem is so sick that we are unable to allocate
* a tiny chunk of memory, there is no much we can do here.
*/
return GenStateOutOfMem(pGen);
}
/* Zero the structure */
SyZero(pBlock, sizeof(GenBlock));
GenStateInitBlock(&(*pGen), pBlock, iType, nFirstInstr, pUserData);
/* Link to the parent block */
pBlock->pParent = pGen->pCurrent;
/* Mark as the current block */
pGen->pCurrent = pBlock;
if( ppBlock ){
/* Write a pointer to the new instance */
*ppBlock = pBlock;
}
return SXRET_OK;
}
/*
* Release block fields without freeing the whole instance.
*/
static void GenStateReleaseBlock(GenBlock *pBlock)
{
SySetRelease(&pBlock->aPostContFix);
SySetRelease(&pBlock->aJumpFix);
}
/*
* Release a block.
*/
static void GenStateFreeBlock(GenBlock *pBlock)
{
jx9_gen_state *pGen = pBlock->pGen;
GenStateReleaseBlock(&(*pBlock));
/* Free the instance */
SyMemBackendPoolFree(&pGen->pVm->sAllocator, pBlock);
}
/*
* POP and release a block from the stack of compiled blocks.
*/
static sxi32 GenStateLeaveBlock(jx9_gen_state *pGen, GenBlock **ppBlock)
{
GenBlock *pBlock = pGen->pCurrent;
if( pBlock == 0 ){
/* No more block to pop */
return SXERR_EMPTY;
}
/* Point to the upper block */
pGen->pCurrent = pBlock->pParent;
if( ppBlock ){
/* Write a pointer to the popped block */
*ppBlock = pBlock;
}else{
/* Safely release the block */
GenStateFreeBlock(&(*pBlock));
}
return SXRET_OK;
}
/*
* Emit a forward jump.
* Notes on forward jumps
* Compilation of some JX9 constructs such as if, for, while and the logical or
* (||) and logical and (&&) operators in expressions requires the
* generation of forward jumps.
* Since the destination PC target of these jumps isn't known when the jumps
* are emitted, we record each forward jump in an instance of the following
* structure. Those jumps are fixed later when the jump destination is resolved.
*/
static sxi32 GenStateNewJumpFixup(GenBlock *pBlock, sxi32 nJumpType, sxu32 nInstrIdx)
{
JumpFixup sJumpFix;
sxi32 rc;
/* Init the JumpFixup structure */
sJumpFix.nJumpType = nJumpType;
sJumpFix.nInstrIdx = nInstrIdx;
/* Insert in the jump fixup table */
rc = SySetPut(&pBlock->aJumpFix,(const void *)&sJumpFix);
return rc;
}
/*
* Fix a forward jump now the jump destination is resolved.
* Return the total number of fixed jumps.
* Notes on forward jumps:
* Compilation of some JX9 constructs such as if, for, while and the logical or
* (||) and logical and (&&) operators in expressions requires the
* generation of forward jumps.
* Since the destination PC target of these jumps isn't known when the jumps
* are emitted, we record each forward jump in an instance of the following
* structure.Those jumps are fixed later when the jump destination is resolved.
*/
static sxu32 GenStateFixJumps(GenBlock *pBlock, sxi32 nJumpType, sxu32 nJumpDest)
{
JumpFixup *aFix;
VmInstr *pInstr;
sxu32 nFixed;
sxu32 n;
/* Point to the jump fixup table */
aFix = (JumpFixup *)SySetBasePtr(&pBlock->aJumpFix);
/* Fix the desired jumps */
for( nFixed = n = 0 ; n < SySetUsed(&pBlock->aJumpFix) ; ++n ){
if( aFix[n].nJumpType < 0 ){
/* Already fixed */
continue;
}
if( nJumpType > 0 && aFix[n].nJumpType != nJumpType ){
/* Not of our interest */
continue;
}
/* Point to the instruction to fix */
pInstr = jx9VmGetInstr(pBlock->pGen->pVm, aFix[n].nInstrIdx);
if( pInstr ){
pInstr->iP2 = nJumpDest;
nFixed++;
/* Mark as fixed */
aFix[n].nJumpType = -1;
}
}
/* Total number of fixed jumps */
return nFixed;
}
/*
* Reserve a room for a numeric constant [i.e: 64-bit integer or real number]
* in the constant table.
*/
static jx9_value * GenStateInstallNumLiteral(jx9_gen_state *pGen, sxu32 *pIdx)
{
jx9_value *pObj;
sxu32 nIdx = 0; /* cc warning */
/* Reserve a new constant */
pObj = jx9VmReserveConstObj(pGen->pVm, &nIdx);
if( pObj == 0 ){
GenStateOutOfMem(pGen);
return 0;
}
*pIdx = nIdx;
/* TODO(chems): Create a numeric table (64bit int keys) same as
* the constant string iterals table [optimization purposes].
*/
return pObj;
}
/*
* Compile a numeric [i.e: integer or real] literal.
* Notes on the integer type.
* According to the JX9 language reference manual
* Integers can be specified in decimal (base 10), hexadecimal (base 16), octal (base 8)
* or binary (base 2) notation, optionally preceded by a sign (- or +).
* To use octal notation, precede the number with a 0 (zero). To use hexadecimal
* notation precede the number with 0x. To use binary notation precede the number with 0b.
*/
static sxi32 jx9CompileNumLiteral(jx9_gen_state *pGen,sxi32 iCompileFlag)
{
SyToken *pToken = pGen->pIn; /* Raw token */
sxu32 nIdx = 0;
if( pToken->nType & JX9_TK_INTEGER ){
jx9_value *pObj;
sxi64 iValue;
iValue = jx9TokenValueToInt64(&pToken->sData);
pObj = GenStateInstallNumLiteral(&(*pGen), &nIdx);
if( pObj == 0 ){
SXUNUSED(iCompileFlag); /* cc warning */
return SXERR_ABORT;
}
jx9MemObjInitFromInt(pGen->pVm, pObj, iValue);
}else{
/* Real number */
jx9_value *pObj;
/* Reserve a new constant */
pObj = jx9VmReserveConstObj(pGen->pVm, &nIdx);
if( pObj == 0 ){
return GenStateOutOfMem(pGen);
}
jx9MemObjInitFromString(pGen->pVm, pObj, &pToken->sData);
jx9MemObjToReal(pObj);
}
/* Emit the load constant instruction */
jx9VmEmitInstr(pGen->pVm, JX9_OP_LOADC, 0, nIdx, 0, 0);
/* Node successfully compiled */
return SXRET_OK;
}
/*
* Compile a nowdoc string.
* According to the JX9 language reference manual:
*
* Nowdocs are to single-quoted strings what heredocs are to double-quoted strings.
* A nowdoc is specified similarly to a heredoc, but no parsing is done inside a nowdoc.
* The construct is ideal for embedding JX9 code or other large blocks of text without the
* need for escaping. It shares some features in common with the SGML <![CDATA[ ]]>
* construct, in that it declares a block of text which is not for parsing.
* A nowdoc is identified with the same <<< sequence used for heredocs, but the identifier
* which follows is enclosed in single quotes, e.g. <<<'EOT'. All the rules for heredoc
* identifiers also apply to nowdoc identifiers, especially those regarding the appearance
* of the closing identifier.
*/
static sxi32 jx9CompileNowdoc(jx9_gen_state *pGen,sxi32 iCompileFlag)
{
SyString *pStr = &pGen->pIn->sData; /* Constant string literal */
jx9_value *pObj;
sxu32 nIdx;
nIdx = 0; /* Prevent compiler warning */
if( pStr->nByte <= 0 ){
/* Empty string, load NULL */
jx9VmEmitInstr(pGen->pVm,JX9_OP_LOADC, 0, 0, 0, 0);
return SXRET_OK;
}
/* Reserve a new constant */
pObj = jx9VmReserveConstObj(pGen->pVm, &nIdx);
if( pObj == 0 ){
jx9GenCompileError(&(*pGen), E_ERROR, pGen->pIn->nLine, "JX9 engine is running out of memory");
SXUNUSED(iCompileFlag); /* cc warning */
return SXERR_ABORT;
}
/* No processing is done here, simply a memcpy() operation */
jx9MemObjInitFromString(pGen->pVm, pObj, pStr);
/* Emit the load constant instruction */
jx9VmEmitInstr(pGen->pVm, JX9_OP_LOADC, 0, nIdx, 0, 0);
/* Node successfully compiled */
return SXRET_OK;
}
/*
* Compile a single quoted string.
* According to the JX9 language reference manual:
*
* The simplest way to specify a string is to enclose it in single quotes (the character ' ).
* To specify a literal single quote, escape it with a backslash (\). To specify a literal
* backslash, double it (\\). All other instances of backslash will be treated as a literal
* backslash: this means that the other escape sequences you might be used to, such as \r
* or \n, will be output literally as specified rather than having any special meaning.
*
*/
JX9_PRIVATE sxi32 jx9CompileSimpleString(jx9_gen_state *pGen, sxi32 iCompileFlag)
{
SyString *pStr = &pGen->pIn->sData; /* Constant string literal */
const char *zIn, *zCur, *zEnd;
jx9_value *pObj;
sxu32 nIdx;
nIdx = 0; /* Prevent compiler warning */
/* Delimit the string */
zIn = pStr->zString;
zEnd = &zIn[pStr->nByte];
if( zIn >= zEnd ){
/* Empty string, load NULL */
jx9VmEmitInstr(pGen->pVm, JX9_OP_LOADC, 0, 0, 0, 0);
return SXRET_OK;
}
if( SXRET_OK == GenStateFindLiteral(&(*pGen), pStr, &nIdx) ){
/* Already processed, emit the load constant instruction
* and return.
*/
jx9VmEmitInstr(pGen->pVm, JX9_OP_LOADC, 0, nIdx, 0, 0);
return SXRET_OK;
}
/* Reserve a new constant */
pObj = jx9VmReserveConstObj(pGen->pVm, &nIdx);
if( pObj == 0 ){
jx9GenCompileError(&(*pGen), E_ERROR, 1, "JX9 engine is running out of memory");
SXUNUSED(iCompileFlag); /* cc warning */
return SXERR_ABORT;
}
jx9MemObjInitFromString(pGen->pVm, pObj, 0);
/* Compile the node */
for(;;){
if( zIn >= zEnd ){
/* End of input */
break;
}
zCur = zIn;
while( zIn < zEnd && zIn[0] != '\\' ){
zIn++;
}
if( zIn > zCur ){
/* Append raw contents*/
jx9MemObjStringAppend(pObj, zCur, (sxu32)(zIn-zCur));
}
zIn++;
if( zIn < zEnd ){
if( zIn[0] == '\\' ){
/* A literal backslash */
jx9MemObjStringAppend(pObj, "\\", sizeof(char));
}else if( zIn[0] == '\'' ){
/* A single quote */
jx9MemObjStringAppend(pObj, "'", sizeof(char));
}else{
/* verbatim copy */
zIn--;
jx9MemObjStringAppend(pObj, zIn, sizeof(char)*2);
zIn++;
}
}
/* Advance the stream cursor */
zIn++;
}
/* Emit the load constant instruction */
jx9VmEmitInstr(pGen->pVm, JX9_OP_LOADC, 0, nIdx, 0, 0);
if( pStr->nByte < 1024 ){
/* Install in the literal table */
GenStateInstallLiteral(pGen, pObj, nIdx);
}
/* Node successfully compiled */
return SXRET_OK;
}
/*
* Process variable expression [i.e: "$var", "${var}"] embedded in a double quoted/heredoc string.
* According to the JX9 language reference manual
* When a string is specified in double quotes or with heredoc, variables are parsed within it.
* There are two types of syntax: a simple one and a complex one. The simple syntax is the most
* common and convenient. It provides a way to embed a variable, an array value, or an object
* property in a string with a minimum of effort.
* Simple syntax
* If a dollar sign ($) is encountered, the parser will greedily take as many tokens as possible
* to form a valid variable name. Enclose the variable name in curly braces to explicitly specify
* the end of the name.
* Similarly, an array index or an object property can be parsed. With array indices, the closing
* square bracket (]) marks the end of the index. The same rules apply to object properties
* as to simple variables.
* Complex (curly) syntax
* This isn't called complex because the syntax is complex, but because it allows for the use
* of complex expressions.
* Any scalar variable, array element or object property with a string representation can be
* included via this syntax. Simply write the expression the same way as it would appear outside
* the string, and then wrap it in { and }. Since { can not be escaped, this syntax will only
* be recognised when the $ immediately follows the {. Use {\$ to get a literal {$
*/
static sxi32 GenStateProcessStringExpression(
jx9_gen_state *pGen, /* Code generator state */
const char *zIn, /* Raw expression */
const char *zEnd /* End of the expression */
)
{
SyToken *pTmpIn, *pTmpEnd;
SySet sToken;
sxi32 rc;
/* Initialize the token set */
SySetInit(&sToken, &pGen->pVm->sAllocator, sizeof(SyToken));
/* Preallocate some slots */
SySetAlloc(&sToken, 0x08);
/* Tokenize the text */
jx9Tokenize(zIn,(sxu32)(zEnd-zIn),&sToken);
/* Swap delimiter */
pTmpIn = pGen->pIn;
pTmpEnd = pGen->pEnd;
pGen->pIn = (SyToken *)SySetBasePtr(&sToken);
pGen->pEnd = &pGen->pIn[SySetUsed(&sToken)];
/* Compile the expression */
rc = jx9CompileExpr(&(*pGen), 0, 0);
/* Restore token stream */
pGen->pIn = pTmpIn;
pGen->pEnd = pTmpEnd;
/* Release the token set */
SySetRelease(&sToken);
/* Compilation result */
return rc;
}
/*
* Reserve a new constant for a double quoted/heredoc string.
*/
static jx9_value * GenStateNewStrObj(jx9_gen_state *pGen,sxi32 *pCount)
{
jx9_value *pConstObj;
sxu32 nIdx = 0;
/* Reserve a new constant */
pConstObj = jx9VmReserveConstObj(pGen->pVm, &nIdx);
if( pConstObj == 0 ){
GenStateOutOfMem(&(*pGen));
return 0;
}
(*pCount)++;
jx9MemObjInitFromString(pGen->pVm, pConstObj, 0);
/* Emit the load constant instruction */
jx9VmEmitInstr(pGen->pVm, JX9_OP_LOADC, 0, nIdx, 0, 0);
return pConstObj;
}
/*
* Compile a double quoted/heredoc string.
* According to the JX9 language reference manual
* Heredoc
* A third way to delimit strings is the heredoc syntax: <<<. After this operator, an identifier
* is provided, then a newline. The string itself follows, and then the same identifier again
* to close the quotation.
* The closing identifier must begin in the first column of the line. Also, the identifier must
* follow the same naming rules as any other label in JX9: it must contain only alphanumeric
* characters and underscores, and must start with a non-digit character or underscore.
* Warning
* It is very important to note that the line with the closing identifier must contain
* no other characters, except possibly a semicolon (;). That means especially that the identifier
* may not be indented, and there may not be any spaces or tabs before or after the semicolon.
* It's also important to realize that the first character before the closing identifier must
* be a newline as defined by the local operating system. This is \n on UNIX systems, including Mac OS X.
* The closing delimiter (possibly followed by a semicolon) must also be followed by a newline.
* If this rule is broken and the closing identifier is not "clean", it will not be considered a closing
* identifier, and JX9 will continue looking for one. If a proper closing identifier is not found before
* the end of the current file, a parse error will result at the last line.
* Heredocs can not be used for initializing object properties.
* Double quoted
* If the string is enclosed in double-quotes ("), JX9 will interpret more escape sequences for special characters:
* Escaped characters Sequence Meaning
* \n linefeed (LF or 0x0A (10) in ASCII)
* \r carriage return (CR or 0x0D (13) in ASCII)
* \t horizontal tab (HT or 0x09 (9) in ASCII)
* \v vertical tab (VT or 0x0B (11) in ASCII)
* \f form feed (FF or 0x0C (12) in ASCII)
* \\ backslash
* \$ dollar sign
* \" double-quote
* \[0-7]{1, 3} the sequence of characters matching the regular expression is a character in octal notation
* \x[0-9A-Fa-f]{1, 2} the sequence of characters matching the regular expression is a character in hexadecimal notation
* As in single quoted strings, escaping any other character will result in the backslash being printed too.
* The most important feature of double-quoted strings is the fact that variable names will be expanded.
* See string parsing for details.
*/
static sxi32 GenStateCompileString(jx9_gen_state *pGen)
{
SyString *pStr = &pGen->pIn->sData; /* Raw token value */
const char *zIn, *zCur, *zEnd;
jx9_value *pObj = 0;
sxi32 iCons;
sxi32 rc;
/* Delimit the string */
zIn = pStr->zString;
zEnd = &zIn[pStr->nByte];
if( zIn >= zEnd ){
/* Empty string, load NULL */
jx9VmEmitInstr(pGen->pVm, JX9_OP_LOADC, 0, 0, 0, 0);
return SXRET_OK;
}
zCur = 0;
/* Compile the node */
iCons = 0;
for(;;){
zCur = zIn;
while( zIn < zEnd && zIn[0] != '\\' ){
if(zIn[0] == '$' && &zIn[1] < zEnd &&
(((unsigned char)zIn[1] >= 0xc0 || SyisAlpha(zIn[1]) || zIn[1] == '_')) ){
break;
}
zIn++;
}
if( zIn > zCur ){
if( pObj == 0 ){
pObj = GenStateNewStrObj(&(*pGen), &iCons);
if( pObj == 0 ){
return SXERR_ABORT;
}
}
jx9MemObjStringAppend(pObj, zCur, (sxu32)(zIn-zCur));
}
if( zIn >= zEnd ){
break;
}
if( zIn[0] == '\\' ){
const char *zPtr = 0;
sxu32 n;
zIn++;
if( zIn >= zEnd ){
break;
}
if( pObj == 0 ){
pObj = GenStateNewStrObj(&(*pGen), &iCons);
if( pObj == 0 ){
return SXERR_ABORT;
}
}
n = sizeof(char); /* size of conversion */
switch( zIn[0] ){
case '$':
/* Dollar sign */
jx9MemObjStringAppend(pObj, "$", sizeof(char));
break;
case '\\':
/* A literal backslash */
jx9MemObjStringAppend(pObj, "\\", sizeof(char));
break;
case 'a':
/* The "alert" character (BEL)[ctrl+g] ASCII code 7 */
jx9MemObjStringAppend(pObj, "\a", sizeof(char));
break;
case 'b':
/* Backspace (BS)[ctrl+h] ASCII code 8 */
jx9MemObjStringAppend(pObj, "\b", sizeof(char));
break;
case 'f':
/* Form-feed (FF)[ctrl+l] ASCII code 12 */
jx9MemObjStringAppend(pObj, "\f", sizeof(char));
break;
case 'n':
/* Line feed(new line) (LF)[ctrl+j] ASCII code 10 */
jx9MemObjStringAppend(pObj, "\n", sizeof(char));
break;
case 'r':
/* Carriage return (CR)[ctrl+m] ASCII code 13 */
jx9MemObjStringAppend(pObj, "\r", sizeof(char));
break;
case 't':
/* Horizontal tab (HT)[ctrl+i] ASCII code 9 */
jx9MemObjStringAppend(pObj, "\t", sizeof(char));
break;
case 'v':
/* Vertical tab(VT)[ctrl+k] ASCII code 11 */
jx9MemObjStringAppend(pObj, "\v", sizeof(char));
break;
case '\'':
/* Single quote */
jx9MemObjStringAppend(pObj, "'", sizeof(char));
break;
case '"':
/* Double quote */
jx9MemObjStringAppend(pObj, "\"", sizeof(char));
break;
case '0':
/* NUL byte */
jx9MemObjStringAppend(pObj, "\0", sizeof(char));
break;
case 'x':
if((unsigned char)zIn[1] < 0xc0 && SyisHex(zIn[1]) ){
int c;
/* Hex digit */
c = SyHexToint(zIn[1]) << 4;
if( &zIn[2] < zEnd ){
c += SyHexToint(zIn[2]);
}
/* Output char */
jx9MemObjStringAppend(pObj, (const char *)&c, sizeof(char));
n += sizeof(char) * 2;
}else{
/* Output literal character */
jx9MemObjStringAppend(pObj, "x", sizeof(char));
}
break;
case 'o':
if( &zIn[1] < zEnd && (unsigned char)zIn[1] < 0xc0 && SyisDigit(zIn[1]) && (zIn[1] - '0') < 8 ){
/* Octal digit stream */
int c;
c = 0;
zIn++;
for( zPtr = zIn ; zPtr < &zIn[3*sizeof(char)] ; zPtr++ ){
if( zPtr >= zEnd || (unsigned char)zPtr[0] >= 0xc0 || !SyisDigit(zPtr[0]) || (zPtr[0] - '0') > 7 ){
break;
}
c = c * 8 + (zPtr[0] - '0');
}
if ( c > 0 ){
jx9MemObjStringAppend(pObj, (const char *)&c, sizeof(char));
}
n = (sxu32)(zPtr-zIn);
}else{
/* Output literal character */
jx9MemObjStringAppend(pObj, "o", sizeof(char));
}
break;
default:
/* Output without a slash */
jx9MemObjStringAppend(pObj, zIn, sizeof(char));
break;
}
/* Advance the stream cursor */
zIn += n;
continue;
}
if( zIn[0] == '{' ){
/* Curly syntax */
const char *zExpr;
sxi32 iNest = 1;
zIn++;
zExpr = zIn;
/* Synchronize with the next closing curly braces */
while( zIn < zEnd ){
if( zIn[0] == '{' ){
/* Increment nesting level */
iNest++;
}else if(zIn[0] == '}' ){
/* Decrement nesting level */
iNest--;
if( iNest <= 0 ){
break;
}
}
zIn++;
}
/* Process the expression */
rc = GenStateProcessStringExpression(&(*pGen),zExpr,zIn);
if( rc == SXERR_ABORT ){
return SXERR_ABORT;
}
if( rc != SXERR_EMPTY ){
++iCons;
}
if( zIn < zEnd ){
/* Jump the trailing curly */
zIn++;
}
}else{
/* Simple syntax */
const char *zExpr = zIn;
/* Assemble variable name */
for(;;){
/* Jump leading dollars */
while( zIn < zEnd && zIn[0] == '$' ){
zIn++;
}
for(;;){
while( zIn < zEnd && (unsigned char)zIn[0] < 0xc0 && (SyisAlphaNum(zIn[0]) || zIn[0] == '_' ) ){
zIn++;
}
if((unsigned char)zIn[0] >= 0xc0 ){
/* UTF-8 stream */
zIn++;
while( zIn < zEnd && (((unsigned char)zIn[0] & 0xc0) == 0x80) ){
zIn++;
}
continue;
}
break;
}
if( zIn >= zEnd ){
break;
}
if( zIn[0] == '[' ){
sxi32 iSquare = 1;
zIn++;
while( zIn < zEnd ){
if( zIn[0] == '[' ){
iSquare++;
}else if (zIn[0] == ']' ){
iSquare--;
if( iSquare <= 0 ){
break;
}
}
zIn++;
}
if( zIn < zEnd ){
zIn++;
}
break;
}else if( zIn[0] == '.' ){
/* Member access operator '.' */
zIn++;
}else{
break;
}
}
/* Process the expression */
rc = GenStateProcessStringExpression(&(*pGen),zExpr, zIn);
if( rc == SXERR_ABORT ){
return SXERR_ABORT;
}
if( rc != SXERR_EMPTY ){
++iCons;
}
}
/* Invalidate the previously used constant */
pObj = 0;
}/*for(;;)*/
if( iCons > 1 ){
/* Concatenate all compiled constants */
jx9VmEmitInstr(pGen->pVm, JX9_OP_CAT, iCons, 0, 0, 0);
}
/* Node successfully compiled */
return SXRET_OK;
}
/*
* Compile a double quoted string.
* See the block-comment above for more information.
*/
JX9_PRIVATE sxi32 jx9CompileString(jx9_gen_state *pGen, sxi32 iCompileFlag)
{
sxi32 rc;
rc = GenStateCompileString(&(*pGen));
SXUNUSED(iCompileFlag); /* cc warning */
/* Compilation result */
return rc;
}
/*
* Compile a literal which is an identifier(name) for simple values.
*/
JX9_PRIVATE sxi32 jx9CompileLiteral(jx9_gen_state *pGen,sxi32 iCompileFlag)
{
SyToken *pToken = pGen->pIn;
jx9_value *pObj;
SyString *pStr;
sxu32 nIdx;
/* Extract token value */
pStr = &pToken->sData;
/* Deal with the reserved literals [i.e: null, false, true, ...] first */
if( pStr->nByte == sizeof("NULL") - 1 ){
if( SyStrnicmp(pStr->zString, "null", sizeof("NULL")-1) == 0 ){
/* NULL constant are always indexed at 0 */
jx9VmEmitInstr(pGen->pVm, JX9_OP_LOADC, 0, 0, 0, 0);
return SXRET_OK;
}else if( SyStrnicmp(pStr->zString, "true", sizeof("TRUE")-1) == 0 ){
/* TRUE constant are always indexed at 1 */
jx9VmEmitInstr(pGen->pVm, JX9_OP_LOADC, 0, 1, 0, 0);
return SXRET_OK;
}
}else if (pStr->nByte == sizeof("FALSE") - 1 &&
SyStrnicmp(pStr->zString, "false", sizeof("FALSE")-1) == 0 ){
/* FALSE constant are always indexed at 2 */
jx9VmEmitInstr(pGen->pVm, JX9_OP_LOADC, 0, 2, 0, 0);
return SXRET_OK;
}else if(pStr->nByte == sizeof("__LINE__") - 1 &&
SyMemcmp(pStr->zString, "__LINE__", sizeof("__LINE__")-1) == 0 ){
/* TICKET 1433-004: __LINE__ constant must be resolved at compile time, not run time */
pObj = jx9VmReserveConstObj(pGen->pVm, &nIdx);
if( pObj == 0 ){
SXUNUSED(iCompileFlag); /* cc warning */
return GenStateOutOfMem(pGen);
}
jx9MemObjInitFromInt(pGen->pVm, pObj, pToken->nLine);
/* Emit the load constant instruction */
jx9VmEmitInstr(pGen->pVm, JX9_OP_LOADC, 0, nIdx, 0, 0);
return SXRET_OK;
}else if( pStr->nByte == sizeof("__FUNCTION__") - 1 &&
SyMemcmp(pStr->zString, "__FUNCTION__", sizeof("__FUNCTION__")-1) == 0 ){
GenBlock *pBlock = pGen->pCurrent;
/* TICKET 1433-004: __FUNCTION__/__METHOD__ constants must be resolved at compile time, not run time */
while( pBlock && (pBlock->iFlags & GEN_BLOCK_FUNC) == 0 ){
/* Point to the upper block */
pBlock = pBlock->pParent;
}
if( pBlock == 0 ){
/* Called in the global scope, load NULL */
jx9VmEmitInstr(pGen->pVm, JX9_OP_LOADC, 0, 0, 0, 0);
}else{
/* Extract the target function/method */
jx9_vm_func *pFunc = (jx9_vm_func *)pBlock->pUserData;
pObj = jx9VmReserveConstObj(pGen->pVm, &nIdx);
if( pObj == 0 ){
return GenStateOutOfMem(pGen);
}
jx9MemObjInitFromString(pGen->pVm, pObj, &pFunc->sName);
/* Emit the load constant instruction */
jx9VmEmitInstr(pGen->pVm, JX9_OP_LOADC, 0, nIdx, 0, 0);
}
return SXRET_OK;
}
/* Query literal table */
if( SXRET_OK != GenStateFindLiteral(&(*pGen), &pToken->sData, &nIdx) ){
jx9_value *pObj;
/* Unknown literal, install it in the literal table */
pObj = jx9VmReserveConstObj(pGen->pVm, &nIdx);
if( pObj == 0 ){
return GenStateOutOfMem(pGen);
}
jx9MemObjInitFromString(pGen->pVm, pObj, &pToken->sData);
GenStateInstallLiteral(&(*pGen), pObj, nIdx);
}
/* Emit the load constant instruction */
jx9VmEmitInstr(pGen->pVm,JX9_OP_LOADC,1,nIdx, 0, 0);
/* Node successfully compiled */
return SXRET_OK;
}
/*
* Compile an array entry whether it is a key or a value.
*/
static sxi32 GenStateCompileJSONEntry(
jx9_gen_state *pGen, /* Code generator state */
SyToken *pIn, /* Token stream */
SyToken *pEnd, /* End of the token stream */
sxi32 iFlags, /* Compilation flags */
sxi32 (*xValidator)(jx9_gen_state *,jx9_expr_node *) /* Expression tree validator callback */
)
{
SyToken *pTmpIn, *pTmpEnd;
sxi32 rc;
/* Swap token stream */
SWAP_DELIMITER(pGen, pIn, pEnd);
/* Compile the expression*/
rc = jx9CompileExpr(&(*pGen), iFlags, xValidator);
/* Restore token stream */
RE_SWAP_DELIMITER(pGen);
return rc;
}
/*
* Compile a Jx9 JSON Array.
*/
JX9_PRIVATE sxi32 jx9CompileJsonArray(jx9_gen_state *pGen, sxi32 iCompileFlag)
{
sxi32 nPair = 0;
SyToken *pCur;
sxi32 rc;
pGen->pIn++; /* Jump the open square bracket '['*/
pGen->pEnd--;
SXUNUSED(iCompileFlag); /* cc warning */
for(;;){