/
sc1.cpp
6334 lines (5754 loc) · 193 KB
/
sc1.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
/* vim: set sts=2 ts=8 sw=2 tw=99 et: */
/* Pawn compiler
*
* Function and variable definition and declaration, statement parser.
*
* Copyright (c) ITB CompuPhase, 1997-2006
*
* This software is provided "as-is", without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from
* the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software in
* a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*
* Version: $Id$
*/
#include <assert.h>
#include <ctype.h>
#include <limits.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <amtl/am-unused.h>
#include <amtl/am-platform.h>
#include "types.h"
#if defined __WIN32__ || defined _WIN32 || defined __MSDOS__
#include <conio.h>
#include <io.h>
#endif
#if defined LINUX || defined __FreeBSD__ || defined __OpenBSD__ || defined DARWIN
#include "sclinux.h"
#include "binreloc.h" /* from BinReloc, see www.autopackage.org */
#include <unistd.h>
#endif
#if defined FORTIFY
#include <alloc/fortify.h>
#endif
#if defined __BORLANDC__ || defined __WATCOMC__
#include <dos.h>
static unsigned total_drives; /* dummy variable */
#define dos_setdrive(i) _dos_setdrive(i,&total_drives)
#elif defined _MSC_VER && defined _WIN32
#include <direct.h> /* for _chdrive() */
#define dos_setdrive(i) _chdrive(i)
#endif
#if defined __BORLANDC__
#include <dir.h> /* for chdir() */
#elif defined __WATCOMC__
#include <direct.h> /* for chdir() */
#endif
#if defined __WIN32__ || defined _WIN32 || defined _Windows
#include <windows.h>
#endif
#include <time.h>
#if defined(SOURCEMOD_BUILD)
# include <sourcemod_version.h>
# define SOURCEPAWN_VERSION SOURCEMOD_VERSION
#endif
#ifdef __EMSCRIPTEN__
# include <emscripten.h>
#endif
#include "lstring.h"
#include "sc.h"
#include "sctracker.h"
#include "sp_symhash.h"
#define VERSION_STR "3.2.3636"
#define VERSION_INT 0x0302
int pc_anytag = 0;
int pc_functag = 0;
int pc_tag_string = 0;
int pc_tag_void = 0;
int pc_tag_object = 0;
int pc_tag_bool = 0;
int pc_tag_null_t = 0;
int pc_tag_nullfunc_t = 0;
int pc_code_version = 0;
bool pc_must_drop_stack = true;
static void resetglobals(void);
static void initglobals(void);
static char *get_extension(char *filename);
static void setopt(int argc,char **argv,char *oname,char *ename,char *pname,
char *codepage);
static void setconfig(char *root);
static void setcaption(void);
static void about(void);
static void setconstants(void);
static void parse(void);
static void dumplits(void);
static void dumpzero(int count);
static void declglb(declinfo_t *decl,int fpublic,int fstatic,int stock);
static void declstructvar(char *firstname,int fpublic, pstruct_t *pstruct);
static void declloc(int tokid);
static void dodelete();
static void decl_const(int table);
static void declstruct();
static void decl_enum(int table);
static cell needsub(int *tag,constvalue **enumroot);
static void initials(int ident,int tag,cell *size,int dim[],int numdim,
constvalue *enumroot);
static cell initarray(int ident,int tag,int dim[],int numdim,int cur,
int startlit,int counteddim[],constvalue *lastdim,
constvalue *enumroot,int *errorfound);
static cell initvector(int ident,int tag,cell size,int fillzero,
constvalue *enumroot,int *errorfound);
static void initials3(declinfo_t *decl);
static cell fix_char_size(declinfo_t *decl);
static cell init(int ident,int *tag,int *errorfound);
static symbol *funcstub(int tokid, declinfo_t *decl, const int *thistag);
static int newfunc(declinfo_t *decl, const int *thistag, int fpublic, int fstatic, int stock, symbol **symp);
static int declargs(symbol *sym, int chkshadow, const int *thistag);
static void doarg(symbol *sym, declinfo_t *decl, int offset, int chkshadow, arginfo *arg);
static void reduce_referrers(symbol *root);
static int testsymbols(symbol *root,int level,int testlabs,int testconst);
static void destructsymbols(symbol *root,int level);
static void statement(int *lastindent,int allow_decl);
static void compound(int stmt_sameline);
static int test(int label,int parens,int invert);
static int doexpr(int comma,int chkeffect,int allowarray,int mark_endexpr,
int *tag,symbol **symptr,int chkfuncresult);
static int doexpr2(int comma,int chkeffect,int allowarray,int mark_endexpr,
int *tag,symbol **symptr,int chkfuncresult,value *lval);
static void doassert(void);
static void doexit(void);
static int doif(void);
static int dowhile(void);
static int dodo(void);
static int dofor(void);
static int doswitch(void);
static void doreturn(void);
static void dotypedef();
static void dotypeset();
static void domethodmap(LayoutSpec spec);
static bool dousing();
static void dobreak(void);
static void docont(void);
static void dosleep(void);
static void addwhile(int *ptr);
static void delwhile(void);
static int *readwhile(void);
static void inst_datetime_defines(void);
static void inst_binary_name(char *binfname);
static int operatorname(char *name);
static int parse_new_typename(const token_t *tok);
static int parse_new_decl(declinfo_t *decl, const token_t *first, int flags);
static int reparse_old_decl(declinfo_t *decl, int flags);
static int reparse_new_decl(declinfo_t *decl, int flags);
static void check_void_decl(const declinfo_t *decl, int variable);
enum {
TEST_PLAIN, /* no parentheses */
TEST_PARENS, /* '(' <expr> ')' */
TEST_OPT, /* '(' <expr> ')' or <expr> */
};
static int norun = 0; /* the compiler never ran */
static int autozero = 1; /* if 1 will zero out the variable, if 0 omit the zeroing */
static int lastst = 0; /* last executed statement type */
static int nestlevel = 0; /* number of active (open) compound statements */
static int endlessloop= 0; /* nesting level of endless loop */
static int rettype = 0; /* the type that a "return" expression should have */
static int skipinput = 0; /* number of lines to skip from the first input file */
static int verbosity = 1; /* verbosity level, 0=quiet, 1=normal, 2=verbose */
static int sc_reparse = 0; /* needs 3th parse because of changed prototypes? */
static int sc_parsenum = 0; /* number of the extra parses */
static int wq[wqTABSZ]; /* "while queue", internal stack for nested loops */
static int *wqptr; /* pointer to next entry */
#if !defined SC_LIGHT
static char sc_rootpath[_MAX_PATH];
static char *sc_documentation=NULL;/* main documentation */
#endif
#if defined __WIN32__ || defined _WIN32 || defined _Windows
static HWND hwndFinish = 0;
#endif
int glbstringread = 0;
char g_tmpfile[_MAX_PATH] = {0};
/* "main" of the compiler
*/
int pc_compile(int argc, char *argv[])
{
#ifdef __EMSCRIPTEN__
EM_ASM(
if (ENVIRONMENT_IS_NODE) {
FS.mkdir('/fakeroot');
FS.mount(NODEFS, { root: '/' }, '/fakeroot');
FS.chdir('/fakeroot/' + process.cwd());
}
);
#endif
int entry,i,jmpcode;
int retcode;
char incfname[_MAX_PATH];
char codepage[MAXCODEPAGE+1];
void *inpfmark;
int lcl_packstr,lcl_needsemicolon,lcl_tabsize,lcl_require_newdecls;
char *ptr;
/* set global variables to their initial value */
initglobals();
errorset(sRESET,0);
errorset(sEXPRRELEASE,0);
lexinit();
/* make sure that we clean up on a fatal error; do this before the first
* call to error(). */
if ((jmpcode=setjmp(errbuf))!=0)
goto cleanup;
sp_Globals = NewHashTable();
if (!sp_Globals)
error(FATAL_ERROR_OOM);
/* allocate memory for fixed tables */
inpfname=(char*)malloc(_MAX_PATH);
if (inpfname==NULL)
error(FATAL_ERROR_OOM); /* insufficient memory */
litq=(cell*)malloc(litmax*sizeof(cell));
if (litq==NULL)
error(FATAL_ERROR_OOM); /* insufficient memory */
if (!phopt_init())
error(FATAL_ERROR_OOM); /* insufficient memory */
setopt(argc,argv,outfname,errfname,incfname,codepage);
strcpy(binfname,outfname);
ptr=get_extension(binfname);
if (ptr!=NULL && stricmp(ptr,".asm")==0)
set_extension(binfname,".smx",TRUE);
else
set_extension(binfname,".smx",FALSE);
/* set output names that depend on the input name */
if (sc_listing)
set_extension(outfname,".lst",TRUE);
else
set_extension(outfname,".asm",TRUE);
if (strlen(errfname)!=0)
remove(errfname); /* delete file on startup */
else if (verbosity>0)
setcaption();
setconfig(argv[0]); /* the path to the include and codepage files */
sc_ctrlchar_org=sc_ctrlchar;
lcl_packstr=sc_packstr;
lcl_needsemicolon=sc_needsemicolon;
lcl_require_newdecls=sc_require_newdecls;
lcl_tabsize=sc_tabsize;
#if !defined NO_CODEPAGE
if (!cp_set(codepage)) /* set codepage */
error(FATAL_ERROR_NO_CODEPAGE);
#endif
/* optionally create a temporary input file that is a collection of all
* input files
*/
assert(get_sourcefile(0)!=NULL); /* there must be at least one source file */
if (get_sourcefile(1)!=NULL) {
/* there are at least two or more source files */
char *tname,*sname;
void *ftmp,*fsrc;
int fidx;
#if defined __WIN32__ || defined _WIN32
tname=_tempnam(NULL,"pawn");
#elif defined __MSDOS__ || defined _Windows
tname=tempnam(NULL,"pawn");
#elif defined(MACOS) && !defined(__MACH__)
/* tempnam is not supported for the Macintosh CFM build. */
error(FATAL_ERROR_INVALID_INSN,get_sourcefile(1));
tname=NULL;
sname=NULL;
#else
char *buffer = strdup(P_tmpdir "/pawn.XXXXXX");
close(mkstemp(buffer));
tname=buffer;
#endif
ftmp=pc_createsrc(tname);
for (fidx=0; (sname=get_sourcefile(fidx))!=NULL; fidx++) {
unsigned char tstring[128];
fsrc=pc_opensrc(sname);
if (fsrc==NULL) {
pc_closesrc(ftmp);
remove(tname);
strcpy(inpfname,sname); /* avoid invalid filename */
error(FATAL_ERROR_READ,sname);
} /* if */
pc_writesrc(ftmp,(unsigned char*)"#file \"");
pc_writesrc(ftmp,(unsigned char*)sname);
pc_writesrc(ftmp,(unsigned char*)"\"\n");
while (!pc_eofsrc(fsrc) && pc_readsrc(fsrc,tstring,sizeof tstring)) {
pc_writesrc(ftmp,tstring);
} /* while */
pc_closesrc(fsrc);
} /* for */
pc_closesrc(ftmp);
strcpy(inpfname,tname);
strcpy(g_tmpfile,tname);
free(tname);
} else {
strcpy(inpfname,get_sourcefile(0));
} /* if */
inpf_org=pc_opensrc(inpfname);
if (inpf_org==NULL)
error(FATAL_ERROR_READ,inpfname);
freading=TRUE;
outf=(FILE*)pc_openasm(outfname); /* first write to assembler file (may be temporary) */
if (outf==NULL)
error(FATAL_ERROR_WRITE,outfname);
setconstants(); /* set predefined constants and tagnames */
for (i=0; i<skipinput; i++) /* skip lines in the input file */
if (pc_readsrc(inpf_org,pline,sLINEMAX)!=NULL)
fline++; /* keep line number up to date */
skipinput=fline;
sc_status=statFIRST;
/* write starting options (from the command line or the configuration file) */
if (sc_listing) {
char string[150];
sprintf(string,"#pragma ctrlchar 0x%02x\n"
"#pragma pack %s\n"
"#pragma semicolon %s\n"
"#pragma tabsize %d\n",
sc_ctrlchar,
sc_packstr ? "true" : "false",
sc_needsemicolon ? "true" : "false",
sc_tabsize);
pc_writeasm(outf,string);
setfiledirect(inpfname);
} /* if */
/* do the first pass through the file (or possibly two or more "first passes") */
sc_parsenum=0;
inpfmark=pc_getpossrc(inpf_org,NULL);
do {
/* reset "defined" flag of all functions and global variables */
reduce_referrers(&glbtab);
delete_symbols(&glbtab,0,TRUE,FALSE);
#if !defined NO_DEFINE
delete_substtable();
inst_datetime_defines();
inst_binary_name(binfname);
#endif
resetglobals();
gTypes.clearExtendedTypes();
pstructs_free();
funcenums_free();
methodmaps_free();
sc_ctrlchar=sc_ctrlchar_org;
sc_packstr=lcl_packstr;
sc_needsemicolon=lcl_needsemicolon;
sc_require_newdecls=lcl_require_newdecls;
sc_tabsize=lcl_tabsize;
errorset(sRESET,0);
/* reset the source file */
inpf=inpf_org;
freading=TRUE;
pc_resetsrc(inpf,inpfmark); /* reset file position */
fline=skipinput; /* reset line number */
sc_reparse=FALSE; /* assume no extra passes */
sc_status=statFIRST; /* resetglobals() resets it to IDLE */
/* look for default prefix (include) file in include paths,
* but only error if it was manually set on the command line
*/
if (strlen(incfname)>0) {
int defOK = plungefile(incfname,FALSE,TRUE);
if (!defOK && strcmp(incfname,sDEF_PREFIX)!=0) {
error(FATAL_ERROR_READ,incfname);
} /* if */
} /* if */
preprocess(); /* fetch first line */
parse(); /* process all input */
sc_parsenum++;
} while (sc_reparse);
/* second (or third) pass */
sc_status=statWRITE; /* set, to enable warnings */
if (sc_listing)
goto cleanup;
/* ??? for re-parsing the listing file instead of the original source
* file (and doing preprocessing twice):
* - close input file, close listing file
* - re-open listing file for reading (inpf)
* - open assembler file (outf)
*/
/* reset "defined" flag of all functions and global variables */
reduce_referrers(&glbtab);
delete_symbols(&glbtab,0,TRUE,FALSE);
gTypes.clearExtendedTypes();
funcenums_free();
methodmaps_free();
pstructs_free();
#if !defined NO_DEFINE
delete_substtable();
inst_datetime_defines();
inst_binary_name(binfname);
#endif
resetglobals();
sc_ctrlchar=sc_ctrlchar_org;
sc_packstr=lcl_packstr;
sc_needsemicolon=lcl_needsemicolon;
sc_require_newdecls=lcl_require_newdecls;
sc_tabsize=lcl_tabsize;
errorset(sRESET,0);
/* reset the source file */
inpf=inpf_org;
freading=TRUE;
pc_resetsrc(inpf,inpfmark); /* reset file position */
fline=skipinput; /* reset line number */
lexinit(); /* clear internal flags of lex() */
sc_status=statWRITE; /* allow to write --this variable was reset by resetglobals() */
writeleader(&glbtab);
insert_dbgfile(inpfname); /* attach to debug information */
insert_inputfile(inpfname); /* save for the error system */
if (strlen(incfname)>0) {
plungefile(incfname,FALSE,TRUE); /* parse "default.inc" (again) */
} /* if */
preprocess(); /* fetch first line */
parse(); /* process all input */
/* inpf is already closed when readline() attempts to pop of a file */
writetrailer(); /* write remaining stuff */
entry=testsymbols(&glbtab,0,TRUE,FALSE); /* test for unused or undefined
* functions and variables */
if (!entry)
error(13); /* no entry point (no public functions) */
cleanup:
if (inpf!=NULL) /* main source file is not closed, do it now */
pc_closesrc(inpf);
// Write the binary file.
if (!(sc_asmfile || sc_listing) && errnum==0 && jmpcode==0) {
pc_resetasm(outf);
assemble(binfname, outf);
}
if (outf!=NULL) {
pc_closeasm(outf,!(sc_asmfile || sc_listing));
outf=NULL;
} /* if */
#if !defined SC_LIGHT
if (errnum==0 && strlen(errfname)==0) {
if ((!norun && (sc_debug & sSYMBOLIC)!=0) || verbosity>=2) {
pc_printf("Code size: %8ld bytes\n", (long)code_idx);
pc_printf("Data size: %8ld bytes\n", (long)glb_declared*sizeof(cell));
pc_printf("Stack/heap size: %8ld bytes\n", (long)pc_stksize*sizeof(cell));
pc_printf("Total requirements:%8ld bytes\n", (long)code_idx+(long)glb_declared*sizeof(cell)+(long)pc_stksize*sizeof(cell));
} /* if */
} /* if */
#endif
if (g_tmpfile[0] != '\0') {
remove(g_tmpfile);
}
if (inpfname!=NULL) {
free(inpfname);
} /* if */
if (litq!=NULL)
free(litq);
phopt_cleanup();
stgbuffer_cleanup();
clearstk();
assert(jmpcode!=0 || loctab.next==NULL);/* on normal flow, local symbols
* should already have been deleted */
delete_symbols(&loctab,0,TRUE,TRUE); /* delete local variables if not yet
* done (i.e. on a fatal error) */
delete_symbols(&glbtab,0,TRUE,TRUE);
DestroyHashTable(sp_Globals);
delete_consttable(&libname_tab);
delete_aliastable();
delete_pathtable();
delete_sourcefiletable();
delete_inputfiletable();
delete_dbgstringtable();
gTypes.clear();
funcenums_free();
methodmaps_free();
pstructs_free();
#if !defined NO_DEFINE
delete_substtable();
#endif
#if !defined SC_LIGHT
delete_docstringtable();
if (sc_documentation!=NULL)
free(sc_documentation);
#endif
delete_autolisttable();
if (errnum!=0) {
if (strlen(errfname)==0)
pc_printf("\n%d Error%s.\n",errnum,(errnum>1) ? "s" : "");
retcode=1;
} else if (warnnum!=0){
if (strlen(errfname)==0)
pc_printf("\n%d Warning%s.\n",warnnum,(warnnum>1) ? "s" : "");
retcode=0; /* use "0", so that MAKE and similar tools continue */
} else {
retcode=jmpcode;
if (retcode==0 && verbosity>=2)
pc_printf("\nDone.\n");
} /* if */
#if defined __WIN32__ || defined _WIN32 || defined _Windows
if (IsWindow(hwndFinish))
PostMessageA(hwndFinish,RegisterWindowMessageA("PawnNotify"),retcode,0L);
#endif
#if defined FORTIFY
Fortify_ListAllMemory();
#endif
return retcode;
}
int pc_addconstant(const char *name,cell value,int tag)
{
errorset(sFORCESET,0); /* make sure error engine is silenced */
sc_status=statIDLE;
add_constant(name,value,sGLOBAL,tag);
return 1;
}
static void inst_binary_name(char *binfname)
{
size_t i, len;
char *binptr;
char newpath[512], newname[512];
binptr = NULL;
len = strlen(binfname);
for (i = len - 1; i < len; i--)
{
if (binfname[i] == '/'
#if defined WIN32 || defined _WIN32
|| binfname[i] == '\\'
#endif
)
{
binptr = &binfname[i + 1];
break;
}
}
if (binptr == NULL)
{
binptr = binfname;
}
snprintf(newpath, sizeof(newpath), "\"%s\"", binfname);
snprintf(newname, sizeof(newname), "\"%s\"", binptr);
insert_subst("__BINARY_PATH__", newpath, 15);
insert_subst("__BINARY_NAME__", newname, 15);
}
static void inst_datetime_defines(void)
{
char date[64];
char ltime[64];
time_t td;
struct tm *curtime;
time(&td);
curtime = localtime(&td);
#if defined __EMSCRIPTEN__
snprintf(date, sizeof(date), "\"%02d/%02d/%04d\"", curtime->tm_mon + 1, curtime->tm_mday, curtime->tm_year + 1900);
snprintf(ltime, sizeof(ltime), "\"%02d:%02d:%02d\"", curtime->tm_hour, curtime->tm_min, curtime->tm_sec);
#else
strftime(date, 31, "\"%m/%d/%Y\"", curtime);
strftime(ltime, 31, "\"%H:%M:%S\"", curtime);
#endif
insert_subst("__DATE__", date, 8);
insert_subst("__TIME__", ltime, 8);
}
const char *pc_typename(int tag)
{
if (tag == 0)
return "int";
if (tag == sc_rationaltag)
return "float";
if (tag == pc_tag_string)
return "char";
return pc_tagname(tag);
}
const char *pc_tagname(int tag)
{
if (Type* type = gTypes.find(tag))
return type->name();
return "__unknown__";
}
int pc_findtag(const char *name)
{
if (Type* type = gTypes.find(name))
return type->tagid();
return -1;
}
int pc_addtag(const char *name)
{
int val;
if (name==NULL) {
/* no tagname was given, check for one */
char *nameptr;
if (lex(&val,&nameptr)!=tLABEL) {
lexpush();
return 0; /* untagged */
} /* if */
name = nameptr;
} /* if */
return gTypes.defineTag(name)->tagid();
}
static void resetglobals(void)
{
/* reset the subset of global variables that is modified by the first pass */
curfunc=NULL; /* pointer to current function */
lastst=0; /* last executed statement type */
nestlevel=0; /* number of active (open) compound statements */
rettype=0; /* the type that a "return" expression should have */
litidx=0; /* index to literal table */
stgidx=0; /* index to the staging buffer */
sc_labnum=0; /* top value of (internal) labels */
staging=0; /* true if staging output */
declared=0; /* number of local cells declared */
glb_declared=0; /* number of global cells declared */
code_idx=0; /* number of bytes with generated code */
ntv_funcid=0; /* incremental number of native function */
curseg=0; /* 1 if currently parsing CODE, 2 if parsing DATA */
freading=FALSE; /* no input file ready yet */
fline=0; /* the line number in the current file */
fnumber=0; /* the file number in the file table (debugging) */
fcurrent=0; /* current file being processed (debugging) */
sc_intest=FALSE; /* true if inside a test */
sideeffect=0; /* true if an expression causes a side-effect */
stmtindent=0; /* current indent of the statement */
indent_nowarn=FALSE; /* do not skip warning "217 loose indentation" */
sc_allowtags=TRUE; /* allow/detect tagnames */
sc_status=statIDLE;
pc_addlibtable=TRUE; /* by default, add a "library table" to the output file */
pc_docexpr=FALSE;
pc_deprecate=NULL;
pc_memflags=0;
}
static void initglobals(void)
{
resetglobals();
sc_asmfile=FALSE; /* do not create .ASM file */
sc_listing=FALSE; /* do not create .LST file */
skipinput=0; /* number of lines to skip from the first input file */
sc_ctrlchar=CTRL_CHAR;/* the escape character */
litmax=sDEF_LITMAX; /* current size of the literal table */
errnum=0; /* number of errors */
warnnum=0; /* number of warnings */
verbosity=1; /* verbosity level, no copyright banner */
sc_debug=sCHKBOUNDS|sSYMBOLIC; /* sourcemod: full debug stuff */
pc_optimize=sOPTIMIZE_DEFAULT; /* sourcemod: full optimization */
sc_packstr=TRUE; /* strings are packed by default */
sc_needsemicolon=FALSE;/* semicolon required to terminate expressions? */
sc_require_newdecls = FALSE;
sc_dataalign=sizeof(cell);
pc_stksize=sDEF_AMXSTACK;/* default stack size */
sc_tabsize=8; /* assume a TAB is 8 spaces */
sc_rationaltag=0; /* assume no support for rational numbers */
rational_digits=0; /* number of fractional digits */
outfname[0]='\0'; /* output file name */
errfname[0]='\0'; /* error file name */
inpf=NULL; /* file read from */
inpfname=NULL; /* pointer to name of the file currently read from */
outf=NULL; /* file written to */
litq=NULL; /* the literal queue */
glbtab.next=NULL; /* clear global variables/constants table */
loctab.next=NULL; /* " local " / " " */
libname_tab.next=NULL;/* library table (#pragma library "..." syntax) */
pline[0]='\0'; /* the line read from the input file */
lptr=NULL; /* points to the current position in "pline" */
curlibrary=NULL; /* current library */
inpf_org=NULL; /* main source file */
wqptr=wq; /* initialize while queue pointer */
#if !defined SC_LIGHT
sc_documentation=NULL;
#endif
}
static char *get_extension(char *filename)
{
char *ptr;
assert(filename!=NULL);
ptr=strrchr(filename,'.');
if (ptr!=NULL) {
/* ignore extension on a directory or at the start of the filename */
if (strchr(ptr,DIRSEP_CHAR)!=NULL || ptr==filename || *(ptr-1)==DIRSEP_CHAR)
ptr=NULL;
} /* if */
return ptr;
}
/* set_extension
* Set the default extension, or force an extension. To erase the
* extension of a filename, set "extension" to an empty string.
*/
void set_extension(char *filename,const char *extension,int force)
{
char *ptr;
assert(extension!=NULL && (*extension=='\0' || *extension=='.'));
assert(filename!=NULL);
ptr=get_extension(filename);
if (force && ptr!=NULL)
*ptr='\0'; /* set zero terminator at the position of the period */
if (force || ptr==NULL)
strcat(filename,extension);
}
static const char *option_value(const char *optptr,char **argv,int argc,int *arg)
{
const char *ptr;
if (*(optptr+1)=='=' || *(optptr+1)==':')
ptr=optptr+2;
else
ptr=optptr+1;
if (strlen(ptr)==0 && *arg!=argc-1)
ptr=argv[++*arg];
return ptr;
}
static int toggle_option(const char *optptr,int option)
{
switch ((*(optptr+1)=='=' || *(optptr+1)==':') ? *(optptr+2) : *(optptr+1)) {
case '-':
option=FALSE;
break;
case '+':
option=TRUE;
break;
default:
about();
} /* switch */
return option;
}
/* Parsing command line options is indirectly recursive: parseoptions()
* calls parserespf() to handle options in a a response file and
* parserespf() calls parseoptions() at its turn after having created
* an "option list" from the contents of the file.
*/
static void parserespf(char *filename,char *oname,char *ename,char *pname,
char *codepage);
static void parseoptions(int argc,char **argv,char *oname,char *ename,char *pname,
char *codepage)
{
char str[_MAX_PATH];
const char *ptr;
int arg,i,isoption;
for (arg=1; arg<argc; arg++) {
#if DIRSEP_CHAR=='/'
isoption= argv[arg][0]=='-';
#else
isoption= argv[arg][0]=='/' || argv[arg][0]=='-';
#endif
if (isoption) {
ptr=&argv[arg][1];
switch (*ptr) {
case 'a':
if (*(ptr+1)!='\0')
about();
sc_asmfile=TRUE; /* skip last pass of making binary file */
if (verbosity>1)
verbosity=1;
break;
case 'c':
strlcpy(codepage,option_value(ptr,argv,argc,&arg),MAXCODEPAGE); /* set name of codepage */
break;
#if defined dos_setdrive
case 'D': /* set active directory */
ptr=option_value(ptr,argv,argc,&arg);
if (ptr[1]==':')
dos_setdrive(toupper(*ptr)-'A'+1); /* set active drive */
chdir(ptr);
break;
#endif
case 'e':
strlcpy(ename,option_value(ptr,argv,argc,&arg),_MAX_PATH); /* set name of error file */
break;
case 'E':
sc_warnings_are_errors = true;
break;
#if defined __WIN32__ || defined _WIN32 || defined _Windows
case 'H':
hwndFinish=(HWND)atoi(option_value(ptr,argv,argc,&arg));
if (!IsWindow(hwndFinish))
hwndFinish=(HWND)0;
break;
#endif
case 'h':
sc_showincludes = 1;
break;
case 'i':
strlcpy(str,option_value(ptr,argv,argc,&arg),sizeof str); /* set name of include directory */
i=strlen(str);
if (i>0) {
if (str[i-1]!=DIRSEP_CHAR) {
str[i]=DIRSEP_CHAR;
str[i+1]='\0';
} /* if */
insert_path(str);
} /* if */
break;
case 'l':
if (*(ptr+1)!='\0')
about();
sc_listing=TRUE; /* skip second pass & code generation */
break;
case 'o':
strlcpy(oname,option_value(ptr,argv,argc,&arg),_MAX_PATH); /* set name of (binary) output file */
break;
case 'O':
pc_optimize=*option_value(ptr,argv,argc,&arg) - '0';
if (pc_optimize<sOPTIMIZE_NONE || pc_optimize>=sOPTIMIZE_NUMBER || pc_optimize==sOPTIMIZE_NOMACRO)
about();
break;
case 'p':
strlcpy(pname,option_value(ptr,argv,argc,&arg),_MAX_PATH); /* set name of implicit include file */
break;
case 's':
skipinput=atoi(option_value(ptr,argv,argc,&arg));
break;
case 't':
sc_tabsize=atoi(option_value(ptr,argv,argc,&arg));
break;
case 'v':
verbosity= isdigit(*option_value(ptr,argv,argc,&arg)) ? atoi(option_value(ptr,argv,argc,&arg)) : 2;
if (sc_asmfile && verbosity>1)
verbosity=1;
break;
case 'w':
i=(int)strtol(option_value(ptr,argv,argc,&arg),(char **)&ptr,10);
if (*ptr=='-')
pc_enablewarning(i,0);
else if (*ptr=='+')
pc_enablewarning(i,1);
else if (*ptr=='\0')
pc_enablewarning(i,2);
break;
case 'x':
i=(int)strtol(option_value(ptr,argv,argc,&arg),(char **)&ptr,10);
switch (i) {
case 13:
case 12:
pc_must_drop_stack = false;
/* Fallthrough */
case 10:
pc_code_version = i;
break;
default:
fprintf(stderr, "unknown code version: %d\n", i);
exit(1);
}
break;
case '\\': /* use \ instead for escape characters */
sc_ctrlchar='\\';
break;
case '^': /* use ^ instead for escape characters */
sc_ctrlchar='^';
break;
case ';':
sc_needsemicolon=toggle_option(ptr,sc_needsemicolon);
break;
default: /* wrong option */
about();
} /* switch */
} else if (argv[arg][0]=='@') {
#if !defined SC_LIGHT
parserespf(&argv[arg][1],oname,ename,pname,codepage);
#endif
} else if ((ptr=strchr(argv[arg],'='))!=NULL) {
i=(int)(ptr-argv[arg]);
if (i>sNAMEMAX) {
i=sNAMEMAX;
error(200,argv[arg],sNAMEMAX); /* symbol too long, truncated to sNAMEMAX chars */
} /* if */
strlcpy(str,argv[arg],i+1); /* str holds symbol name */
i=atoi(ptr+1);
add_constant(str,i,sGLOBAL,0);
} else {
strlcpy(str,argv[arg],sizeof(str)-5); /* -5 because default extension is ".sp" */
set_extension(str,".sp",FALSE);
insert_sourcefile(str);
/* The output name is the first input name with a different extension,
* but it is stored in a different directory
*/
if (strlen(oname)==0) {
if ((ptr=strrchr(str,DIRSEP_CHAR))!=NULL)
ptr++; /* strip path */
else
ptr=str;
assert(strlen(ptr)<_MAX_PATH);
strcpy(oname,ptr);
} /* if */
set_extension(oname,".asm",TRUE);
} /* if */
} /* for */
}
#if !defined SC_LIGHT
static void parserespf(char *filename,char *oname,char *ename,char *pname,
char *codepage)
{
#define MAX_OPTIONS 100
FILE *fp;
char *string, *ptr, **argv;
int argc;
long size;
if ((fp=fopen(filename,"r"))==NULL)
error(FATAL_ERROR_READ,filename);
/* load the complete file into memory */
fseek(fp,0L,SEEK_END);
size=ftell(fp);
fseek(fp,0L,SEEK_SET);
assert(size<INT_MAX);
if ((string=(char *)malloc((int)size+1))==NULL)
error(FATAL_ERROR_OOM); /* insufficient memory */
/* fill with zeros; in MS-DOS, fread() may collapse CR/LF pairs to
* a single '\n', so the string size may be smaller than the file
* size. */
memset(string,0,(int)size+1);
ke::Unused() << fread(string,1,(int)size,fp);
fclose(fp);
/* allocate table for option pointers */
if ((argv=(char **)malloc(MAX_OPTIONS*sizeof(char*)))==NULL)
error(FATAL_ERROR_OOM); /* insufficient memory */
/* fill the options table */
ptr=strtok(string," \t\r\n");
for (argc=1; argc<MAX_OPTIONS && ptr!=NULL; argc++) {
/* note: the routine skips argv[0], for compatibility with main() */
argv[argc]=ptr;
ptr=strtok(NULL," \t\r\n");
} /* for */
if (ptr!=NULL)
error(FATAL_ERROR_ALLOC_OVERFLOW,"option table");
/* parse the option table */
parseoptions(argc,argv,oname,ename,pname,codepage);
/* free allocated memory */
free(argv);
free(string);
}
#endif
static void setopt(int argc,char **argv,char *oname,char *ename,char *pname,
char *codepage)
{
delete_sourcefiletable(); /* make sure it is empty */
*oname='\0';
*ename='\0';
*pname='\0';
*codepage='\0';
strcpy(pname,sDEF_PREFIX);
#if 0 /* needed to test with BoundsChecker for DOS (it does not pass
* through arguments) */
insert_sourcefile("test.p");
strcpy(oname,"test.asm");
#endif
#if !defined SC_LIGHT
/* first parse a "config" file with default options */