-
Notifications
You must be signed in to change notification settings - Fork 72
/
sc1.c
7904 lines (7449 loc) · 252 KB
/
sc1.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
/* 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: sc1.c 3664 2006-11-08 12:09:25Z thiadmer $
*/
#include <assert.h>
#include <ctype.h>
#include <limits.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#if defined __WIN32__ || defined _WIN32 || defined __MSDOS__
#include <conio.h>
#include <io.h>
#endif
#if defined LINUX || defined __FreeBSD__ || defined __OpenBSD__
#include <sclinux.h>
#include <binreloc.h> /* from BinReloc, see www.autopackage.org */
#endif
#if defined LINUX || defined __APPLE__
#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)
#define stricmp _stricmp
#define chdir _chdir
#define access _access
#define snprintf _snprintf
#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 "lstring.h"
#include "sc.h"
#include "version.h"
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 *rname,char *codepage);
static void setconfig(char *root);
static void setcaption(void);
static void about(void);
static void setconstants(void);
static void setstringconstants(void);
static void parse(void);
static void dumplits(void);
static void dumpzero(int count);
static void declfuncvar(int fpublic,int fstatic,int fstock,int fconst);
static void declglb(char *firstname,int firsttag,int fpublic,int fstatic,
int stock,int fconst);
static int declloc(int fstatic);
static void decl_const(int table);
static void decl_enum(int table,int fstatic);
static cell needsub(int *tag,constvalue_root **enumroot);
static void initials(int ident,int tag,cell *size,int dim[],int numdim,
constvalue_root *enumroot);
static cell initarray(int ident,int tag,int dim[],int numdim,int cur,
int startlit,int counteddim[],constvalue_root *lastdim,
constvalue_root *enumroot,int *errorfound);
static cell initvector(int ident,int tag,cell size,int startlit,int fillzero,
constvalue_root *enumroot,int *errorfound);
static cell init(int ident,int *tag,int *errorfound);
static int getstates(const char *funcname);
static void attachstatelist(symbol *sym, int state_id);
static void funcstub(int fnative);
static int newfunc(char *firstname,int firsttag,int fpublic,int fstatic,int stock);
static int declargs(symbol *sym,int chkshadow);
static void doarg(char *name,int ident,int offset,int tags[],int numtags,
int fpublic,int fconst,int written,int chkshadow,arginfo *arg);
static void make_report(symbol *root,FILE *log,char *sourcefile);
static void reduce_referrers(symbol *root);
static long max_stacksize(symbol *root,int *recursion);
static int testsymbols(symbol *root,int level,int testlabs,int testconst);
static void destructsymbols(symbol *root,int level);
static constvalue *find_constval_byval(constvalue_root *table,cell val);
static symbol *fetchlab(char *name);
static void statement(int *lastindent,int allow_decl);
static void compound(int stmt_sameline,int starttok);
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 void doassert(void);
static void doexit(void);
static int doif(void);
static int dowhile(void);
static int dodo(void);
static int dofor(void);
static void doswitch(void);
static void dogoto(void);
static void dolabel(void);
static void doreturn(void);
static void dobreak(void);
static void docont(void);
static void dosleep(void);
static void dostate(void);
static void addwhile(int *ptr);
static void delwhile(void);
static int *readwhile(void);
typedef void (SC_FASTCALL *OPCODE_PROC)(char *name);
typedef struct {
char *name;
OPCODE_PROC func;
} EMIT_OPCODE;
enum {
TEST_PLAIN, /* no parentheses */
TEST_THEN, /* '(' <expr> ')' or <expr> 'then' */
TEST_DO, /* '(' <expr> ')' or <expr> 'do' */
TEST_OPT, /* '(' <expr> ')' or <expr> */
};
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 optproccall = TRUE; /* support "procedure call" */
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
#if !defined NO_MAIN
#if defined __TURBOC__ && !defined __32BIT__
extern unsigned int _stklen = 0x2000;
#endif
int main(int argc, char *argv[])
{
return pc_compile(argc,argv);
}
/* pc_printf()
* Called for general purpose "console" output. This function prints general
* purpose messages; errors go through pc_error(). The function is modelled
* after printf().
*/
int pc_printf(const char *message,...)
{
int ret;
va_list argptr;
va_start(argptr,message);
ret=vprintf(message,argptr);
va_end(argptr);
return ret;
}
/* pc_error()
* Called for producing error output.
* number the error number (as documented in the manual)
* message a string describing the error with embedded %d and %s tokens
* filename the name of the file currently being parsed
* firstline the line number at which the expression started on which
* the error was found, or -1 if there is no "starting line"
* lastline the line number at which the error was detected
* argptr a pointer to the first of a series of arguments (for macro
* "va_arg")
* Return:
* If the function returns 0, the parser attempts to continue compilation.
* On a non-zero return value, the parser aborts.
*/
int pc_error(int number,char *message,char *filename,int firstline,int lastline,va_list argptr)
{
static char *prefix[3]={ "error", "fatal error", "warning" };
if (number!=0) {
char *pre;
pre=prefix[number/100];
if (number>=200 && pc_geterrorwarnings()){
pre=prefix[0];
}
if (firstline>=0)
fprintf(stderr,"%s(%d -- %d) : %s %03d: ",filename,firstline,lastline,pre,number);
else
fprintf(stderr,"%s(%d) : %s %03d: ",filename,lastline,pre,number);
} /* if */
vfprintf(stderr,message,argptr);
fflush(stderr);
return 0;
}
/* pc_opensrc()
* Opens a source file (or include file) for reading. The "file" does not have
* to be a physical file, one might compile from memory.
* filename the name of the "file" to read from
* Return:
* The function must return a pointer, which is used as a "magic cookie" to
* all I/O functions. When failing to open the file for reading, the
* function must return NULL.
* Note:
* Several "source files" may be open at the same time. Specifically, one
* file can be open for reading and another for writing.
*/
void *pc_opensrc(char *filename)
{
return fopen(filename,"r");
}
/* pc_createsrc()
* Creates/overwrites a source file for writing. The "file" does not have
* to be a physical file, one might compile from memory.
* filename the name of the "file" to create
* Return:
* The function must return a pointer, which is used as a "magic cookie" to
* all I/O functions. When failing to open the file for reading, the
* function must return NULL.
* Note:
* Several "source files" may be open at the same time. Specifically, one
* file can be open for reading and another for writing.
*/
void *pc_createsrc(char *filename)
{
return fopen(filename,"w");
}
/* pc_createtmpsrc()
* Creates a temporary source file with a unique name for writing.
* Return:
* The function must return a pointer, which is used as a "magic cookie" to
* all I/O functions. When failing to open the file for reading, the
* function must return NULL.
*/
void *pc_createtmpsrc(char **filename)
{
char *tname=NULL;
FILE *ftmp=NULL;
#if defined __WIN32__ || defined _WIN32
tname=_tempnam(NULL,"pawn");
ftmp=fopen(tname,"wt");
#elif defined __MSDOS__ || defined _Windows
tname=tempnam(NULL,"pawn");
ftmp=fopen(tname,"wt");
#else
static const char template[]="/tmp/pawnXXXXXX";
if ((tname=malloc(sizeof(template)))!=NULL) {
int fdtmp;
strncpy(tname,template,sizeof(template));
if ((fdtmp=mkstemp(tname)) >= 0) {
ftmp=fdopen(fdtmp,"wt");
} else {
free(tname);
tname=NULL;
} /* if */
} /* if */
#endif
if (filename!=NULL)
*filename=tname;
return ftmp;
}
/* pc_closesrc()
* Closes a source file (or include file). The "handle" parameter has the
* value that pc_opensrc() returned in an earlier call.
*/
void pc_closesrc(void *handle)
{
assert(handle!=NULL);
fclose((FILE*)handle);
}
/* pc_resetsrc()
* "position" may only hold a pointer that was previously obtained from
* pc_getpossrc()
*/
void pc_resetsrc(void *handle,void *position)
{
assert(handle!=NULL);
fsetpos((FILE*)handle,(fpos_t *)position);
}
/* pc_readsrc()
* Reads a single line from the source file (or up to a maximum number of
* characters if the line in the input file is too long).
*/
char *pc_readsrc(void *handle,unsigned char *target,int maxchars)
{
return fgets((char*)target,maxchars,(FILE*)handle);
}
/* pc_writesrc()
* Writes to to the source file. There is no automatic line ending; to end a
* line, write a "\n".
*/
int pc_writesrc(void *handle,unsigned char *source)
{
return fputs((char*)source,(FILE*)handle) >= 0;
}
void *pc_getpossrc(void *handle)
{
static fpos_t lastpos; /* may need to have a LIFO stack of such positions */
fgetpos((FILE*)handle,&lastpos);
return &lastpos;
}
int pc_eofsrc(void *handle)
{
return feof((FILE*)handle);
}
/* should return a pointer, which is used as a "magic cookie" to all I/O
* functions; return NULL for failure
*/
void *pc_openasm(char *filename)
{
#if defined __MSDOS__ || defined SC_LIGHT
return fopen(filename,"w+");
#else
return mfcreate(filename);
#endif
}
void pc_closeasm(void *handle, int deletefile)
{
#if defined __MSDOS__ || defined SC_LIGHT
if (handle!=NULL)
fclose((FILE*)handle);
if (deletefile)
remove(outfname);
#else
if (handle!=NULL) {
if (!deletefile)
mfdump((MEMFILE*)handle);
mfclose((MEMFILE*)handle);
} /* if */
#endif
}
void pc_resetasm(void *handle)
{
assert(handle!=NULL);
#if defined __MSDOS__ || defined SC_LIGHT
fflush((FILE*)handle);
fseek((FILE*)handle,0,SEEK_SET);
#else
mfseek((MEMFILE*)handle,0,SEEK_SET);
#endif
}
int pc_writeasm(void *handle,char *string)
{
#if defined __MSDOS__ || defined SC_LIGHT
return fputs(string,(FILE*)handle) >= 0;
#else
return mfputs((MEMFILE*)handle,string);
#endif
}
char *pc_readasm(void *handle, char *string, int maxchars)
{
#if defined __MSDOS__ || defined SC_LIGHT
return fgets(string,maxchars,(FILE*)handle);
#else
return mfgets((MEMFILE*)handle,string,maxchars);
#endif
}
/* Should return a pointer, which is used as a "magic cookie" to all I/O
* functions; return NULL for failure.
*/
void *pc_openbin(char *filename)
{
FILE *fbin;
fbin=fopen(filename,"wb");
setvbuf(fbin,NULL,_IOFBF,1UL<<20);
return fbin;
}
void pc_closebin(void *handle,int deletefile)
{
fclose((FILE*)handle);
if (deletefile)
remove(binfname);
}
/* pc_resetbin()
* Can seek to any location in the file.
* The offset is always from the start of the file.
*/
void pc_resetbin(void *handle,long offset)
{
fflush((FILE*)handle);
fseek((FILE*)handle,offset,SEEK_SET);
}
int pc_writebin(void *handle,void *buffer,int size)
{
return (int)fwrite(buffer,1,size,(FILE*)handle) == size;
}
long pc_lengthbin(void *handle)
{
return ftell((FILE*)handle);
}
#endif /* !defined NO_MAIN */
/* "main" of the compiler
*/
#if defined __cplusplus
extern "C"
#endif
int pc_compile(int argc, char *argv[])
{
int entry,i,jmpcode;
int retcode;
char incfname[_MAX_PATH];
char reportname[_MAX_PATH];
char codepage[MAXCODEPAGE+1];
FILE *binf;
void *inpfmark;
int lcl_packstr,lcl_needsemicolon,lcl_tabsize;
#if !defined SC_LIGHT
int hdrsize=0;
#endif
char *ptr;
char *tname=NULL;
/* set global variables to their initial value */
binf=NULL;
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;
/* allocate memory for fixed tables */
inpfname=(char*)malloc(_MAX_PATH);
if (inpfname==NULL)
error(103); /* insufficient memory */
litq=(cell*)malloc(litmax*sizeof(cell));
if (litq==NULL)
error(103); /* insufficient memory */
/* inptfname may be used in error(), fill it with zeros */
memset(inpfname,0,_MAX_PATH);
setopt(argc,argv,outfname,errfname,incfname,reportname,codepage);
strcpy(binfname,outfname);
ptr=get_extension(binfname);
if (ptr!=NULL && stricmp(ptr,".asm")==0)
set_extension(binfname,".amx",TRUE);
else
set_extension(binfname,".amx",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 (!strempty(errfname))
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_tabsize=sc_tabsize;
#if !defined NO_CODEPAGE
if (!cp_set(codepage)) /* set codepage */
error(108); /* codepage mapping file not found */
#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 *sname;
FILE *ftmp,*fsrc;
int fidx;
ftmp=pc_createtmpsrc(&tname);
for (fidx=0; (sname=get_sourcefile(fidx))!=NULL; fidx++) {
unsigned char tstring[128];
fsrc=(FILE*)pc_opensrc(sname);
if (fsrc==NULL) {
strcpy(inpfname,sname); /* avoid invalid filename */
error(100,sname);
} /* if */
pc_writesrc(ftmp,(unsigned char*)"#file \"");
pc_writesrc(ftmp,(unsigned char*)sname);
pc_writesrc(ftmp,(unsigned char*)"\"\n");
while (pc_readsrc(fsrc,tstring,sizeof tstring)!=NULL) {
pc_writesrc(ftmp,tstring);
} /* while */
pc_writesrc(ftmp,(unsigned char*)"\n");
pc_closesrc(fsrc);
} /* for */
pc_closesrc(ftmp);
strcpy(inpfname,tname);
} else {
strcpy(inpfname,get_sourcefile(0));
} /* if */
inpf_org=(FILE*)pc_opensrc(inpfname);
if (inpf_org==NULL)
error(100,inpfname);
freading=TRUE;
outf=(FILE*)pc_openasm(outfname); /* first write to assembler file (may be temporary) */
if (outf==NULL)
error(101,outfname);
/* immediately open the binary file, for other programs to check */
if (sc_asmfile || sc_listing) {
binf=NULL;
} else {
binf=(FILE*)pc_openbin(binfname);
if (binf==NULL)
error(101,binfname);
} /* if */
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;
/* do the first pass through the file (or possibly two or more "first passes") */
sc_parsenum=0;
inpfmark=pc_getpossrc(inpf_org);
do {
/* reset "defined" flag of all functions and global variables */
reduce_referrers(&glbtab);
delete_symbols(&glbtab,0,TRUE,FALSE);
delete_heaplisttable();
#if !defined NO_DEFINE
delete_substtable();
#endif
resetglobals();
sc_ctrlchar=sc_ctrlchar_org;
sc_packstr=lcl_packstr;
sc_needsemicolon=lcl_needsemicolon;
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 */
setstringconstants();
setfileconst(inpfname);
if (!strempty(incfname)) {
if (strcmp(incfname,sDEF_PREFIX)==0) {
plungefile(incfname,FALSE,TRUE); /* parse "default.inc" */
} else {
if (!plungequalifiedfile(incfname)) /* parse "prefix" include file */
error(100,incfname); /* cannot read from ... (fatal error) */
} /* if */
} /* if */
preprocess(); /* fetch first line */
parse(); /* process all input */
sc_parsenum++;
} while (sc_reparse);
/* second (or third) pass */
if (sc_listing)
sc_status=statSECOND;
else
sc_status=statWRITE; /* set, to enable warnings */
state_conflict(&glbtab);
/* write a report, if requested */
#if !defined SC_LIGHT
if (sc_makereport) {
FILE *frep=stdout;
if (!strempty(reportname))
frep=fopen(reportname,"wb"); /* avoid translation of \n to \r\n in DOS/Windows */
if (frep!=NULL) {
make_report(&glbtab,frep,get_sourcefile(0));
if (!strempty(reportname))
fclose(frep);
} /* if */
if (sc_documentation!=NULL) {
free(sc_documentation);
sc_documentation=NULL;
} /* if */
} /* if */
#endif
sc_ctrlchar=sc_ctrlchar_org;
sc_packstr=lcl_packstr;
sc_needsemicolon=lcl_needsemicolon;
sc_tabsize=lcl_tabsize;
/*if (sc_listing)
goto cleanup;*/
/* 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);
} /* if */
setfiledirect(inpfname);
/* ??? 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);
#if !defined NO_DEFINE
delete_substtable();
#endif
resetglobals();
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() */
if (sc_listing)
sc_status=statSECOND;
else
sc_status=statWRITE; /* allow to write --this variable was reset by resetglobals() */
writeleader(&glbtab);
setstringconstants();
setfileconst(inpfname);
insert_dbgfile(inpfname);
if (!strempty(incfname)) {
if (strcmp(incfname,sDEF_PREFIX)==0)
plungefile(incfname,FALSE,TRUE); /* parse "default.inc" (again) */
else
plungequalifiedfile(incfname); /* parse implicit include file (again) */
} /* if */
preprocess(); /* fetch first line */
parse(); /* process all input */
if (sc_listing)
goto cleanup;
/* 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);
inpf=NULL;
}
/* write the binary file (the file is already open) */
if (!(sc_asmfile || sc_listing) && errnum==0 && jmpcode==0) {
assert(binf!=NULL);
pc_resetasm(outf); /* flush and loop back, for reading */
#if !defined SC_LIGHT
hdrsize=
#endif
assemble(binf,outf); /* assembler file is now input */
} /* if */
if (outf!=NULL) {
pc_closeasm(outf,!(sc_asmfile || sc_listing));
outf=NULL;
} /* if */
if (binf!=NULL) {
pc_closebin(binf,errnum!=0);
binf=NULL;
} /* if */
#if !defined SC_LIGHT
if (errnum==0 && strempty(errfname)) {
int recursion;
long stacksize=max_stacksize(&glbtab,&recursion);
int flag_exceed=0;
if (pc_amxlimit>0) {
long totalsize=hdrsize+code_idx;
if (pc_amxram==0)
totalsize+=(glb_declared+pc_stksize)*sizeof(cell);
if (totalsize>=pc_amxlimit)
flag_exceed=1;
} /* if */
if (pc_amxram>0 && (glb_declared+pc_stksize)*sizeof(cell)>=(unsigned long)pc_amxram)
flag_exceed=1;
if ((sc_debug & sSYMBOLIC)!=0 || verbosity>=2 || stacksize+32>=(long)pc_stksize || flag_exceed) {
pc_printf("Header size: %8ld bytes\n", (long)hdrsize);
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; ", (long)pc_stksize*sizeof(cell));
pc_printf("estimated max. usage");
if (recursion)
pc_printf(": unknown, due to recursion\n");
else if ((pc_memflags & suSLEEP_INSTR)!=0)
pc_printf(": unknown, due to the \"sleep\" instruction\n");
else
pc_printf("=%ld cells (%ld bytes)\n",stacksize,stacksize*sizeof(cell));
pc_printf("Total requirements:%8ld bytes\n", (long)hdrsize+(long)code_idx+(long)glb_declared*sizeof(cell)+(long)pc_stksize*sizeof(cell));
} /* if */
if (flag_exceed)
error(106,pc_amxlimit+pc_amxram); /* this causes a jump back to label "cleanup" */
} /* if */
#endif
if (get_sourcefile(1)!=NULL && tname!=NULL) {
remove(tname); /* the "input file" was in fact a temporary file */
free(tname);
} /* if */
free(inpfname);
free(litq);
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);
line_sym=NULL;
hashtable_term(&symbol_cache_ht);
delete_consttable(&tagname_tab);
delete_consttable(&libname_tab);
delete_consttable(&sc_automaton_tab);
delete_consttable(&sc_state_tab);
state_deletetable();
delete_aliastable();
delete_pathtable();
delete_sourcefiletable();
delete_dbgstringtable();
#if !defined NO_DEFINE
delete_substtable();
#endif
#if !defined SC_LIGHT
delete_docstringtable();
free(sc_documentation);
#endif
delete_autolisttable();
delete_heaplisttable();
if (errnum!=0) {
if (strempty(errfname))
pc_printf("\n%d Error%s.\n",errnum,(errnum>1) ? "s" : "");
retcode=1;
} else if (warnnum!=0){
if (strempty(errfname))
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))
PostMessage(hwndFinish,RegisterWindowMessage("PawnNotify"),retcode,0L);
#endif
#if defined FORTIFY
Fortify_ListAllMemory();
#endif
return retcode;
}
#if defined __cplusplus
extern "C"
#endif
int pc_addconstant(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;
}
#if defined __cplusplus
extern "C"
#endif
int pc_addtag(char *name)
{
cell val;
constvalue *ptr;
int last,tag;
if (name==NULL) {
/* no tagname was given, check for one */
if (lex(&val,&name)!=tLABEL) {
lexpush();
return 0; /* untagged */
} /* if */
} /* if */
assert(strchr(name,':')==NULL); /* colon should already have been stripped */
last=0;
ptr=tagname_tab.first;
while (ptr!=NULL) {
tag=(int)(ptr->value & TAGMASK);
if (strcmp(name,ptr->name)==0)
return tag; /* tagname is known, return its sequence number */
tag &= (int)~FIXEDTAG;
if (tag>last)
last=tag;
ptr=ptr->next;
} /* while */
/* tagname currently unknown, add it */
tag=last+1; /* guaranteed not to exist already */
if (isupper(*name))
tag |= (int)FIXEDTAG;
append_constval(&tagname_tab,name,(cell)tag,0);
return tag;
}
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 */
pc_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;
sc_allowproccall=FALSE;
pc_addlibtable=TRUE; /* by default, add a "library table" to the output file */
sc_alignnext=FALSE;
pc_docexpr=FALSE;
pc_deprecate=NULL;
sc_curstates=0;
pc_memflags=0;
pc_naked=FALSE;
emit_flags=0;
emit_stgbuf_idx=-1;
}
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 */
optproccall=TRUE; /* support "procedure call" */
verbosity=1; /* verbosity level, no copyright banner */
sc_debug=sCHKBOUNDS; /* by default: bounds checking+assertions */
pc_optimize=sOPTIMIZE_NOMACRO;
sc_packstr=FALSE; /* strings are unpacked by default */
#if AMX_COMPACTMARGIN > 2
sc_compress=TRUE; /* compress output bytecodes */
#else
sc_compress=FALSE;
#endif
sc_needsemicolon=FALSE; /* semicolon required to terminate expressions? */
sc_dataalign=sizeof(cell);
pc_stksize=sDEF_AMXSTACK; /* default stack size */
pc_amxlimit=0; /* no limit on size of the abstract machine */
pc_amxram=0; /* no limit on data size of the abstract machine */
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 " / " " */
hashtable_init(&symbol_cache_ht, sizeof(symbol *),(16384/3*2),NULL); /* 16384 slots */
tagname_tab.first=tagname_tab.last=NULL; /* tagname table */
libname_tab.first=libname_tab.last=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;
sc_makereport=FALSE; /* do not generate a cross-reference report */
#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.
*/
SC_FUNC void set_extension(char *filename,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)
{
return (*(optptr+1)=='=' || *(optptr+1)==':') ? optptr+2 : optptr+1;
}