added experimental new String tag. this tag will revert array usage to "char" sizing and packed strings
1 /* Pawn compiler - File input, preprocessing and lexical analysis functions
3 * Copyright (c) ITB CompuPhase, 1997-2006
5 * This software is provided "as-is", without any express or implied warranty.
6 * In no event will the authors be held liable for any damages arising from
7 * the use of this software.
9 * Permission is granted to anyone to use this software for any purpose,
10 * including commercial applications, and to alter it and redistribute it
11 * freely, subject to the following restrictions:
13 * 1. The origin of this software must not be misrepresented; you must not
14 * claim that you wrote the original software. If you use this software in
15 * a product, an acknowledgment in the product documentation would be
16 * appreciated but is not required.
17 * 2. Altered source versions must be plainly marked as such, and must not be
18 * misrepresented as being the original software.
19 * 3. This notice may not be removed or altered from any source distribution.
21 * Version: $Id: sc2.c 3636 2006-08-14 15:42:05Z thiadmer $
31 #if defined LINUX || defined __FreeBSD__ || defined __OpenBSD__
36 #include <alloc/fortify.h>
39 /* flags for litchar() */
42 static cell litchar(const unsigned char **lptr,int flags);
43 static symbol *find_symbol(const symbol *root,const char *name,int fnumber,int automaton,int *cmptag);
45 static void substallpatterns(unsigned char *line,int buffersize);
46 static int match(char *st,int end);
47 static int alpha(char c);
49 #define SKIPMODE 1 /* bit field in "#if" stack */
50 #define PARSEMODE 2 /* bit field in "#if" stack */
51 #define HANDLED_ELSE 4 /* bit field in "#if" stack */
52 #define SKIPPING (skiplevel>0 && (ifstack[skiplevel-1] & SKIPMODE)==SKIPMODE)
54 static short icomment; /* currently in multiline comment? */
55 static char ifstack[sCOMP_STACK]; /* "#if" stack */
56 static short iflevel; /* nesting level if #if/#else/#endif */
57 static short skiplevel; /* level at which we started skipping (including nested #if .. #endif) */
58 static unsigned char term_expr[] = "";
59 static int listline=-1; /* "current line" for the list file */
64 * Uses a LIFO stack to store information. The stack is used by doinclude(),
65 * doswitch() (to hold the state of "swactive") and some other routines.
67 * Porting note: I made the bold assumption that an integer will not be
68 * larger than a pointer (it may be smaller). That is, the stack element
69 * is typedef'ed as a pointer type, but I also store integers on it. See
72 * Global references: stack,stkidx,stktop (private to pushstk(), popstk()
75 static stkitem *stack=NULL;
76 static int stkidx=0,stktop=0;
78 SC_FUNC void pushstk(stkitem val)
80 assert(stkidx<=stktop);
83 int newsize= (stktop==0) ? 16 : 2*stktop;
84 /* try to resize the stack */
85 assert(newsize>stktop);
86 newstack=(stkitem*)malloc(newsize*sizeof(stkitem));
88 error(102,"parser stack"); /* stack overflow (recursive include?) */
90 memcpy(newstack,stack,stkidx*sizeof(stkitem));
96 assert(stkidx<stktop);
101 SC_FUNC stkitem popstk(void)
105 s.i=-1; /* stack is empty */
110 return stack[stkidx];
113 SC_FUNC void clearstk(void)
115 assert(stack!=NULL || stktop==0);
124 SC_FUNC int plungequalifiedfile(char *name)
126 static char *extensions[] = { ".inc", ".p", ".pawn" };
133 fp=(FILE*)pc_opensrc(name);
134 ext=strchr(name,'\0'); /* save position */
136 /* try to append an extension */
137 strcpy(ext,extensions[ext_idx]);
138 fp=(FILE*)pc_opensrc(name);
140 *ext='\0'; /* on failure, restore filename */
143 } while (fp==NULL && ext_idx<(sizeof extensions / sizeof extensions[0]));
145 *ext='\0'; /* restore filename */
149 PUSHSTK_P(inpfname); /* pointer to current file name */
150 PUSHSTK_P(curlibrary);
153 assert(skiplevel==iflevel); /* these two are always the same when "parsing" */
154 PUSHSTK_I(sc_is_utf8);
158 inpfname=duplicatestring(name);/* set name of include file */
160 error(103); /* insufficient memory */
161 inpf=fp; /* set input file pointer to include file */
163 fline=0; /* set current line number to 0 */
165 icomment=0; /* not in a comment */
166 insert_dbgfile(inpfname);
167 setfiledirect(inpfname);
168 listline=-1; /* force a #line directive when changing the file */
169 sc_is_utf8=(short)scan_utf8(inpf,name);
173 SC_FUNC int plungefile(char *name,int try_currentpath,int try_includepaths)
177 if (try_currentpath) {
178 result=plungequalifiedfile(name);
180 /* failed to open the file in the active directory, try to open the file
181 * in the same directory as the current file --but first check whether
182 * there is a (relative) path for the current file
185 if ((ptr=strrchr(inpfname,DIRSEP_CHAR))!=0) {
186 int len=(int)(ptr-inpfname)+1;
187 if (len+strlen(name)<_MAX_PATH) {
188 char path[_MAX_PATH];
189 strlcpy(path,inpfname,len+1);
190 strlcat(path,name,sizeof path);
191 result=plungequalifiedfile(path);
197 if (try_includepaths && name[0]!=DIRSEP_CHAR) {
200 for (i=0; !result && (ptr=get_path(i))!=NULL; i++) {
201 char path[_MAX_PATH];
202 strlcpy(path,ptr,sizeof path);
203 strlcat(path,name,sizeof path);
204 result=plungequalifiedfile(path);
210 static void check_empty(const unsigned char *lptr)
212 /* verifies that the string contains only whitespace */
213 while (*lptr<=' ' && *lptr!='\0')
216 error(38); /* extra characters on line */
221 * Gets the name of an include file, pushes the old file on the stack and
222 * sets some options. This routine doesn't use lex(), since lex() doesn't
223 * recognize file names (and directories).
225 * Global references: inpf (altered)
230 static void doinclude(int silent)
232 char name[_MAX_PATH];
233 char symname[sNAMEMAX];
238 while (*lptr<=' ' && *lptr!='\0') /* skip leading whitespace */
240 if (*lptr=='<' || *lptr=='\"'){
241 c=(char)((*lptr=='\"') ? '\"' : '>'); /* termination character */
243 while (*lptr<=' ' && *lptr!='\0') /* skip whitespace after quote */
250 while (*lptr!=c && *lptr!='\0' && i<sizeof name - 1) /* find the end of the string */
252 while (i>0 && name[i-1]<=' ')
253 i--; /* strip trailing whitespace */
254 assert(i>=0 && i<sizeof name);
255 name[i]='\0'; /* zero-terminate the string */
257 if (*lptr!=c) { /* verify correct string termination */
258 error(37); /* invalid string */
262 check_empty(lptr+1); /* verify that the rest of the line is whitespace */
264 /* create a symbol from the name of the include file; this allows the system
265 * to test for multiple inclusions
267 strcpy(symname,"_inc_");
268 if ((ptr=strrchr(name,DIRSEP_CHAR))!=NULL)
269 strlcat(symname,ptr+1,sizeof symname);
271 strlcat(symname,name,sizeof symname);
272 if (find_symbol(&glbtab,symname,fcurrent,-1,NULL)==NULL) {
273 /* constant is not present, so this file has not been included yet */
275 /* Include files between "..." or without quotes are read from the current
276 * directory, or from a list of "include directories". Include files
277 * between <...> are only read from the list of include directories.
279 result=plungefile(name,(c!='>'),TRUE);
281 add_constant(symname,1,sGLOBAL,0);
283 error(100,name); /* cannot read from ... (fatal error) */
289 * Reads in a new line from the input file pointed to by "inpf". readline()
290 * concatenates lines that end with a \ with the next line. If no more data
291 * can be read from the file, readline() attempts to pop off the previous file
292 * from the stack. If that fails too, it sets "freading" to 0.
294 * Global references: inpf,fline,inpfname,freading,icomment (altered)
296 static void readline(unsigned char *line)
306 if (inpf==NULL || pc_eofsrc(inpf)) {
308 error(49); /* invalid line continuation */
309 if (inpf!=NULL && inpf!=inpf_org)
312 if (i==-1) { /* All's done; popstk() returns "stack is empty" */
315 /* when there is nothing more to read, the #if/#else stack should
316 * be empty and we should not be in a comment
320 error(1,"#endif","-end of file-");
321 else if (icomment!=0)
322 error(1,"*/","-end of file-");
326 fcurrent=(short)POPSTK_I();
327 icomment=(short)POPSTK_I();
328 sc_is_utf8=(short)POPSTK_I();
329 iflevel=(short)POPSTK_I();
330 skiplevel=iflevel; /* this condition held before including the file */
331 assert(!SKIPPING); /* idem ditto */
332 curlibrary=(constvalue *)POPSTK_P();
333 free(inpfname); /* return memory allocated for the include file name */
334 inpfname=(char *)POPSTK_P();
335 inpf=(FILE *)POPSTK_P();
336 insert_dbgfile(inpfname);
337 setfiledirect(inpfname);
338 listline=-1; /* force a #line directive when changing the file */
341 if (pc_readsrc(inpf,line,num)==NULL) {
342 *line='\0'; /* delete line */
345 /* check whether to erase leading spaces */
347 unsigned char *ptr=line;
348 while (*ptr<=' ' && *ptr!='\0')
351 memmove(line,ptr,strlen((char*)ptr)+1);
354 /* check whether a full line was read */
355 if (strchr((char*)line,'\n')==NULL && !pc_eofsrc(inpf))
356 error(75); /* line too long */
357 /* check if the next line must be concatenated to this line */
358 if ((ptr=(unsigned char*)strchr((char*)line,'\n'))==NULL)
359 ptr=(unsigned char*)strchr((char*)line,'\r');
360 if (ptr!=NULL && ptr>line) {
361 assert(*(ptr+1)=='\0'); /* '\n' or '\r' should be last in the string */
362 while (ptr>line && *ptr<=' ')
363 ptr--; /* skip trailing whitespace */
366 /* set '\a' at the position of '\\' to make it possible to check
367 * for a line continuation in a single line comment (error 49)
370 *ptr='\0'; /* erase '\n' (and any trailing whitespace) */
373 num-=strlen((char*)line);
374 line+=strlen((char*)line);
377 } while (num>=0 && cont);
382 * Replaces all comments from the line by space characters. It updates
383 * a global variable ("icomment") for multiline comments.
385 * This routine also supports the C++ extension for single line comments.
386 * These comments are started with "//" and end at the end of the line.
388 * The function also detects (and manages) "documentation comments". The
389 * global variable "icomment" is set to 2 for documentation comments.
391 * Global references: icomment (private to "stripcom")
393 static void stripcom(unsigned char *line)
396 #if !defined SC_LIGHT
397 #define COMMENT_LIMIT 100
398 #define COMMENT_MARGIN 40 /* length of the longest word */
399 char comment[COMMENT_LIMIT+COMMENT_MARGIN];
402 static int prev_singleline=FALSE;
403 int singleline=prev_singleline;
405 prev_singleline=FALSE; /* preset */
410 if (*line=='*' && *(line+1)=='/') {
411 #if !defined SC_LIGHT
413 assert(commentidx<COMMENT_LIMIT+COMMENT_MARGIN);
414 comment[commentidx]='\0';
415 if (strlen(comment)>0)
416 insert_docstring(comment);
419 icomment=0; /* comment has ended */
420 *line=' '; /* replace '*' and '/' characters by spaces */
424 if (*line=='/' && *(line+1)=='*')
425 error(216); /* nested comment */
426 #if !defined SC_LIGHT
427 /* collect the comment characters in a string */
429 if (skipstar && (*line!='\0' && *line<=' ' || *line=='*')) {
430 /* ignore leading whitespace and '*' characters */
431 } else if (commentidx<COMMENT_LIMIT+COMMENT_MARGIN-1) {
432 comment[commentidx++]=(char)((*line!='\n') ? *line : ' ');
433 if (commentidx>COMMENT_LIMIT && *line!='\0' && *line<=' ') {
434 comment[commentidx]='\0';
435 insert_docstring(comment);
442 *line=' '; /* replace comments by spaces */
446 if (*line=='/' && *(line+1)=='*'){
447 icomment=1; /* start comment */
448 #if !defined SC_LIGHT
449 /* there must be two "*" behind the slash and then white space */
450 if (*(line+2)=='*' && *(line+3)<=' ') {
451 /* if we are not in a function, we must attach the previous block
452 * to the global documentation
454 if (curfunc==NULL && get_docstring(0)!=NULL)
455 sc_attachdocumentation(NULL);
456 icomment=2; /* documentation comment */
461 *line=' '; /* replace '/' and '*' characters by spaces */
466 } else if (*line=='/' && *(line+1)=='/'){ /* comment to end of line */
467 if (strchr((char*)line,'\a')!=NULL)
468 error(49); /* invalid line continuation */
469 #if !defined SC_LIGHT
470 if (*(line+2)=='/' && *(line+3)<=' ') {
471 /* documentation comment */
472 char *str=(char*)line+3;
474 while (*str<=' ' && *str!='\0')
475 str++; /* skip leading whitespace */
476 if ((end=strrchr(str,'\n'))!=NULL)
477 *end='\0';/* erase trailing '\n' */
478 /* if there is a disjunct block, we may need to attach the previous
479 * block to the global documentation
481 if (!singleline && curfunc==NULL && get_docstring(0)!=NULL)
482 sc_attachdocumentation(NULL);
483 insert_docstring(str);
484 prev_singleline=TRUE;
487 *line++='\n'; /* put "newline" at first slash */
488 *line='\0'; /* put "zero-terminator" at second slash */
490 if (*line=='\"' || *line=='\''){ /* leave literals unaltered */
491 c=*line; /* ending quote, single or double */
493 while ((*line!=c || *(line-1)==sc_ctrlchar) && *line!='\0')
495 line+=1; /* skip final quote */
502 #if !defined SC_LIGHT
504 assert(commentidx<COMMENT_LIMIT+COMMENT_MARGIN);
505 comment[commentidx]='\0';
506 if (strlen(comment)>0)
507 insert_docstring(comment);
514 * Attempts to interpret a numeric symbol as a boolean value. On success
515 * it returns the number of characters processed (so the line pointer can be
516 * adjusted) and the value is stored in "val". Otherwise it returns 0 and
519 * A boolean value must start with "0b"
521 static int btoi(cell *val,const unsigned char *curptr)
523 const unsigned char *ptr;
527 if (*ptr=='0' && *(ptr+1)=='b') {
529 while (*ptr=='0' || *ptr=='1' || *ptr=='_') {
531 *val=(*val<<1) | (*ptr-'0');
537 if (alphanum(*ptr)) /* number must be delimited by non-alphanumeric char */
540 return (int)(ptr-curptr);
545 * Attempts to interpret a numeric symbol as a decimal value. On success
546 * it returns the number of characters processed and the value is stored in
547 * "val". Otherwise it returns 0 and "val" is garbage.
549 static int dtoi(cell *val,const unsigned char *curptr)
551 const unsigned char *ptr;
555 if (!isdigit(*ptr)) /* should start with digit */
557 while (isdigit(*ptr) || *ptr=='_') {
559 *val=(*val*10)+(*ptr-'0');
562 if (alphanum(*ptr)) /* number must be delimited by non-alphanumerical */
564 if (*ptr=='.' && isdigit(*(ptr+1)))
565 return 0; /* but a fractional part must not be present */
566 return (int)(ptr-curptr);
571 * Attempts to interpret a numeric symbol as a hexadecimal value. On
572 * success it returns the number of characters processed and the value is
573 * stored in "val". Otherwise it return 0 and "val" is garbage.
575 static int htoi(cell *val,const unsigned char *curptr)
577 const unsigned char *ptr;
581 if (!isdigit(*ptr)) /* should start with digit */
583 if (*ptr=='0' && *(ptr+1)=='x') { /* C style hexadecimal notation */
585 while (ishex(*ptr) || *ptr=='_') {
592 *val+= (tolower(*ptr)-'a'+10);
602 return (int)(ptr-curptr);
606 static double pow10(int value)
627 * Attempts to interpret a numeric symbol as a rational number, either as
628 * IEEE 754 single/double precision floating point or as a fixed point integer.
629 * On success it returns the number of characters processed and the value is
630 * stored in "val". Otherwise it returns 0 and "val" is unchanged.
632 * Pawn has stricter definition for rational numbers than most:
633 * o the value must start with a digit; ".5" is not a valid number, you
635 * o a period must appear in the value, even if an exponent is given; "2e3"
636 * is not a valid number, you should write "2.0e3"
637 * o at least one digit must follow the period; "6." is not a valid number,
638 * you should write "6.0"
640 static int ftoi(cell *val,const unsigned char *curptr)
642 const unsigned char *ptr;
643 double fnum,ffrac,fmult;
644 unsigned long dnum,dbase;
647 assert(rational_digits>=0 && rational_digits<9);
648 for (i=0,dbase=1; i<rational_digits; i++)
653 if (!isdigit(*ptr)) /* should start with digit */
655 while (isdigit(*ptr) || *ptr=='_') {
657 fnum=(fnum*10.0)+(*ptr-'0');
658 dnum=(dnum*10L)+(*ptr-'0')*dbase;
663 return 0; /* there must be a period */
665 if (!isdigit(*ptr)) /* there must be at least one digit after the dot */
670 while (isdigit(*ptr) || *ptr=='_') {
672 ffrac=(ffrac*10.0)+(*ptr-'0');
675 dnum += (*ptr-'0')*dbase;
676 if (dbase==0L && sc_rationaltag && rational_digits>0 && !ignore) {
677 error(222); /* number of digits exceeds rational number precision */
683 fnum += ffrac*fmult; /* form the number so far */
684 if (*ptr=='e') { /* optional fractional part */
693 if (!isdigit(*ptr)) /* 'e' should be followed by a digit */
696 while (isdigit(*ptr)) {
697 exp=(exp*10)+(*ptr-'0');
701 fmult=pow10(exp*sign);
703 fmult=pow(10,exp*sign);
706 dnum *= (unsigned long)(fmult+0.5);
709 /* decide how to store the number */
710 if (sc_rationaltag==0) {
711 error(70); /* rational number support was not enabled */
713 } else if (rational_digits==0) {
715 #if PAWN_CELL_SIZE==32
716 float value=(float)fnum;
717 *val=*((cell *)&value);
718 #if 0 /* SourceMod - not needed */
719 /* I assume that the C/C++ compiler stores "float" values in IEEE 754
720 * format (as mandated in the ANSI standard). Test this assumption
722 * Note: problems have been reported with GCC 3.2.x, version 3.3.x works.
724 { float test1 = 0.0, test2 = 50.0, test3 = -50.0;
726 /* test 0.0 == all bits 0 */
727 assert(*(uint32_t*)&test1==0x00000000L);
728 /* test sign & magnitude format */
729 assert(((*(uint32_t*)&test2) ^ (*(uint32_t*)&test3)) == (bit << (PAWN_CELL_SIZE-1)));
730 /* test a known value */
731 assert(*(uint32_t*)&test2==0x42480000L);
734 #elif PAWN_CELL_SIZE==64
735 *val=*((cell *)&fnum);
736 #if 0 /* SourceMod - not needed */
737 /* I assume that the C/C++ compiler stores "double" values in IEEE 754
738 * format (as mandated in the ANSI standard).
740 { float test1 = 0.0, test2 = 50.0, test3 = -50.0;
742 /* test 0.0 == all bits 0 */
743 assert(*(uint64_t*)&test1==0x00000000L);
744 /* test sign & magnitude format */
745 assert(((*(uint64_t*)&test2) ^ (*(uint64_t*)&test3)) == (bit << (PAWN_CELL_SIZE-1)));
749 #error Unsupported cell size
756 return (int)(ptr-curptr);
761 * Reads in a number (binary, decimal or hexadecimal). It returns the number
762 * of characters processed or 0 if the symbol couldn't be interpreted as a
763 * number (in this case the argument "val" remains unchanged). This routine
764 * relies on the 'early dropout' implementation of the logical or (||)
767 * Note: the routine doesn't check for a sign (+ or -). The - is checked
768 * for at "hier2()" (in fact, it is viewed as an operator, not as a
769 * sign) and the + is invalid (as in K&R C, and unlike ANSI C).
771 static int number(cell *val,const unsigned char *curptr)
776 if ((i=btoi(&value,curptr))!=0 /* binary? */
777 || (i=htoi(&value,curptr))!=0 /* hexadecimal? */
778 || (i=dtoi(&value,curptr))!=0) /* decimal? */
783 return 0; /* else not a number */
787 static void chrcat(char *str,char chr)
789 str=strchr(str,'\0');
794 static int preproc_expr(cell *val,int *tag)
801 /* Disable staging; it should be disabled already because
802 * expressions may not be cut off half-way between conditional
803 * compilations. Reset the staging index, but keep the code
806 if (stgget(&index,&code_index)) {
807 error(57); /* unfinished expression */
808 stgdel(0,code_index);
811 assert((lptr-pline)<(int)strlen((char*)pline)); /* lptr must point inside the string */
812 #if !defined NO_DEFINE
813 /* preprocess the string */
814 substallpatterns(pline,sLINEMAX);
815 assert((lptr-pline)<(int)strlen((char*)pline)); /* lptr must STILL point inside the string */
817 /* append a special symbol to the string, so the expression
818 * analyzer won't try to read a next line when it encounters
821 assert(strlen((char*)pline)<sLINEMAX);
822 term=strchr((char*)pline,'\0');
824 chrcat((char*)pline,PREPROC_TERM); /* the "DEL" code (see SC.H) */
825 result=constexpr(val,tag,NULL); /* get value (or 0 on error) */
826 *term='\0'; /* erase the token (if still present) */
827 lexclr(FALSE); /* clear any "pushed" tokens */
832 * Returns returns a pointer behind the closing quote or to the other
833 * character that caused the input to be ended.
835 static const unsigned char *getstring(unsigned char *dest,int max,const unsigned char *line)
837 assert(dest!=NULL && line!=NULL);
839 while (*line<=' ' && *line!='\0')
840 line++; /* skip whitespace */
844 while (*line!='"' && *line!='\0') {
851 line++; /* skip closing " */
853 error(37); /* invalid string */
855 error(37); /* invalid string */
873 * Recognizes the compiler directives. The function returns:
874 * CMD_NONE the line must be processed
875 * CMD_TERM a pending expression must be completed before processing further lines
876 * Other value: the line must be skipped, because:
877 * CMD_CONDFALSE false "#if.." code
878 * CMD_EMPTYLINE line is empty
879 * CMD_INCLUDE the line contains a #include directive
880 * CMD_DEFINE the line contains a #subst directive
881 * CMD_IF the line contains a #if/#else/#endif directive
882 * CMD_DIRECTIVE the line contains some other compiler directive
884 * Global variables: iflevel, ifstack (altered)
887 static int command(void)
895 while (*lptr<=' ' && *lptr!='\0')
898 return CMD_EMPTYLINE; /* empty line */
900 return SKIPPING ? CMD_CONDFALSE : CMD_NONE; /* it is not a compiler directive */
901 /* compiler directive found */
902 indent_nowarn=TRUE; /* allow loose indentation" */
903 lexclr(FALSE); /* clear any "pushed" tokens */
904 /* on a pending expression, force to return a silent ';' token and force to
907 if (!sc_needsemicolon && stgget(&index,&code_index)) {
912 ret=SKIPPING ? CMD_CONDFALSE : CMD_DIRECTIVE; /* preset 'ret' to CMD_DIRECTIVE (most common case) */
914 case tpIF: /* conditional compilation */
917 if (iflevel>=sCOMP_STACK)
918 error(102,"Conditional compilation stack"); /* table overflow */
921 break; /* break out of switch */
923 preproc_expr(&val,NULL); /* get value (or 0 on error) */
924 ifstack[iflevel-1]=(char)(val ? PARSEMODE : SKIPMODE);
932 error(26); /* no matching #if */
935 /* check for earlier #else */
936 if ((ifstack[iflevel-1] & HANDLED_ELSE)==HANDLED_ELSE) {
938 error(61); /* #elseif directive may not follow an #else */
940 error(60); /* multiple #else directives between #if ... #endif */
944 /* if there has been a "parse mode" on this level, set "skip mode",
945 * otherwise, clear "skip mode"
947 if ((ifstack[iflevel-1] & PARSEMODE)==PARSEMODE) {
948 /* there has been a parse mode already on this level, so skip the rest */
949 ifstack[iflevel-1] |= (char)SKIPMODE;
950 /* if we were already skipping this section, allow expressions with
951 * undefined symbols; otherwise check the expression to catch errors
954 if (skiplevel==iflevel)
955 preproc_expr(&val,NULL); /* get, but ignore the expression */
957 lptr=strchr(lptr,'\0');
960 /* previous conditions were all FALSE */
962 /* if we were already skipping this section, allow expressions with
963 * undefined symbols; otherwise check the expression to catch errors
965 if (skiplevel==iflevel) {
966 preproc_expr(&val,NULL); /* get value (or 0 on error) */
968 lptr=strchr(lptr,'\0');
971 ifstack[iflevel-1]=(char)(val ? PARSEMODE : SKIPMODE);
973 /* a simple #else, clear skip mode */
974 ifstack[iflevel-1] &= (char)~SKIPMODE;
984 error(26); /* no matching "#if" */
988 if (iflevel<skiplevel)
993 case tINCLUDE: /* #include directive */
997 doinclude(tok==tpTRYINCLUDE);
1001 char pathname[_MAX_PATH];
1002 lptr=getstring((unsigned char*)pathname,sizeof pathname,lptr);
1003 if (strlen(pathname)>0) {
1005 inpfname=duplicatestring(pathname);
1007 error(103); /* insufficient memory */
1014 if (lex(&val,&str)!=tNUMBER)
1015 error(8); /* invalid/non-constant expression */
1021 if (!SKIPPING && (sc_debug & sCHKBOUNDS)!=0) {
1022 for (str=(char*)lptr; *str<=' ' && *str!='\0'; str++)
1023 /* nothing */; /* save start of expression */
1024 preproc_expr(&val,NULL); /* get constant expression (or 0 on error) */
1026 error(110,str); /* assertion failed */
1032 if (lex(&val,&str)==tSYMBOL) {
1033 if (strcmp(str,"amxlimit")==0) {
1034 preproc_expr(&pc_amxlimit,NULL);
1035 } else if (strcmp(str,"amxram")==0) {
1036 preproc_expr(&pc_amxram,NULL);
1037 } else if (strcmp(str,"codepage")==0) {
1038 char name[sNAMEMAX+1];
1039 while (*lptr<=' ' && *lptr!='\0')
1042 lptr=getstring((unsigned char*)name,sizeof name,lptr);
1045 for (i=0; i<sizeof name && alphanum(*lptr); i++,lptr++)
1050 error(108); /* codepage mapping file not found */
1051 } else if (strcmp(str,"compress")==0) {
1053 preproc_expr(&val,NULL);
1054 sc_compress=(int)val; /* switch code packing on/off */
1055 } else if (strcmp(str,"ctrlchar")==0) {
1056 while (*lptr<=' ' && *lptr!='\0')
1059 sc_ctrlchar=sc_ctrlchar_org;
1061 if (lex(&val,&str)!=tNUMBER)
1062 error(27); /* invalid character constant */
1063 sc_ctrlchar=(char)val;
1065 } else if (strcmp(str,"deprecated")==0) {
1066 while (*lptr<=' ' && *lptr!='\0')
1068 pc_deprecate=(char*)malloc(strlen((char*)lptr)+1);
1069 if (pc_deprecate!=NULL)
1070 strcpy(pc_deprecate,(char*)lptr);
1071 lptr=(unsigned char*)strchr((char*)lptr,'\0'); /* skip to end (ignore "extra characters on line") */
1072 } else if (strcmp(str,"dynamic")==0) {
1073 preproc_expr(&pc_stksize,NULL);
1074 } else if (!strcmp(str,"library")
1075 ||!strcmp(str,"reqclass")
1076 ||!strcmp(str,"loadlib")
1077 ||!strcmp(str,"explib")
1078 ||!strcmp(str,"expclass")
1079 ||!strcmp(str,"defclasslib")) {
1080 char name[sNAMEMAX+1],sname[sNAMEMAX+1];
1081 const char *prefix="";
1084 if (!strcmp(str,"library"))
1086 else if (!strcmp(str,"reqclass"))
1088 else if (!strcmp(str,"loadlib"))
1090 else if (!strcmp(str,"explib"))
1092 else if (!strcmp(str,"expclass"))
1094 else if (!strcmp(str,"defclasslib"))
1096 while (*lptr<=' ' && *lptr!='\0')
1099 lptr=getstring((unsigned char*)name,sizeof name,lptr);
1102 for (i=0; i<sizeof name && (alphanum(*lptr) || *lptr=='-'); i++,lptr++)
1105 if (!strncmp(str,"exp",3) || !strncmp(str,"def",3)) {
1106 while (*lptr && isspace(*lptr))
1108 for (i=1; i<sizeof sname && alphanum(*lptr); i++,lptr++)
1118 if (strlen(name)==0) {
1120 } else if (strcmp(name,"-")==0) {
1121 pc_addlibtable=FALSE;
1123 /* add the name if it does not yet exist in the table */
1124 char newname[sNAMEMAX+1];
1125 if (strlen(name)+strlen(prefix)+strlen(sname)<=sNAMEMAX) {
1126 strcpy(newname,prefix);
1127 strcat(newname,name);
1128 strcat(newname,sname);
1129 if (find_constval(&libname_tab,newname,0)==NULL) {
1130 if (!strcmp(str,"library") || !strcmp(str,"reqclass")) {
1131 curlibrary=append_constval(&libname_tab,newname,1,0);
1133 append_constval(&libname_tab,newname,1,0);
1138 #if 0 /* more unused */
1139 } else if (strcmp(str,"pack")==0) {
1141 preproc_expr(&val,NULL); /* default = packed/unpacked */
1142 sc_packstr=(int)val;
1144 } else if (strcmp(str,"rational")==0) {
1145 char name[sNAMEMAX+1];
1148 /* first gather all information, start with the tag name */
1149 while (*lptr<=' ' && *lptr!='\0')
1151 for (i=0; i<sizeof name && alphanum(*lptr); i++,lptr++)
1154 /* then the precision (for fixed point arithmetic) */
1155 while (*lptr<=' ' && *lptr!='\0')
1158 preproc_expr(&digits,NULL);
1159 if (digits<=0 || digits>9) {
1160 error(68); /* invalid rational number precision */
1166 /* add the tag (make it public) and check the values */
1169 if (sc_rationaltag==0 || (sc_rationaltag==i && rational_digits==(int)digits)) {
1171 rational_digits=(int)digits;
1173 error(69); /* rational number format already set, can only be set once */
1175 } else if (strcmp(str,"semicolon")==0) {
1177 preproc_expr(&val,NULL);
1178 sc_needsemicolon=(int)val;
1179 } else if (strcmp(str,"tabsize")==0) {
1181 preproc_expr(&val,NULL);
1182 sc_tabsize=(int)val;
1183 } else if (strcmp(str,"align")==0) {
1185 } else if (strcmp(str,"unused")==0) {
1186 char name[sNAMEMAX+1];
1191 while (*lptr<=' ' && *lptr!='\0')
1193 for (i=0; i<sizeof name && alphanum(*lptr); i++,lptr++)
1196 /* get the symbol */
1199 sym=findglb(name,sSTATEVAR);
1201 sym->usage |= uREAD;
1202 if (sym->ident==iVARIABLE || sym->ident==iREFERENCE
1203 || sym->ident==iARRAY || sym->ident==iREFARRAY)
1204 sym->usage |= uWRITTEN;
1206 error(17,name); /* undefined symbol */
1208 /* see if a comma follows the name */
1209 while (*lptr<=' ' && *lptr!='\0')
1211 comma= (*lptr==',');
1216 error(207); /* unknown #pragma */
1219 error(207); /* unknown #pragma */
1236 /* write opcode to output file */
1239 while (*lptr<=' ' && *lptr!='\0')
1241 for (i=0; i<40 && (isalpha(*lptr) || *lptr=='.'); i++,lptr++)
1242 name[i]=(char)tolower(*lptr);
1247 code_idx+=opcodes(1);
1248 /* write parameter (if any) */
1249 while (*lptr<=' ' && *lptr!='\0')
1258 code_idx+=opargs(1);
1263 sym=findglb(str,sSTATEVAR);
1264 if (sym==NULL || sym->ident!=iFUNCTN && sym->ident!=iREFFUNC && (sym->usage & uDEFINE)==0) {
1265 error(17,str); /* undefined symbol */
1267 outval(sym->addr,FALSE);
1268 /* mark symbol as "used", unknown whether for read or write */
1269 markusage(sym,uREAD | uWRITTEN);
1270 code_idx+=opargs(1);
1275 extern char *sc_tokens[];/* forward declaration */
1277 sprintf(s2,"%c",(char)tok);
1279 strcpy(s2,sc_tokens[tok-tFIRST]);
1280 error(1,sc_tokens[tSYMBOL-tFIRST],s2);
1290 #if !defined NO_DEFINE
1294 char *pattern,*substitution;
1295 const unsigned char *start,*end;
1296 int count,prefixlen;
1298 /* find the pattern to match */
1299 while (*lptr<=' ' && *lptr!='\0')
1301 start=lptr; /* save starting point of the match pattern */
1303 while (*lptr>' ' && *lptr!='\0') {
1304 litchar(&lptr,0); /* litchar() advances "lptr" and handles escape characters */
1308 /* check pattern to match */
1309 if (!alpha(*start)) {
1310 error(74); /* pattern must start with an alphabetic character */
1313 /* store matched pattern */
1314 pattern=(char*)malloc(count+1);
1316 error(103); /* insufficient memory */
1321 assert(*lptr!='\0');
1322 pattern[count++]=(char)litchar(&lptr,0);
1324 pattern[count]='\0';
1325 /* special case, erase trailing variable, because it could match anything */
1326 if (count>=2 && isdigit(pattern[count-1]) && pattern[count-2]=='%')
1327 pattern[count-2]='\0';
1328 /* find substitution string */
1329 while (*lptr<=' ' && *lptr!='\0')
1331 start=lptr; /* save starting point of the match pattern */
1334 while (*lptr!='\0') {
1335 /* keep position of the start of trailing whitespace */
1347 /* store matched substitution */
1348 substitution=(char*)malloc(count+1); /* +1 for '\0' */
1349 if (substitution==NULL)
1350 error(103); /* insufficient memory */
1355 assert(*lptr!='\0');
1356 substitution[count++]=*lptr++;
1358 substitution[count]='\0';
1359 /* check whether the definition already exists */
1360 for (prefixlen=0,start=(unsigned char*)pattern; alphanum(*start); prefixlen++,start++)
1362 assert(prefixlen>0);
1363 if ((def=find_subst(pattern,prefixlen))!=NULL) {
1364 if (strcmp(def->first,pattern)!=0 || strcmp(def->second,substitution)!=0)
1365 error(201,pattern); /* redefinition of macro (non-identical) */
1366 delete_subst(pattern,prefixlen);
1368 /* add the pattern/substitution pair to the list */
1369 assert(strlen(pattern)>0);
1370 insert_subst(pattern,substitution,prefixlen);
1378 if (lex(&val,&str)==tSYMBOL) {
1379 ret=delete_subst(str,strlen(str));
1381 /* also undefine normal constants */
1382 symbol *sym=findconst(str,NULL);
1383 if (sym!=NULL && (sym->usage & (uENUMROOT | uENUMFIELD))==0) {
1384 delete_symbol(&glbtab,sym);
1389 error(17,str); /* undefined symbol */
1391 error(20,str); /* invalid symbol name */
1398 while (*lptr<=' ' && *lptr!='\0')
1401 error(111,lptr); /* user error */
1404 error(31); /* unknown compiler directive */
1405 ret=SKIPPING ? CMD_CONDFALSE : CMD_NONE; /* process as normal line */
1410 #if !defined NO_DEFINE
1411 static int is_startstring(const unsigned char *string)
1413 if (*string=='\"' || *string=='\'')
1414 return TRUE; /* "..." */
1418 if (*string=='\"' || *string=='\'')
1419 return TRUE; /* !"..." */
1420 if (*string==sc_ctrlchar) {
1422 if (*string=='\"' || *string=='\'')
1423 return TRUE; /* !\"..." */
1425 } else if (*string==sc_ctrlchar) {
1427 if (*string=='\"' || *string=='\'')
1428 return TRUE; /* \"..." */
1431 if (*string=='\"' || *string=='\'')
1432 return TRUE; /* \!"..." */
1439 static const unsigned char *skipstring(const unsigned char *string)
1444 while (*string=='!' || *string==sc_ctrlchar) {
1445 if (*string==sc_ctrlchar)
1451 assert(endquote=='"' || endquote=='\'');
1452 string++; /* skip open quote */
1453 while (*string!=endquote && *string!='\0')
1454 litchar(&string,flags);
1458 static const unsigned char *skippgroup(const unsigned char *string)
1479 close='\0'; /* only to avoid a compiler warning */
1483 while (*string!=close || nest>0) {
1486 else if (*string==close)
1488 else if (is_startstring(string))
1489 string=skipstring(string);
1497 static char *strdel(char *str,size_t len)
1499 size_t length=strlen(str);
1502 memmove(str, str+len, length-len+1); /* include EOS byte */
1506 static char *strins(char *dest,char *src,size_t srclen)
1508 size_t destlen=strlen(dest);
1509 assert(srclen<=strlen(src));
1510 memmove(dest+srclen, dest, destlen+1);/* include EOS byte */
1511 memcpy(dest, src, srclen);
1515 static int substpattern(unsigned char *line,size_t buffersize,char *pattern,char *substitution)
1518 const unsigned char *p,*s,*e;
1519 unsigned char *args[10];
1520 int match,arg,len,argsnum=0;
1522 memset(args,0,sizeof args);
1524 /* check the length of the prefix */
1525 for (prefixlen=0,s=(unsigned char*)pattern; alphanum(*s); prefixlen++,s++)
1527 assert(prefixlen>0);
1528 assert(strncmp((char*)line,pattern,prefixlen)==0);
1530 /* pattern prefix matches; match the rest of the pattern, gather
1534 p=(unsigned char*)pattern+prefixlen;
1535 match=TRUE; /* so far, pattern matches */
1536 while (match && *s!='\0' && *p!='\0') {
1541 assert(arg>=0 && arg<=9);
1542 p++; /* skip parameter id */
1544 /* match the source string up to the character after the digit
1545 * (skipping strings in the process
1548 while (*e!=*p && *e!='\0' && *e!='\n') {
1549 if (is_startstring(e)) /* skip strings */
1551 else if (strchr("({[",*e)!=NULL) /* skip parenthized groups */
1554 e++; /* skip non-alphapetic character (or closing quote of
1555 * a string, or the closing paranthese of a group) */
1557 /* store the parameter (overrule any earlier) */
1558 if (args[arg]!=NULL)
1563 args[arg]=(unsigned char*)malloc(len+1);
1564 if (args[arg]==NULL)
1565 error(103); /* insufficient memory */
1566 strlcpy((char*)args[arg],(char*)s,len+1);
1567 /* character behind the pattern was matched too */
1570 } else if (*e=='\n' && *p==';' && *(p+1)=='\0' && !sc_needsemicolon) {
1571 s=e; /* allow a trailing ; in the pattern match to end of line */
1573 assert(*e=='\0' || *e=='\n');
1581 } else if (*p==';' && *(p+1)=='\0' && !sc_needsemicolon) {
1582 /* source may be ';' or end of the line */
1583 while (*s<=' ' && *s!='\0')
1584 s++; /* skip white space */
1585 if (*s!=';' && *s!='\0')
1587 p++; /* skip the semicolon in the pattern */
1590 /* skip whitespace between two non-alphanumeric characters, except
1591 * for two identical symbols
1593 assert((char*)p>pattern);
1594 if (!alphanum(*p) && *(p-1)!=*p)
1595 while (*s<=' ' && *s!='\0')
1596 s++; /* skip white space */
1597 ch=litchar(&p,0); /* this increments "p" */
1601 s++; /* this character matches */
1605 if (match && *p=='\0') {
1606 /* if the last character to match is an alphanumeric character, the
1607 * current character in the source may not be alphanumeric
1609 assert(p>(unsigned char*)pattern);
1610 if (alphanum(*(p-1)) && alphanum(*s))
1615 /* calculate the length of the substituted string */
1616 for (e=(unsigned char*)substitution,len=0; *e!='\0'; e++) {
1617 if (*e=='%' && isdigit(*(e+1)) && argsnum) {
1619 assert(arg>=0 && arg<=9);
1620 if (args[arg]!=NULL) {
1621 len+=strlen((char*)args[arg]);
1630 /* check length of the string after substitution */
1631 if (strlen((char*)line) + len - (int)(s-line) > buffersize) {
1632 error(75); /* line too long */
1634 /* substitute pattern */
1635 strdel((char*)line,(int)(s-line));
1636 for (e=(unsigned char*)substitution,s=line; *e!='\0'; e++) {
1637 if (*e=='%' && isdigit(*(e+1))) {
1639 assert(arg>=0 && arg<=9);
1640 if (args[arg]!=NULL) {
1641 strins((char*)s,(char*)args[arg],strlen((char*)args[arg]));
1642 s+=strlen((char*)args[arg]);
1645 error(236); /* parameter does not exist, incorrect #define pattern */
1646 strins((char*)s,(char*)e,2);
1649 e++; /* skip %, digit is skipped later */
1650 } else if (*e == '"') {
1652 if (is_startstring(e)) {
1654 strins((char*)s,(char *)p,(e-p+1));
1657 strins((char*)s,(char*)e,1);
1661 strins((char*)s,(char*)e,1);
1668 for (arg=0; arg<10; arg++)
1669 if (args[arg]!=NULL)
1675 static void substallpatterns(unsigned char *line,int buffersize)
1677 unsigned char *start, *end;
1682 while (*start!='\0') {
1683 /* find the start of a prefix (skip all non-alphabetic characters),
1686 while (!alpha(*start) && *start!='\0') {
1688 if (is_startstring(start)) {
1689 start=(unsigned char *)skipstring(start);
1691 break; /* abort loop on error */
1693 start++; /* skip non-alphapetic character (or closing quote of a string) */
1696 break; /* abort loop on error */
1697 /* if matching the operator "defined", skip it plus the symbol behind it */
1698 if (strncmp((char*)start,"defined",7)==0 && !isalpha((char)*(start+7))) {
1699 start+=7; /* skip "defined" */
1700 /* skip white space & parantheses */
1701 while (*start<=' ' && *start!='\0' || *start=='(')
1703 /* skip the symbol behind it */
1704 while (alphanum(*start))
1706 /* drop back into the main loop */
1709 /* get the prefix (length), look for a matching definition */
1712 while (alphanum(*end)) {
1716 assert(prefixlen>0);
1717 subst=find_subst((char*)start,prefixlen);
1719 /* properly match the pattern and substitute */
1720 if (!substpattern(start,buffersize-(int)(start-line),subst->first,subst->second))
1721 start=end; /* match failed, skip this prefix */
1722 /* match succeeded: do not update "start", because the substitution text
1723 * may be matched by other macros
1726 start=end; /* no macro with this prefix, skip this prefix */
1734 * Reads a line by readline() into "pline" and performs basic preprocessing:
1735 * deleting comments, skipping lines with false "#if.." code and recognizing
1736 * other compiler directives. There is an indirect recursion: lex() calls
1737 * preprocess() if a new line must be read, preprocess() calls command(),
1738 * which at his turn calls lex() to identify the token.
1740 * Global references: lptr (altered)
1742 * freading (referred to only)
1744 SC_FUNC void preprocess(void)
1752 stripcom(pline); /* ??? no need for this when reading back from list file (in the second pass) */
1753 lptr=pline; /* set "line pointer" to start of the parsing buffer */
1754 iscommand=command();
1755 if (iscommand!=CMD_NONE)
1756 errorset(sRESET,0); /* reset error flag ("panic mode") on empty line or directive */
1757 #if !defined NO_DEFINE
1758 if (iscommand==CMD_NONE) {
1759 assert(lptr!=term_expr);
1760 substallpatterns(pline,sLINEMAX);
1761 lptr=pline; /* reset "line pointer" to start of the parsing buffer */
1764 if (sc_status==statFIRST && sc_listing && freading
1765 && (iscommand==CMD_NONE || iscommand==CMD_EMPTYLINE || iscommand==CMD_DIRECTIVE))
1768 if (fline!=listline) {
1770 setlinedirect(fline);
1772 if (iscommand==CMD_EMPTYLINE)
1773 pc_writeasm(outf,"\n");
1775 pc_writeasm(outf,(char*)pline);
1777 } while (iscommand!=CMD_NONE && iscommand!=CMD_TERM && freading); /* enddo */
1780 static const unsigned char *unpackedstring(const unsigned char *lptr,int flags)
1782 while (*lptr!='\"' && *lptr!='\0') {
1783 if (*lptr=='\a') { /* ignore '\a' (which was inserted at a line concatenation) */
1787 litadd(litchar(&lptr,flags | UTF8MODE)); /* litchar() alters "lptr" */
1789 litadd(0); /* terminate string */
1793 static const unsigned char *packedstring(const unsigned char *lptr,int flags)
1798 i=0; /* start at least significant byte */
1800 while (*lptr!='\"' && *lptr!='\0') {
1801 if (*lptr=='\a') { /* ignore '\a' (which was inserted at a line concatenation) */
1805 c=litchar(&lptr,flags); /* litchar() alters "lptr" */
1806 if (c>=(ucell)(1 << sCHARBITS))
1807 error(43); /* character constant exceeds range */
1809 if (i==sizeof(ucell)-(sCHARBITS/8)) {
1817 /* save last code; make sure there is at least one terminating zero character */
1819 litadd(val); /* at least one zero character in "val" */
1821 litadd(0); /* add full cell of zeros */
1825 /* lex(lexvalue,lexsym) Lexical Analysis
1827 * lex() first deletes leading white space, then checks for multi-character
1828 * operators, keywords (including most compiler directives), numbers,
1829 * labels, symbols and literals (literal characters are converted to a number
1830 * and are returned as such). If every check fails, the line must contain
1831 * a single-character operator. So, lex() returns this character. In the other
1832 * case (something did match), lex() returns the number of the token. All
1833 * these tokens have been assigned numbers above 255.
1835 * Some tokens have "attributes":
1836 * tNUMBER the value of the number is return in "lexvalue".
1837 * tRATIONAL the value is in IEEE 754 encoding or in fixed point
1838 * encoding in "lexvalue".
1839 * tSYMBOL the first sNAMEMAX characters of the symbol are
1840 * stored in a buffer, a pointer to this buffer is
1841 * returned in "lexsym".
1842 * tLABEL the first sNAMEMAX characters of the label are
1843 * stored in a buffer, a pointer to this buffer is
1844 * returned in "lexsym".
1845 * tSTRING the string is stored in the literal pool, the index
1846 * in the literal pool to this string is stored in
1849 * lex() stores all information (the token found and possibly its attribute)
1850 * in global variables. This allows a token to be examined twice. If "_pushed"
1851 * is true, this information is returned.
1853 * Global references: lptr (altered)
1854 * fline (referred to only)
1855 * litidx (referred to only)
1856 * _lextok, _lexval, _lexstr
1862 static cell _lexval;
1863 static char _lexstr[sLINEMAX+1];
1864 static int _lexnewline;
1866 SC_FUNC void lexinit(void)
1868 stkidx=0; /* index for pushstk() and popstk() */
1869 iflevel=0; /* preprocessor: nesting of "#if" is currently 0 */
1870 skiplevel=0; /* preprocessor: not currently skipping */
1871 icomment=0; /* currently not in a multiline comment */
1872 _pushed=FALSE; /* no token pushed back into lex */
1876 char *sc_tokens[] = {
1877 "*=", "/=", "%=", "+=", "-=", "<<=", ">>>=", ">>=", "&=", "^=", "|=",
1878 "||", "&&", "==", "!=", "<=", ">=", "<<", ">>>", ">>", "++", "--",
1880 "assert", "*begin", "break", "case", "chars", "const", "continue", "default",
1881 "defined", "do", "else", "*end", "enum", "exit", "for", "forward", "funcenum", "goto",
1882 "if", "native", "new", "decl", "operator", "public", "return", "sizeof",
1883 "sleep", "state", "static", "stock", "switch", "tagof", "*then", "while",
1884 "#assert", "#define", "#else", "#elseif", "#emit", "#endif", "#endinput",
1885 "#endscript", "#error", "#file", "#if", "#include", "#line", "#pragma",
1886 "#tryinclude", "#undef",
1887 ";", ";", "-integer value-", "-rational value-", "-identifier-",
1888 "-label-", "-string-"
1891 SC_FUNC int lex(cell *lexvalue,char **lexsym)
1893 int i,toolong,newline,stringflags;
1895 const unsigned char *starttoken;
1898 _pushed=FALSE; /* reset "_pushed" flag */
1904 _lextok=0; /* preset all values */
1913 newline= (lptr==pline); /* does lptr point to start of line buffer */
1914 while (*lptr<=' ') { /* delete leading white space */
1916 preprocess(); /* preprocess resets "lptr" */
1919 if (lptr==term_expr) /* special sequence to terminate a pending expression */
1920 return (_lextok=tENDEXPR);
1921 _lexnewline=TRUE; /* set this after preprocess(), because
1922 * preprocess() calls lex() recursively */
1930 for (i=0; i<(int)(lptr-pline); i++)
1931 if (pline[i]=='\t' && sc_tabsize>0)
1932 stmtindent += (int)(sc_tabsize - (stmtindent+sc_tabsize) % sc_tabsize);
1939 while (i<=tMIDDLE) { /* match multi-character operators */
1940 if (*lptr==**tokptr && match(*tokptr,FALSE)) {
1942 if (pc_docexpr) /* optionally concatenate to documentation string */
1943 insert_autolist(*tokptr);
1949 while (i<=tLAST) { /* match reserved words and compiler directives */
1950 if (*lptr==**tokptr && match(*tokptr,TRUE)) {
1952 errorset(sRESET,0); /* reset error flag (clear the "panic mode")*/
1953 if (pc_docexpr) /* optionally concatenate to documentation string */
1954 insert_autolist(*tokptr);
1961 starttoken=lptr; /* save start pointer (for concatenating to documentation string) */
1962 if ((i=number(&_lexval,lptr))!=0) { /* number */
1966 } else if ((i=ftoi(&_lexval,lptr))!=0) {
1970 } else if (alpha(*lptr)) { /* symbol or label */
1971 /* Note: only sNAMEMAX characters are significant. The compiler
1972 * generates a warning if a symbol exceeds this length.
1977 while (alphanum(*lptr)){
1987 error(200,_lexstr,sNAMEMAX); /* symbol too long, truncated to sNAMEMAX chars */
1988 if (_lexstr[0]==PUBLIC_CHAR && _lexstr[1]=='\0') {
1989 _lextok=PUBLIC_CHAR; /* '@' all alone is not a symbol, it is an operator */
1990 } else if (_lexstr[0]=='_' && _lexstr[1]=='\0') {
1991 _lextok='_'; /* '_' by itself is not a symbol, it is a placeholder */
1993 if (*lptr==':' && *(lptr+1)!=':' && _lextok!=PUBLIC_CHAR) {
1995 _lextok=tLABEL; /* it wasn't a normal symbol, it was a label/tagname */
1996 lptr+=1; /* skip colon */
1997 } else if (find_constval(&tagname_tab,_lexstr,0)!=NULL) {
1998 /* this looks like a tag override (because a tag with this name
1999 * exists), but tags are not allowed right now, so it is probably an
2005 } else if (*lptr=='\"' || *lptr==sc_ctrlchar && *(lptr+1)=='\"')
2006 { /* unpacked string literal */
2008 stringflags= (*lptr==sc_ctrlchar) ? RAWMODE : 0;
2009 *lexvalue=_lexval=litidx;
2010 lptr+=1; /* skip double quote */
2011 if ((stringflags & RAWMODE)!=0)
2012 lptr+=1; /* skip "escape" character too */
2013 /* Note that this should always be packedstring() for SourcePawn */
2014 lptr=sc_packstr ? packedstring(lptr,stringflags) : unpackedstring(lptr,stringflags);
2016 lptr+=1; /* skip final quote */
2018 error(37); /* invalid (non-terminated) string */
2019 } else if (*lptr=='!' && *(lptr+1)=='\"'
2020 || *lptr=='!' && *(lptr+1)==sc_ctrlchar && *(lptr+2)=='\"'
2021 || *lptr==sc_ctrlchar && *(lptr+1)=='!' && *(lptr+2)=='\"')
2022 { /* packed string literal */
2024 stringflags= (*lptr==sc_ctrlchar || *(lptr+1)==sc_ctrlchar) ? RAWMODE : 0;
2025 *lexvalue=_lexval=litidx;
2026 lptr+=2; /* skip exclamation point and double quote */
2027 if ((stringflags & RAWMODE)!=0)
2028 lptr+=1; /* skip "escape" character too */
2029 lptr=sc_packstr ? unpackedstring(lptr,stringflags) : packedstring(lptr,stringflags);
2031 lptr+=1; /* skip final quote */
2033 error(37); /* invalid (non-terminated) string */
2034 } else if (*lptr=='\'') { /* character literal */
2035 lptr+=1; /* skip quote */
2037 *lexvalue=_lexval=litchar(&lptr,UTF8MODE);
2039 lptr+=1; /* skip final quote */
2041 error(27); /* invalid character constant (must be one character) */
2042 } else if (*lptr==';') { /* semicolumn resets "error" flag */
2045 errorset(sRESET,0); /* reset error flag (clear the "panic mode")*/
2047 _lextok=*lptr; /* if every match fails, return the character */
2048 lptr+=1; /* increase the "lptr" pointer */
2051 if (pc_docexpr) { /* optionally concatenate to documentation string */
2052 char *docstr=(char*)malloc(((int)(lptr-starttoken)+1)*sizeof(char));
2054 strlcpy(docstr,(char*)starttoken,(int)(lptr-starttoken)+1);
2055 insert_autolist(docstr);
2064 * Pushes a token back, so the next call to lex() will return the token
2065 * last examined, instead of a new token.
2067 * Only one token can be pushed back.
2069 * In fact, lex() already stores the information it finds into global
2070 * variables, so all that is to be done is set a flag that informs lex()
2071 * to read and return the information from these variables, rather than
2072 * to read in a new token from the input file.
2074 SC_FUNC void lexpush(void)
2076 assert(_pushed==FALSE);
2082 * Sets the variable "_pushed" to 0 to make sure lex() will read in a new
2083 * symbol (a not continue with some old one). This is required upon return
2084 * from Assembler mode, and in a few cases after detecting an syntax error.
2086 SC_FUNC void lexclr(int clreol)
2090 lptr=(unsigned char*)strchr((char*)pline,'\0');
2097 * This routine is useful if only a simple check is needed. If the token
2098 * differs from the one expected, it is pushed back.
2099 * This function returns 1 for "token found" and 2 for "implied statement
2100 * termination token" found --the statement termination is an end of line in
2101 * an expression where there is no pending operation. Such an implied token
2102 * (i.e. not present in the source code) should not be pushed back, which is
2103 * why it is sometimes important to distinguish the two.
2105 SC_FUNC int matchtoken(int token)
2112 if (tok==token || token==tTERM && (tok==';' || tok==tENDEXPR)) {
2114 } else if (!sc_needsemicolon && token==tTERM && (_lexnewline || !freading)) {
2115 /* Push "tok" back, because it is the token following the implicit statement
2116 * termination (newline) token.
2128 * Returns additional information of a token after using "matchtoken()"
2129 * or needtoken(). It does no harm using this routine after a call to
2130 * "lex()", but lex() already returns the same information.
2132 * The token itself is the return value. Normally, this one is already known.
2134 SC_FUNC int tokeninfo(cell *val,char **str)
2136 /* if the token was pushed back, tokeninfo() returns the token and
2137 * parameters of the *next* token, not of the *current* token.
2147 * This routine checks for a required token and gives an error message if
2148 * it isn't there (and returns 0/FALSE in that case). Like function matchtoken(),
2149 * this function returns 1 for "token found" and 2 for "statement termination
2150 * token" found; see function matchtoken() for details.
2152 * Global references: _lextok;
2154 SC_FUNC int needtoken(int token)
2159 if ((t=matchtoken(token))!=0) {
2162 /* token already pushed back */
2165 sprintf(s1,"%c",(char)token); /* single character token */
2167 strcpy(s1,sc_tokens[token-tFIRST]); /* multi-character symbol */
2169 strcpy(s2,"-end of file-");
2170 else if (_lextok<256)
2171 sprintf(s2,"%c",(char)_lextok);
2173 strcpy(s2,sc_tokens[_lextok-tFIRST]);
2174 error(1,s1,s2); /* expected ..., but found ... */
2181 * Compares a series of characters from the input file with the characters
2182 * in "st" (that contains a token). If the token on the input file matches
2183 * "st", the input file pointer "lptr" is adjusted to point to the next
2184 * token, otherwise "lptr" remains unaltered.
2186 * If the parameter "end: is true, match() requires that the first character
2187 * behind the recognized token is non-alphanumeric.
2189 * Global references: lptr (altered)
2191 static int match(char *st,int end)
2194 const unsigned char *ptr;
2199 if ((unsigned char)st[k]!=*ptr)
2204 if (end) { /* symbol must terminate with non-alphanumeric char */
2208 lptr=ptr; /* match found, skip symbol */
2212 static void chk_grow_litq(void)
2214 if (litidx>=litmax) {
2217 litmax+=sDEF_LITMAX;
2218 p=(cell *)realloc(litq,litmax*sizeof(cell));
2220 error(102,"literal table"); /* literal table overflow (fatal error) */
2227 * Adds a value at the end of the literal queue. The literal queue is used
2228 * for literal strings used in functions and for initializing array variables.
2230 * Global references: litidx (altered)
2233 SC_FUNC void litadd(cell value)
2236 assert(litidx<litmax);
2237 litq[litidx++]=value;
2242 * Inserts a value into the literal queue. This is sometimes necessary for
2243 * initializing multi-dimensional arrays.
2245 * Global references: litidx (altered)
2248 SC_FUNC void litinsert(cell value,int pos)
2251 assert(litidx<litmax);
2252 assert(pos>=0 && pos<=litidx);
2253 memmove(litq+(pos+1),litq+pos,(litidx-pos)*sizeof(cell));
2260 * Return current literal character and increase the pointer to point
2261 * just behind this literal character.
2263 * Note: standard "escape sequences" are suported, but the backslash may be
2264 * replaced by another character; the syntax '\ddd' is supported,
2265 * but ddd must be decimal!
2267 static cell litchar(const unsigned char **lptr,int flags)
2270 const unsigned char *cptr;
2273 if ((flags & RAWMODE)!=0 || *cptr!=sc_ctrlchar) { /* no escape character */
2274 #if !defined NO_UTF8
2275 if (sc_is_utf8 && (flags & UTF8MODE)!=0) {
2276 c=get_utf8_char(cptr,&cptr);
2277 assert(c>=0); /* file was already scanned for conformance to UTF-8 */
2280 #if !defined NO_CODEPAGE
2281 c=cp_translate(cptr,&cptr);
2286 #if !defined NO_UTF8
2291 if (*cptr==sc_ctrlchar) {
2292 c=*cptr; /* \\ == \ (the escape character itself) */
2296 case 'a': /* \a == audible alarm */
2300 case 'b': /* \b == backspace */
2304 case 'e': /* \e == escape */
2308 case 'f': /* \f == form feed */
2312 case 'n': /* \n == NewLine character */
2316 case 'r': /* \r == carriage return */
2320 case 't': /* \t == horizontal TAB */
2324 case 'v': /* \v == vertical TAB */
2331 while (ishex(*cptr)) {
2333 c=(c<<4)+(*cptr-'0');
2335 c=(c<<4)+(tolower(*cptr)-'a'+10);
2339 cptr++; /* swallow a trailing ';' */
2341 case '\'': /* \' == ' (single quote) */
2342 case '"': /* \" == " (single quote) */
2343 case '%': /* \% == % (percent) */
2348 if (isdigit(*cptr)) { /* \ddd */
2350 while (*cptr>='0' && *cptr<='9') /* decimal! */
2351 c=c*10 + *cptr++ - '0';
2353 cptr++; /* swallow a trailing ';' */
2355 error(27); /* invalid character constant */
2367 * Test if character "c" is alphabetic ("a".."z"), an underscore ("_")
2368 * or an "at" sign ("@"). The "@" is an extension to standard C.
2370 static int alpha(char c)
2372 return (isalpha(c) || c=='_' || c==PUBLIC_CHAR);
2377 * Test if character "c" is alphanumeric ("a".."z", "0".."9", "_" or "@")
2379 SC_FUNC int alphanum(char c)
2381 return (alpha(c) || isdigit(c));
2386 * Test if character "c" is a hexadecimal digit ("0".."9" or "a".."f").
2388 SC_FUNC int ishex(char c)
2390 return (c>='0' && c<='9') || (c>='a' && c<='f') || (c>='A' && c<='F');
2393 /* The local variable table must be searched backwards, so that the deepest
2394 * nesting of local variables is searched first. The simplest way to do
2395 * this is to insert all new items at the head of the list.
2396 * In the global list, the symbols are kept in sorted order, so that the
2397 * public functions are written in sorted order.
2399 static symbol *add_symbol(symbol *root,symbol *entry,int sort)
2404 while (root->next!=NULL && strcmp(entry->name,root->next->name)>0)
2407 if ((newsym=(symbol *)malloc(sizeof(symbol)))==NULL) {
2411 memcpy(newsym,entry,sizeof(symbol));
2412 newsym->next=root->next;
2417 static void free_symbol(symbol *sym)
2421 /* free all sub-symbol allocated memory blocks, depending on the
2422 * kind of the symbol
2425 if (sym->ident==iFUNCTN) {
2426 /* run through the argument list; "default array" arguments
2427 * must be freed explicitly; the tag list must also be freed */
2428 assert(sym->dim.arglist!=NULL);
2429 for (arg=sym->dim.arglist; arg->ident!=0; arg++) {
2430 if (arg->ident==iREFARRAY && arg->hasdefault)
2431 free(arg->defvalue.array.data);
2432 else if (arg->ident==iVARIABLE
2433 && ((arg->hasdefault & uSIZEOF)!=0 || (arg->hasdefault & uTAGOF)!=0))
2434 free(arg->defvalue.size.symname);
2435 assert(arg->tags!=NULL);
2438 free(sym->dim.arglist);
2439 if (sym->states!=NULL) {
2440 delete_consttable(sym->states);
2443 } else if (sym->ident==iVARIABLE || sym->ident==iARRAY) {
2444 if (sym->states!=NULL) {
2445 delete_consttable(sym->states);
2448 } else if (sym->ident==iCONSTEXPR && (sym->usage & uENUMROOT)==uENUMROOT) {
2449 /* free the constant list of an enum root */
2450 assert(sym->dim.enumlist!=NULL);
2451 delete_consttable(sym->dim.enumlist);
2452 free(sym->dim.enumlist);
2454 assert(sym->refer!=NULL);
2456 if (sym->documentation!=NULL)
2457 free(sym->documentation);
2461 SC_FUNC void delete_symbol(symbol *root,symbol *sym)
2463 /* find the symbol and its predecessor
2464 * (this function assumes that you will never delete a symbol that is not
2465 * in the table pointed at by "root")
2468 while (root->next!=sym) {
2473 /* unlink it, then free it */
2474 root->next=sym->next;
2478 SC_FUNC void delete_symbols(symbol *root,int level,int delete_labels,int delete_functions)
2480 symbol *sym,*parent_sym;
2481 constvalue *stateptr;
2484 /* erase only the symbols with a deeper nesting level than the
2485 * specified nesting level */
2486 while (root->next!=NULL) {
2488 if (sym->compound<level)
2490 switch (sym->ident) {
2492 mustdelete=delete_labels;
2496 /* do not delete global variables if functions are preserved */
2497 mustdelete=delete_functions;
2500 /* always delete references (only exist as function parameters) */
2504 /* a global iREFARRAY symbol is the return value of a function: delete
2505 * this only if "globals" must be deleted; other iREFARRAY instances
2506 * (locals) are also deleted
2508 mustdelete=delete_functions;
2509 for (parent_sym=sym->parent; parent_sym!=NULL && parent_sym->ident!=iFUNCTN; parent_sym=parent_sym->parent)
2510 assert(parent_sym->ident==iREFARRAY);
2511 assert(parent_sym==NULL || (parent_sym->ident==iFUNCTN && parent_sym->parent==NULL));
2512 if (parent_sym==NULL || parent_sym->ident!=iFUNCTN)
2516 /* delete constants, except predefined constants */
2517 mustdelete=delete_functions || (sym->usage & uPREDEF)==0;
2520 /* optionally preserve globals (variables & functions), but
2521 * NOT native functions
2523 mustdelete=delete_functions || (sym->usage & uNATIVE)!=0;
2524 assert(sym->parent==NULL);
2535 root->next=sym->next;
2538 /* if the function was prototyped, but not implemented in this source,
2539 * mark it as such, so that its use can be flagged
2541 if (sym->ident==iFUNCTN && (sym->usage & uDEFINE)==0)
2542 sym->usage |= uMISSING;
2543 if (sym->ident==iFUNCTN || sym->ident==iVARIABLE || sym->ident==iARRAY)
2544 sym->usage &= ~uDEFINE; /* clear "defined" flag */
2545 /* set all states as "undefined" too */
2546 if (sym->states!=NULL)
2547 for (stateptr=sym->states->next; stateptr!=NULL; stateptr=stateptr->next)
2549 /* for user defined operators, also remove the "prototyped" flag, as
2550 * user-defined operators *must* be declared before use
2552 if (sym->ident==iFUNCTN && !alpha(*sym->name))
2553 sym->usage &= ~uPROTOTYPED;
2554 root=sym; /* skip the symbol */
2559 /* The purpose of the hash is to reduce the frequency of a "name"
2560 * comparison (which is costly). There is little interest in avoiding
2561 * clusters in similar names, which is why this function is plain simple.
2563 SC_FUNC uint32_t namehash(const char *name)
2565 const unsigned char *ptr=(const unsigned char *)name;
2566 int len=strlen(name);
2570 return (len<<24Lu) + (ptr[0]<<16Lu) + (ptr[len-1]<<8Lu) + (ptr[len>>1Lu]);
2573 static symbol *find_symbol(const symbol *root,const char *name,int fnumber,int automaton,int *cmptag)
2575 symbol *firstmatch=NULL;
2576 symbol *sym=root->next;
2578 unsigned long hash=namehash(name);
2580 if (hash==sym->hash && strcmp(name,sym->name)==0 /* check name */
2581 && (sym->parent==NULL || sym->ident==iCONSTEXPR) /* sub-types (hierarchical types) are skipped, except for enum fields */
2582 && (sym->fnumber<0 || sym->fnumber==fnumber)) /* check file number for scope */
2584 assert(sym->states==NULL || sym->states->next!=NULL); /* first element of the state list is the "root" */
2585 if (sym->ident==iFUNCTN
2586 || automaton<0 && sym->states==NULL
2587 || automaton>=0 && sym->states!=NULL && state_getfsa(sym->states->next->index)==automaton)
2590 return sym; /* return first match */
2591 /* return closest match or first match; count number of matches */
2592 if (firstmatch==NULL)
2594 assert(cmptag!=NULL);
2597 if (*cmptag==sym->tag) {
2598 *cmptag=1; /* good match found, set number of matches to 1 */
2605 if (cmptag!=NULL && firstmatch!=NULL)
2610 static symbol *find_symbol_child(const symbol *root,const symbol *sym)
2612 symbol *ptr=root->next;
2614 if (ptr->parent==sym)
2621 /* Adds "bywhom" to the list of referrers of "entry". Typically,
2622 * bywhom will be the function that uses a variable or that calls
2625 SC_FUNC int refer_symbol(symbol *entry,symbol *bywhom)
2629 assert(bywhom!=NULL); /* it makes no sense to add a "void" referrer */
2630 assert(entry!=NULL);
2631 assert(entry->refer!=NULL);
2633 /* see if it is already there */
2634 for (count=0; count<entry->numrefers && entry->refer[count]!=bywhom; count++)
2636 if (count<entry->numrefers) {
2637 assert(entry->refer[count]==bywhom);
2641 /* see if there is an empty spot in the referrer list */
2642 for (count=0; count<entry->numrefers && entry->refer[count]!=NULL; count++)
2644 assert(count <= entry->numrefers);
2645 if (count==entry->numrefers) {
2647 int newsize=2*entry->numrefers;
2649 /* grow the referrer list */
2650 refer=(symbol**)realloc(entry->refer,newsize*sizeof(symbol*));
2652 return FALSE; /* insufficient memory */
2653 /* initialize the new entries */
2655 for (count=entry->numrefers; count<newsize; count++)
2656 entry->refer[count]=NULL;
2657 count=entry->numrefers; /* first empty spot */
2658 entry->numrefers=newsize;
2661 /* add the referrer */
2662 assert(entry->refer[count]==NULL);
2663 entry->refer[count]=bywhom;
2667 SC_FUNC void markusage(symbol *sym,int usage)
2670 sym->usage |= (char)usage;
2671 if ((usage & uWRITTEN)!=0)
2673 /* check if (global) reference must be added to the symbol */
2674 if ((usage & (uREAD | uWRITTEN))!=0) {
2675 /* only do this for global symbols */
2676 if (sym->vclass==sGLOBAL) {
2677 /* "curfunc" should always be valid, since statements may not occurs
2678 * outside functions; in the case of syntax errors, however, the
2679 * compiler may arrive through this function
2682 refer_symbol(sym,curfunc);
2690 * Returns a pointer to the global symbol (if found) or NULL (if not found)
2692 SC_FUNC symbol *findglb(const char *name,int filter)
2694 /* find a symbol with a matching automaton first */
2697 if (filter>sGLOBAL && sc_curstates>0) {
2698 /* find a symbol whose state list matches the current fsa */
2699 sym=find_symbol(&glbtab,name,fcurrent,state_getfsa(sc_curstates),NULL);
2700 if (sym!=NULL && sym->ident!=iFUNCTN) {
2701 /* if sym!=NULL, we found a variable in the automaton; now we should
2702 * also verify whether there is an intersection between the symbol's
2703 * state list and the current state list
2705 assert(sym->states!=NULL && sym->states->next!=NULL);
2706 if (!state_conflict_id(sc_curstates,sym->states->next->index))
2711 /* if no symbol with a matching automaton exists, find a variable/function
2712 * that has no state(s) attached to it
2715 sym=find_symbol(&glbtab,name,fcurrent,-1,NULL);
2721 * Returns a pointer to the local symbol (if found) or NULL (if not found).
2722 * See add_symbol() how the deepest nesting level is searched first.
2724 SC_FUNC symbol *findloc(const char *name)
2726 return find_symbol(&loctab,name,-1,-1,NULL);
2729 SC_FUNC symbol *findconst(const char *name,int *cmptag)
2733 sym=find_symbol(&loctab,name,-1,-1,cmptag); /* try local symbols first */
2734 if (sym==NULL || sym->ident!=iCONSTEXPR) /* not found, or not a constant */
2735 sym=find_symbol(&glbtab,name,fcurrent,-1,cmptag);
2736 if (sym==NULL || sym->ident!=iCONSTEXPR)
2738 assert(sym->parent==NULL || (sym->usage & uENUMFIELD)!=0);
2739 /* ^^^ constants have no hierarchy, but enumeration fields may have a parent */
2743 SC_FUNC symbol *finddepend(const symbol *parent)
2747 sym=find_symbol_child(&loctab,parent); /* try local symbols first */
2748 if (sym==NULL) /* not found */
2749 sym=find_symbol_child(&glbtab,parent);
2755 * Adds a symbol to the symbol table (either global or local variables,
2756 * or global and local constants).
2758 SC_FUNC symbol *addsym(const char *name,cell addr,int ident,int vclass,int tag,int usage)
2760 symbol entry, **refer;
2762 /* labels may only be defined once */
2763 assert(ident!=iLABEL || findloc(name)==NULL);
2765 /* create an empty referrer list */
2766 if ((refer=(symbol**)malloc(sizeof(symbol*)))==NULL) {
2767 error(103); /* insufficient memory */
2772 /* first fill in the entry */
2773 memset(&entry,0,sizeof entry);
2774 strcpy(entry.name,name);
2775 entry.hash=namehash(name);
2777 entry.codeaddr=code_idx;
2778 entry.vclass=(char)vclass;
2779 entry.ident=(char)ident;
2781 entry.usage=(char)usage;
2782 entry.fnumber=-1; /* assume global visibility (ignored for local symbols) */
2783 entry.lnumber=fline;
2787 /* then insert it in the list */
2788 if (vclass==sGLOBAL)
2789 return add_symbol(&glbtab,&entry,TRUE);
2791 return add_symbol(&loctab,&entry,FALSE);
2794 SC_FUNC symbol *addvariable(const char *name,cell addr,int ident,int vclass,int tag,
2795 int dim[],int numdim,int idxtag[])
2799 /* global variables may only be defined once
2800 * One complication is that functions returning arrays declare an array
2801 * with the same name as the function, so the assertion must allow for
2802 * this special case. Another complication is that variables may be
2803 * "redeclared" if they are local to an automaton (and findglb() will find
2804 * the symbol without states if no symbol with states exists).
2806 assert(vclass!=sGLOBAL || (sym=findglb(name,sGLOBAL))==NULL || (sym->usage & uDEFINE)==0
2807 || sym->ident==iFUNCTN && sym==curfunc
2808 || sym->states==NULL && sc_curstates>0);
2810 if (ident==iARRAY || ident==iREFARRAY) {
2811 symbol *parent=NULL,*top;
2813 sym=NULL; /* to avoid a compiler warning */
2814 for (level=0; level<numdim; level++) {
2815 top=addsym(name,addr,ident,vclass,tag,uDEFINE);
2816 top->dim.array.length=dim[level];
2817 top->dim.array.level=(short)(numdim-level-1);
2818 top->x.tags.index=idxtag[level];
2825 sym=addsym(name,addr,ident,vclass,tag,uDEFINE);
2832 * Returns te next internal label number. The global variable sc_labnum is
2833 * initialized to zero.
2835 SC_FUNC int getlabel(void)
2842 * Converts a number to a hexadecimal string and returns a pointer to that
2843 * string. This function is NOT re-entrant.
2845 SC_FUNC char *itoh(ucell val)
2847 static char itohstr[30];
2849 int i,nibble[16]; /* a 64-bit hexadecimal cell has 16 nibbles */
2852 #if PAWN_CELL_SIZE==16
2854 #elif PAWN_CELL_SIZE==32
2856 #elif PAWN_CELL_SIZE==64
2859 #error Unsupported cell size
2862 for (i=0; i<max; i+=1){
2863 nibble[i]=(int)(val & 0x0f); /* nibble 0 is lowest nibble */
2867 while (nibble[i]==0 && i>0) /* search for highest non-zero nibble */
2871 *ptr++=(char)('a'+(nibble[i]-10));
2873 *ptr++=(char)('0'+nibble[i]);
2876 *ptr='\0'; /* and a zero-terminator */