Added some useful IDA scripts (NPOTB).
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.
31 #if defined LINUX || defined __FreeBSD__ || defined __OpenBSD__
34 #include "sp_symhash.h"
37 #include <alloc/fortify.h>
40 /* flags for litchar() */
43 static cell litchar(const unsigned char **lptr,int flags);
44 static symbol *find_symbol(const symbol *root,const char *name,int fnumber,int automaton,int *cmptag);
46 static void substallpatterns(unsigned char *line,int buffersize);
47 static int match(char *st,int end);
48 static int alpha(char c);
50 #define SKIPMODE 1 /* bit field in "#if" stack */
51 #define PARSEMODE 2 /* bit field in "#if" stack */
52 #define HANDLED_ELSE 4 /* bit field in "#if" stack */
53 #define SKIPPING (skiplevel>0 && (ifstack[skiplevel-1] & SKIPMODE)==SKIPMODE)
55 static short icomment; /* currently in multiline comment? */
56 static char ifstack[sCOMP_STACK]; /* "#if" stack */
57 static short iflevel; /* nesting level if #if/#else/#endif */
58 static short skiplevel; /* level at which we started skipping (including nested #if .. #endif) */
59 static unsigned char term_expr[] = "";
60 static int listline=-1; /* "current line" for the list file */
63 static double pow10(double d)
72 * Uses a LIFO stack to store information. The stack is used by doinclude(),
73 * doswitch() (to hold the state of "swactive") and some other routines.
75 * Porting note: I made the bold assumption that an integer will not be
76 * larger than a pointer (it may be smaller). That is, the stack element
77 * is typedef'ed as a pointer type, but I also store integers on it. See
80 * Global references: stack,stkidx,stktop (private to pushstk(), popstk()
83 static stkitem *stack=NULL;
84 static int stkidx=0,stktop=0;
86 SC_FUNC void pushstk(stkitem val)
88 assert(stkidx<=stktop);
91 int newsize= (stktop==0) ? 16 : 2*stktop;
92 /* try to resize the stack */
93 assert(newsize>stktop);
94 newstack=(stkitem*)malloc(newsize*sizeof(stkitem));
96 error(122,"parser stack"); /* stack overflow (recursive include?) */
98 memcpy(newstack,stack,stkidx*sizeof(stkitem));
104 assert(stkidx<stktop);
109 SC_FUNC stkitem popstk(void)
113 s.i=-1; /* stack is empty */
118 return stack[stkidx];
121 SC_FUNC void clearstk(void)
123 assert(stack!=NULL || stktop==0);
132 SC_FUNC int plungequalifiedfile(char *name)
134 static char *extensions[] = { ".inc", ".p", ".pawn" };
141 fp=(FILE*)pc_opensrc(name);
142 ext=strchr(name,'\0'); /* save position */
144 /* try to append an extension */
145 strcpy(ext,extensions[ext_idx]);
146 fp=(FILE*)pc_opensrc(name);
148 *ext='\0'; /* on failure, restore filename */
151 } while (fp==NULL && ext_idx<(sizeof extensions / sizeof extensions[0]));
153 *ext='\0'; /* restore filename */
157 PUSHSTK_P(inpfname); /* pointer to current file name */
158 PUSHSTK_P(curlibrary);
161 assert(skiplevel==iflevel); /* these two are always the same when "parsing" */
162 PUSHSTK_I(sc_is_utf8);
166 inpfname=duplicatestring(name);/* set name of include file */
168 error(123); /* insufficient memory */
169 inpf=fp; /* set input file pointer to include file */
171 fline=0; /* set current line number to 0 */
173 icomment=0; /* not in a comment */
174 insert_dbgfile(inpfname);
175 setfiledirect(inpfname);
176 listline=-1; /* force a #line directive when changing the file */
177 sc_is_utf8=(short)scan_utf8(inpf,name);
181 SC_FUNC int plungefile(char *name,int try_currentpath,int try_includepaths)
185 if (try_currentpath) {
186 result=plungequalifiedfile(name);
188 /* failed to open the file in the active directory, try to open the file
189 * in the same directory as the current file --but first check whether
190 * there is a (relative) path for the current file
193 if ((ptr=strrchr(inpfname,DIRSEP_CHAR))!=0) {
194 int len=(int)(ptr-inpfname)+1;
195 if (len+strlen(name)<_MAX_PATH) {
196 char path[_MAX_PATH];
197 strlcpy(path,inpfname,len+1);
198 strlcat(path,name,sizeof path);
199 result=plungequalifiedfile(path);
205 if (try_includepaths && name[0]!=DIRSEP_CHAR) {
208 for (i=0; !result && (ptr=get_path(i))!=NULL; i++) {
209 char path[_MAX_PATH];
210 strlcpy(path,ptr,sizeof path);
211 strlcat(path,name,sizeof path);
212 result=plungequalifiedfile(path);
218 static void check_empty(const unsigned char *lptr)
220 /* verifies that the string contains only whitespace */
221 while (*lptr<=' ' && *lptr!='\0')
224 error(38); /* extra characters on line */
229 * Gets the name of an include file, pushes the old file on the stack and
230 * sets some options. This routine doesn't use lex(), since lex() doesn't
231 * recognize file names (and directories).
233 * Global references: inpf (altered)
238 static void doinclude(int silent)
240 char name[_MAX_PATH];
241 char symname[sNAMEMAX+1];
246 while (*lptr<=' ' && *lptr!='\0') /* skip leading whitespace */
248 if (*lptr=='<' || *lptr=='\"'){
249 c=(char)((*lptr=='\"') ? '\"' : '>'); /* termination character */
251 while (*lptr<=' ' && *lptr!='\0') /* skip whitespace after quote */
258 while (*lptr!=c && *lptr!='\0' && i<sizeof name - 1) /* find the end of the string */
260 while (i>0 && name[i-1]<=' ')
261 i--; /* strip trailing whitespace */
262 assert(i>=0 && i<sizeof name);
263 name[i]='\0'; /* zero-terminate the string */
265 if (*lptr!=c) { /* verify correct string termination */
266 error(37); /* invalid string */
270 check_empty(lptr+1); /* verify that the rest of the line is whitespace */
272 result=plungefile(name,(c!='>'),TRUE);
273 if (!result && !silent)
274 error(120,name); /* cannot read from ... (fatal error) */
279 * Reads in a new line from the input file pointed to by "inpf". readline()
280 * concatenates lines that end with a \ with the next line. If no more data
281 * can be read from the file, readline() attempts to pop off the previous file
282 * from the stack. If that fails too, it sets "freading" to 0.
284 * Global references: inpf,fline,inpfname,freading,icomment (altered)
286 static void readline(unsigned char *line)
296 if (inpf==NULL || pc_eofsrc(inpf)) {
298 error(49); /* invalid line continuation */
299 if (inpf!=NULL && inpf!=inpf_org)
302 if (i==-1) { /* All's done; popstk() returns "stack is empty" */
305 /* when there is nothing more to read, the #if/#else stack should
306 * be empty and we should not be in a comment
310 error(1,"#endif","-end of file-");
311 else if (icomment!=0)
312 error(1,"*/","-end of file-");
316 fcurrent=(short)POPSTK_I();
317 icomment=(short)POPSTK_I();
318 sc_is_utf8=(short)POPSTK_I();
319 iflevel=(short)POPSTK_I();
320 skiplevel=iflevel; /* this condition held before including the file */
321 assert(!SKIPPING); /* idem ditto */
322 curlibrary=(constvalue *)POPSTK_P();
323 free(inpfname); /* return memory allocated for the include file name */
324 inpfname=(char *)POPSTK_P();
325 inpf=(FILE *)POPSTK_P();
326 insert_dbgfile(inpfname);
327 setfiledirect(inpfname);
328 listline=-1; /* force a #line directive when changing the file */
331 if (pc_readsrc(inpf,line,num)==NULL) {
332 *line='\0'; /* delete line */
335 /* check whether to erase leading spaces */
337 unsigned char *ptr=line;
338 while (*ptr<=' ' && *ptr!='\0')
341 memmove(line,ptr,strlen((char*)ptr)+1);
344 /* check whether a full line was read */
345 if (strchr((char*)line,'\n')==NULL && !pc_eofsrc(inpf))
346 error(75); /* line too long */
347 /* check if the next line must be concatenated to this line */
348 if ((ptr=(unsigned char*)strchr((char*)line,'\n'))==NULL)
349 ptr=(unsigned char*)strchr((char*)line,'\r');
350 if (ptr!=NULL && ptr>line) {
351 assert(*(ptr+1)=='\0'); /* '\n' or '\r' should be last in the string */
352 while (ptr>line && *ptr<=' ')
353 ptr--; /* skip trailing whitespace */
356 /* set '\a' at the position of '\\' to make it possible to check
357 * for a line continuation in a single line comment (error 49)
360 *ptr='\0'; /* erase '\n' (and any trailing whitespace) */
363 num-=strlen((char*)line);
364 line+=strlen((char*)line);
367 } while (num>=0 && cont);
372 * Replaces all comments from the line by space characters. It updates
373 * a global variable ("icomment") for multiline comments.
375 * This routine also supports the C++ extension for single line comments.
376 * These comments are started with "//" and end at the end of the line.
378 * The function also detects (and manages) "documentation comments". The
379 * global variable "icomment" is set to 2 for documentation comments.
381 * Global references: icomment (private to "stripcom")
383 static void stripcom(unsigned char *line)
386 #if !defined SC_LIGHT
387 #define COMMENT_LIMIT 100
388 #define COMMENT_MARGIN 40 /* length of the longest word */
389 char comment[COMMENT_LIMIT+COMMENT_MARGIN];
392 static int prev_singleline=FALSE;
393 int singleline=prev_singleline;
395 prev_singleline=FALSE; /* preset */
400 if (*line=='*' && *(line+1)=='/') {
401 #if !defined SC_LIGHT
403 assert(commentidx<COMMENT_LIMIT+COMMENT_MARGIN);
404 comment[commentidx]='\0';
405 if (strlen(comment)>0)
406 insert_docstring(comment);
409 icomment=0; /* comment has ended */
410 *line=' '; /* replace '*' and '/' characters by spaces */
414 if (*line=='/' && *(line+1)=='*')
415 error(216); /* nested comment */
416 #if !defined SC_LIGHT
417 /* collect the comment characters in a string */
419 if (skipstar && (*line!='\0' && *line<=' ' || *line=='*')) {
420 /* ignore leading whitespace and '*' characters */
421 } else if (commentidx<COMMENT_LIMIT+COMMENT_MARGIN-1) {
422 comment[commentidx++]=(char)((*line!='\n') ? *line : ' ');
423 if (commentidx>COMMENT_LIMIT && *line!='\0' && *line<=' ') {
424 comment[commentidx]='\0';
425 insert_docstring(comment);
432 *line=' '; /* replace comments by spaces */
436 if (*line=='/' && *(line+1)=='*'){
437 icomment=1; /* start comment */
438 #if !defined SC_LIGHT
439 /* there must be two "*" behind the slash and then white space */
440 if (*(line+2)=='*' && *(line+3)<=' ') {
441 /* if we are not in a function, we must attach the previous block
442 * to the global documentation
444 if (curfunc==NULL && get_docstring(0)!=NULL)
445 sc_attachdocumentation(NULL);
446 icomment=2; /* documentation comment */
451 *line=' '; /* replace '/' and '*' characters by spaces */
456 } else if (*line=='/' && *(line+1)=='/'){ /* comment to end of line */
457 if (strchr((char*)line,'\a')!=NULL)
458 error(49); /* invalid line continuation */
459 #if !defined SC_LIGHT
460 if (*(line+2)=='/' && *(line+3)<=' ') {
461 /* documentation comment */
462 char *str=(char*)line+3;
464 while (*str<=' ' && *str!='\0')
465 str++; /* skip leading whitespace */
466 if ((end=strrchr(str,'\n'))!=NULL)
467 *end='\0';/* erase trailing '\n' */
468 /* if there is a disjunct block, we may need to attach the previous
469 * block to the global documentation
471 if (!singleline && curfunc==NULL && get_docstring(0)!=NULL)
472 sc_attachdocumentation(NULL);
473 insert_docstring(str);
474 prev_singleline=TRUE;
477 *line++='\n'; /* put "newline" at first slash */
478 *line='\0'; /* put "zero-terminator" at second slash */
480 if (*line=='\"' || *line=='\''){ /* leave literals unaltered */
481 c=*line; /* ending quote, single or double */
483 while ((*line!=c || *(line-1)==sc_ctrlchar) && *line!='\0')
485 line+=1; /* skip final quote */
492 #if !defined SC_LIGHT
494 assert(commentidx<COMMENT_LIMIT+COMMENT_MARGIN);
495 comment[commentidx]='\0';
496 if (strlen(comment)>0)
497 insert_docstring(comment);
504 * Attempts to interpret a numeric symbol as a boolean value. On success
505 * it returns the number of characters processed (so the line pointer can be
506 * adjusted) and the value is stored in "val". Otherwise it returns 0 and
509 * A boolean value must start with "0b"
511 static int btoi(cell *val,const unsigned char *curptr)
513 const unsigned char *ptr;
517 if (*ptr=='0' && *(ptr+1)=='b') {
519 while (*ptr=='0' || *ptr=='1' || *ptr=='_') {
521 *val=(*val<<1) | (*ptr-'0');
527 if (alphanum(*ptr)) /* number must be delimited by non-alphanumeric char */
530 return (int)(ptr-curptr);
535 * Attempts to interpret a numeric symbol as a decimal value. On success
536 * it returns the number of characters processed and the value is stored in
537 * "val". Otherwise it returns 0 and "val" is garbage.
539 static int dtoi(cell *val,const unsigned char *curptr)
541 const unsigned char *ptr;
545 if (!isdigit(*ptr)) /* should start with digit */
547 while (isdigit(*ptr) || *ptr=='_') {
549 *val=(*val*10)+(*ptr-'0');
552 if (alphanum(*ptr)) /* number must be delimited by non-alphanumerical */
554 if (*ptr=='.' && isdigit(*(ptr+1)))
555 return 0; /* but a fractional part must not be present */
556 return (int)(ptr-curptr);
561 * Attempts to interpret a numeric symbol as a hexadecimal value. On
562 * success it returns the number of characters processed and the value is
563 * stored in "val". Otherwise it return 0 and "val" is garbage.
565 static int htoi(cell *val,const unsigned char *curptr)
567 const unsigned char *ptr;
571 if (!isdigit(*ptr)) /* should start with digit */
573 if (*ptr=='0' && *(ptr+1)=='x') { /* C style hexadecimal notation */
575 while (ishex(*ptr) || *ptr=='_') {
582 *val+= (tolower(*ptr)-'a'+10);
592 return (int)(ptr-curptr);
597 * Attempts to interpret a numeric symbol as a rational number, either as
598 * IEEE 754 single/double precision floating point or as a fixed point integer.
599 * On success it returns the number of characters processed and the value is
600 * stored in "val". Otherwise it returns 0 and "val" is unchanged.
602 * Pawn has stricter definition for rational numbers than most:
603 * o the value must start with a digit; ".5" is not a valid number, you
605 * o a period must appear in the value, even if an exponent is given; "2e3"
606 * is not a valid number, you should write "2.0e3"
607 * o at least one digit must follow the period; "6." is not a valid number,
608 * you should write "6.0"
610 static int ftoi(cell *val,const unsigned char *curptr)
612 const unsigned char *ptr;
613 double fnum,ffrac,fmult;
614 unsigned long dnum,dbase;
617 assert(rational_digits>=0 && rational_digits<9);
618 for (i=0,dbase=1; i<rational_digits; i++)
623 if (!isdigit(*ptr)) /* should start with digit */
625 while (isdigit(*ptr) || *ptr=='_') {
627 fnum=(fnum*10.0)+(*ptr-'0');
628 dnum=(dnum*10L)+(*ptr-'0')*dbase;
633 return 0; /* there must be a period */
635 if (!isdigit(*ptr)) /* there must be at least one digit after the dot */
640 while (isdigit(*ptr) || *ptr=='_') {
642 ffrac=(ffrac*10.0)+(*ptr-'0');
645 dnum += (*ptr-'0')*dbase;
646 if (dbase==0L && sc_rationaltag && rational_digits>0 && !ignore) {
647 error(222); /* number of digits exceeds rational number precision */
653 fnum += ffrac*fmult; /* form the number so far */
654 if (*ptr=='e') { /* optional fractional part */
663 if (!isdigit(*ptr)) /* 'e' should be followed by a digit */
666 while (isdigit(*ptr)) {
667 exp=(exp*10)+(*ptr-'0');
671 fmult=pow10(exp*sign);
673 fmult=pow(10,exp*sign);
676 dnum *= (unsigned long)(fmult+0.5);
679 /* decide how to store the number */
680 if (sc_rationaltag==0) {
681 error(70); /* rational number support was not enabled */
683 } else if (rational_digits==0) {
685 #if PAWN_CELL_SIZE==32
686 float value=(float)fnum;
687 *val=*((cell *)&value);
688 #if 0 /* SourceMod - not needed */
689 /* I assume that the C/C++ compiler stores "float" values in IEEE 754
690 * format (as mandated in the ANSI standard). Test this assumption
692 * Note: problems have been reported with GCC 3.2.x, version 3.3.x works.
694 { float test1 = 0.0, test2 = 50.0, test3 = -50.0;
696 /* test 0.0 == all bits 0 */
697 assert(*(uint32_t*)&test1==0x00000000L);
698 /* test sign & magnitude format */
699 assert(((*(uint32_t*)&test2) ^ (*(uint32_t*)&test3)) == (bit << (PAWN_CELL_SIZE-1)));
700 /* test a known value */
701 assert(*(uint32_t*)&test2==0x42480000L);
704 #elif PAWN_CELL_SIZE==64
705 *val=*((cell *)&fnum);
706 #if 0 /* SourceMod - not needed */
707 /* I assume that the C/C++ compiler stores "double" values in IEEE 754
708 * format (as mandated in the ANSI standard).
710 { float test1 = 0.0, test2 = 50.0, test3 = -50.0;
712 /* test 0.0 == all bits 0 */
713 assert(*(uint64_t*)&test1==0x00000000L);
714 /* test sign & magnitude format */
715 assert(((*(uint64_t*)&test2) ^ (*(uint64_t*)&test3)) == (bit << (PAWN_CELL_SIZE-1)));
719 #error Unsupported cell size
726 return (int)(ptr-curptr);
731 * Reads in a number (binary, decimal or hexadecimal). It returns the number
732 * of characters processed or 0 if the symbol couldn't be interpreted as a
733 * number (in this case the argument "val" remains unchanged). This routine
734 * relies on the 'early dropout' implementation of the logical or (||)
737 * Note: the routine doesn't check for a sign (+ or -). The - is checked
738 * for at "hier2()" (in fact, it is viewed as an operator, not as a
739 * sign) and the + is invalid (as in K&R C, and unlike ANSI C).
741 static int number(cell *val,const unsigned char *curptr)
746 if ((i=btoi(&value,curptr))!=0 /* binary? */
747 || (i=htoi(&value,curptr))!=0 /* hexadecimal? */
748 || (i=dtoi(&value,curptr))!=0) /* decimal? */
753 return 0; /* else not a number */
757 static void chrcat(char *str,char chr)
759 str=strchr(str,'\0');
764 static int preproc_expr(cell *val,int *tag)
771 /* Disable staging; it should be disabled already because
772 * expressions may not be cut off half-way between conditional
773 * compilations. Reset the staging index, but keep the code
776 if (stgget(&index,&code_index)) {
777 error(57); /* unfinished expression */
778 stgdel(0,code_index);
781 assert((lptr-pline)<(int)strlen((char*)pline)); /* lptr must point inside the string */
782 #if !defined NO_DEFINE
783 /* preprocess the string */
784 substallpatterns(pline,sLINEMAX);
785 assert((lptr-pline)<(int)strlen((char*)pline)); /* lptr must STILL point inside the string */
787 /* append a special symbol to the string, so the expression
788 * analyzer won't try to read a next line when it encounters
791 assert(strlen((char*)pline)<sLINEMAX);
792 term=strchr((char*)pline,'\0');
794 chrcat((char*)pline,PREPROC_TERM); /* the "DEL" code (see SC.H) */
795 result=constexpr(val,tag,NULL); /* get value (or 0 on error) */
796 *term='\0'; /* erase the token (if still present) */
797 lexclr(FALSE); /* clear any "pushed" tokens */
802 * Returns returns a pointer behind the closing quote or to the other
803 * character that caused the input to be ended.
805 static const unsigned char *getstring(unsigned char *dest,int max,const unsigned char *line)
807 assert(dest!=NULL && line!=NULL);
809 while (*line<=' ' && *line!='\0')
810 line++; /* skip whitespace */
814 while (*line!='"' && *line!='\0') {
821 line++; /* skip closing " */
823 error(37); /* invalid string */
825 error(37); /* invalid string */
843 * Recognizes the compiler directives. The function returns:
844 * CMD_NONE the line must be processed
845 * CMD_TERM a pending expression must be completed before processing further lines
846 * Other value: the line must be skipped, because:
847 * CMD_CONDFALSE false "#if.." code
848 * CMD_EMPTYLINE line is empty
849 * CMD_INCLUDE the line contains a #include directive
850 * CMD_DEFINE the line contains a #subst directive
851 * CMD_IF the line contains a #if/#else/#endif directive
852 * CMD_DIRECTIVE the line contains some other compiler directive
854 * Global variables: iflevel, ifstack (altered)
857 static int command(void)
865 while (*lptr<=' ' && *lptr!='\0')
868 return CMD_EMPTYLINE; /* empty line */
870 return SKIPPING ? CMD_CONDFALSE : CMD_NONE; /* it is not a compiler directive */
871 /* compiler directive found */
872 indent_nowarn=TRUE; /* allow loose indentation" */
873 lexclr(FALSE); /* clear any "pushed" tokens */
874 /* on a pending expression, force to return a silent ';' token and force to
877 if (!sc_needsemicolon && stgget(&index,&code_index)) {
882 ret=SKIPPING ? CMD_CONDFALSE : CMD_DIRECTIVE; /* preset 'ret' to CMD_DIRECTIVE (most common case) */
884 case tpIF: /* conditional compilation */
887 if (iflevel>=sCOMP_STACK)
888 error(122,"Conditional compilation stack"); /* table overflow */
891 break; /* break out of switch */
893 preproc_expr(&val,NULL); /* get value (or 0 on error) */
894 ifstack[iflevel-1]=(char)(val ? PARSEMODE : SKIPMODE);
902 error(26); /* no matching #if */
905 /* check for earlier #else */
906 if ((ifstack[iflevel-1] & HANDLED_ELSE)==HANDLED_ELSE) {
908 error(61); /* #elseif directive may not follow an #else */
910 error(60); /* multiple #else directives between #if ... #endif */
914 /* if there has been a "parse mode" on this level, set "skip mode",
915 * otherwise, clear "skip mode"
917 if ((ifstack[iflevel-1] & PARSEMODE)==PARSEMODE) {
918 /* there has been a parse mode already on this level, so skip the rest */
919 ifstack[iflevel-1] |= (char)SKIPMODE;
920 /* if we were already skipping this section, allow expressions with
921 * undefined symbols; otherwise check the expression to catch errors
924 if (skiplevel==iflevel)
925 preproc_expr(&val,NULL); /* get, but ignore the expression */
927 lptr=(unsigned char*)strchr((char*)lptr,'\0');
930 /* previous conditions were all FALSE */
932 /* if we were already skipping this section, allow expressions with
933 * undefined symbols; otherwise check the expression to catch errors
935 if (skiplevel==iflevel) {
936 preproc_expr(&val,NULL); /* get value (or 0 on error) */
938 lptr=(unsigned char*)strchr((char*)lptr,'\0');
941 ifstack[iflevel-1]=(char)(val ? PARSEMODE : SKIPMODE);
943 /* a simple #else, clear skip mode */
944 ifstack[iflevel-1] &= (char)~SKIPMODE;
954 error(26); /* no matching "#if" */
958 if (iflevel<skiplevel)
963 case tINCLUDE: /* #include directive */
967 doinclude(tok==tpTRYINCLUDE);
971 char pathname[_MAX_PATH];
972 lptr=getstring((unsigned char*)pathname,sizeof pathname,lptr);
973 if (strlen(pathname)>0) {
975 inpfname=duplicatestring(pathname);
977 error(123); /* insufficient memory */
985 if (lex(&val,&str)!=tNUMBER)
986 error(8); /* invalid/non-constant expression */
992 if (!SKIPPING && (sc_debug & sCHKBOUNDS)!=0) {
993 for (str=(char*)lptr; *str<=' ' && *str!='\0'; str++)
994 /* nothing */; /* save start of expression */
995 preproc_expr(&val,NULL); /* get constant expression (or 0 on error) */
997 error(130,str); /* assertion failed */
1003 if (lex(&val,&str)==tSYMBOL) {
1004 if (strcmp(str,"amxlimit")==0) {
1005 preproc_expr(&pc_amxlimit,NULL);
1006 } else if (strcmp(str,"amxram")==0) {
1007 preproc_expr(&pc_amxram,NULL);
1008 } else if (strcmp(str,"codepage")==0) {
1009 char name[sNAMEMAX+1];
1010 while (*lptr<=' ' && *lptr!='\0')
1013 lptr=getstring((unsigned char*)name,sizeof name,lptr);
1016 for (i=0; i<sizeof name && alphanum(*lptr); i++,lptr++)
1021 error(128); /* codepage mapping file not found */
1022 } else if (strcmp(str,"compress")==0) {
1024 preproc_expr(&val,NULL);
1025 sc_compress=(int)val; /* switch code packing on/off */
1026 } else if (strcmp(str,"ctrlchar")==0) {
1027 while (*lptr<=' ' && *lptr!='\0')
1030 sc_ctrlchar=sc_ctrlchar_org;
1032 if (lex(&val,&str)!=tNUMBER)
1033 error(27); /* invalid character constant */
1034 sc_ctrlchar=(char)val;
1036 } else if (strcmp(str,"deprecated")==0) {
1037 while (*lptr<=' ' && *lptr!='\0')
1039 pc_deprecate=(char*)malloc(strlen((char*)lptr)+1);
1040 if (pc_deprecate!=NULL)
1041 strcpy(pc_deprecate,(char*)lptr);
1042 lptr=(unsigned char*)strchr((char*)lptr,'\0'); /* skip to end (ignore "extra characters on line") */
1043 } else if (strcmp(str,"dynamic")==0) {
1044 preproc_expr(&pc_stksize,NULL);
1045 } else if (!strcmp(str,"library")
1046 ||!strcmp(str,"reqclass")
1047 ||!strcmp(str,"loadlib")
1048 ||!strcmp(str,"explib")
1049 ||!strcmp(str,"expclass")
1050 ||!strcmp(str,"defclasslib")) {
1051 char name[sNAMEMAX+1],sname[sNAMEMAX+1];
1052 const char *prefix="";
1055 if (!strcmp(str,"library"))
1057 else if (!strcmp(str,"reqclass"))
1059 else if (!strcmp(str,"loadlib"))
1061 else if (!strcmp(str,"explib"))
1063 else if (!strcmp(str,"expclass"))
1065 else if (!strcmp(str,"defclasslib"))
1067 while (*lptr<=' ' && *lptr!='\0')
1070 lptr=getstring((unsigned char*)name,sizeof name,lptr);
1073 for (i=0; i<sizeof name && (alphanum(*lptr) || *lptr=='-'); i++,lptr++)
1076 if (!strncmp(str,"exp",3) || !strncmp(str,"def",3)) {
1077 while (*lptr && isspace(*lptr))
1079 for (i=1; i<sizeof sname && alphanum(*lptr); i++,lptr++)
1089 if (strlen(name)==0) {
1091 } else if (strcmp(name,"-")==0) {
1092 pc_addlibtable=FALSE;
1094 /* add the name if it does not yet exist in the table */
1095 char newname[sNAMEMAX+1];
1096 if (strlen(name)+strlen(prefix)+strlen(sname)<=sNAMEMAX) {
1097 strcpy(newname,prefix);
1098 strcat(newname,name);
1099 strcat(newname,sname);
1100 if (find_constval(&libname_tab,newname,0)==NULL) {
1101 if (!strcmp(str,"library") || !strcmp(str,"reqclass")) {
1102 curlibrary=append_constval(&libname_tab,newname,1,0);
1104 append_constval(&libname_tab,newname,1,0);
1109 #if 0 /* more unused */
1110 } else if (strcmp(str,"pack")==0) {
1112 preproc_expr(&val,NULL); /* default = packed/unpacked */
1113 sc_packstr=(int)val;
1115 } else if (strcmp(str,"rational")==0) {
1116 char name[sNAMEMAX+1];
1119 /* first gather all information, start with the tag name */
1120 while (*lptr<=' ' && *lptr!='\0')
1122 for (i=0; i<sizeof name && alphanum(*lptr); i++,lptr++)
1125 /* then the precision (for fixed point arithmetic) */
1126 while (*lptr<=' ' && *lptr!='\0')
1129 preproc_expr(&digits,NULL);
1130 if (digits<=0 || digits>9) {
1131 error(68); /* invalid rational number precision */
1137 /* add the tag (make it public) and check the values */
1140 if (sc_rationaltag==0 || (sc_rationaltag==i && rational_digits==(int)digits)) {
1142 rational_digits=(int)digits;
1144 error(69); /* rational number format already set, can only be set once */
1146 } else if (strcmp(str,"semicolon")==0) {
1148 preproc_expr(&val,NULL);
1149 sc_needsemicolon=(int)val;
1150 } else if (strcmp(str,"tabsize")==0) {
1152 preproc_expr(&val,NULL);
1153 sc_tabsize=(int)val;
1154 } else if (strcmp(str,"align")==0) {
1156 } else if (strcmp(str,"unused")==0) {
1157 char name[sNAMEMAX+1];
1162 while (*lptr<=' ' && *lptr!='\0')
1164 for (i=0; i<sizeof name && alphanum(*lptr); i++,lptr++)
1167 /* get the symbol */
1170 sym=findglb(name,sSTATEVAR);
1172 sym->usage |= uREAD;
1173 if (sym->ident==iVARIABLE || sym->ident==iREFERENCE
1174 || sym->ident==iARRAY || sym->ident==iREFARRAY)
1175 sym->usage |= uWRITTEN;
1177 error(17,name); /* undefined symbol */
1179 /* see if a comma follows the name */
1180 while (*lptr<=' ' && *lptr!='\0')
1182 comma= (*lptr==',');
1187 error(207); /* unknown #pragma */
1190 error(207); /* unknown #pragma */
1207 /* write opcode to output file */
1210 while (*lptr<=' ' && *lptr!='\0')
1212 for (i=0; i<40 && (isalpha(*lptr) || *lptr=='.'); i++,lptr++)
1213 name[i]=(char)tolower(*lptr);
1218 code_idx+=opcodes(1);
1219 /* write parameter (if any) */
1220 while (*lptr<=' ' && *lptr!='\0')
1229 code_idx+=opargs(1);
1234 sym=findglb(str,sSTATEVAR);
1235 if (sym==NULL || sym->ident!=iFUNCTN && sym->ident!=iREFFUNC && (sym->usage & uDEFINE)==0) {
1236 error(17,str); /* undefined symbol */
1238 outval(sym->addr,FALSE);
1239 /* mark symbol as "used", unknown whether for read or write */
1240 markusage(sym,uREAD | uWRITTEN);
1241 code_idx+=opargs(1);
1246 extern char *sc_tokens[];/* forward declaration */
1248 sprintf(s2,"%c",(char)tok);
1250 strcpy(s2,sc_tokens[tok-tFIRST]);
1251 error(1,sc_tokens[tSYMBOL-tFIRST],s2);
1261 #if !defined NO_DEFINE
1265 char *pattern,*substitution;
1266 const unsigned char *start,*end;
1267 int count,prefixlen;
1269 /* find the pattern to match */
1270 while (*lptr<=' ' && *lptr!='\0')
1272 start=lptr; /* save starting point of the match pattern */
1274 while (*lptr>' ' && *lptr!='\0') {
1275 litchar(&lptr,0); /* litchar() advances "lptr" and handles escape characters */
1279 /* check pattern to match */
1280 if (!alpha(*start)) {
1281 error(74); /* pattern must start with an alphabetic character */
1284 /* store matched pattern */
1285 pattern=(char*)malloc(count+1);
1287 error(123); /* insufficient memory */
1292 assert(*lptr!='\0');
1293 pattern[count++]=(char)litchar(&lptr,0);
1295 pattern[count]='\0';
1296 /* special case, erase trailing variable, because it could match anything */
1297 if (count>=2 && isdigit(pattern[count-1]) && pattern[count-2]=='%')
1298 pattern[count-2]='\0';
1299 /* find substitution string */
1300 while (*lptr<=' ' && *lptr!='\0')
1302 start=lptr; /* save starting point of the match pattern */
1305 while (*lptr!='\0') {
1306 /* keep position of the start of trailing whitespace */
1318 /* store matched substitution */
1319 substitution=(char*)malloc(count+1); /* +1 for '\0' */
1320 if (substitution==NULL)
1321 error(123); /* insufficient memory */
1326 assert(*lptr!='\0');
1327 substitution[count++]=*lptr++;
1329 substitution[count]='\0';
1330 /* check whether the definition already exists */
1331 for (prefixlen=0,start=(unsigned char*)pattern; alphanum(*start); prefixlen++,start++)
1333 assert(prefixlen>0);
1334 if ((def=find_subst(pattern,prefixlen))!=NULL) {
1335 if (strcmp(def->first,pattern)!=0 || strcmp(def->second,substitution)!=0)
1336 error(201,pattern); /* redefinition of macro (non-identical) */
1337 delete_subst(pattern,prefixlen);
1339 /* add the pattern/substitution pair to the list */
1340 assert(strlen(pattern)>0);
1341 insert_subst(pattern,substitution,prefixlen);
1349 if (lex(&val,&str)==tSYMBOL) {
1350 ret=delete_subst(str,strlen(str));
1352 /* also undefine normal constants */
1353 symbol *sym=findconst(str,NULL);
1354 if (sym!=NULL && (sym->usage & (uENUMROOT | uENUMFIELD))==0) {
1355 delete_symbol(&glbtab,sym);
1360 error(17,str); /* undefined symbol */
1362 error(20,str); /* invalid symbol name */
1369 while (*lptr<=' ' && *lptr!='\0')
1372 error(131,lptr); /* user error */
1375 error(31); /* unknown compiler directive */
1376 ret=SKIPPING ? CMD_CONDFALSE : CMD_NONE; /* process as normal line */
1381 #if !defined NO_DEFINE
1382 static int is_startstring(const unsigned char *string)
1384 if (*string=='\"' || *string=='\'')
1385 return TRUE; /* "..." */
1389 if (*string=='\"' || *string=='\'')
1390 return TRUE; /* !"..." */
1391 if (*string==sc_ctrlchar) {
1393 if (*string=='\"' || *string=='\'')
1394 return TRUE; /* !\"..." */
1396 } else if (*string==sc_ctrlchar) {
1398 if (*string=='\"' || *string=='\'')
1399 return TRUE; /* \"..." */
1402 if (*string=='\"' || *string=='\'')
1403 return TRUE; /* \!"..." */
1410 static const unsigned char *skipstring(const unsigned char *string)
1415 while (*string=='!' || *string==sc_ctrlchar) {
1416 if (*string==sc_ctrlchar)
1422 assert(endquote=='"' || endquote=='\'');
1423 string++; /* skip open quote */
1424 while (*string!=endquote && *string!='\0')
1425 litchar(&string,flags);
1429 static const unsigned char *skippgroup(const unsigned char *string)
1450 close='\0'; /* only to avoid a compiler warning */
1454 while (*string!=close || nest>0) {
1457 else if (*string==close)
1459 else if (is_startstring(string))
1460 string=skipstring(string);
1468 static char *strdel(char *str,size_t len)
1470 size_t length=strlen(str);
1473 memmove(str, str+len, length-len+1); /* include EOS byte */
1477 static char *strins(char *dest,char *src,size_t srclen)
1479 size_t destlen=strlen(dest);
1480 assert(srclen<=strlen(src));
1481 memmove(dest+srclen, dest, destlen+1);/* include EOS byte */
1482 memcpy(dest, src, srclen);
1486 static int substpattern(unsigned char *line,size_t buffersize,char *pattern,char *substitution)
1489 const unsigned char *p,*s,*e;
1490 unsigned char *args[10];
1491 int match,arg,len,argsnum=0;
1493 memset(args,0,sizeof args);
1495 /* check the length of the prefix */
1496 for (prefixlen=0,s=(unsigned char*)pattern; alphanum(*s); prefixlen++,s++)
1498 assert(prefixlen>0);
1499 assert(strncmp((char*)line,pattern,prefixlen)==0);
1501 /* pattern prefix matches; match the rest of the pattern, gather
1505 p=(unsigned char*)pattern+prefixlen;
1506 match=TRUE; /* so far, pattern matches */
1507 while (match && *s!='\0' && *p!='\0') {
1512 assert(arg>=0 && arg<=9);
1513 p++; /* skip parameter id */
1515 /* match the source string up to the character after the digit
1516 * (skipping strings in the process
1519 while (*e!=*p && *e!='\0' && *e!='\n') {
1520 if (is_startstring(e)) /* skip strings */
1522 else if (strchr("({[",*e)!=NULL) /* skip parenthized groups */
1525 e++; /* skip non-alphapetic character (or closing quote of
1526 * a string, or the closing paranthese of a group) */
1528 /* store the parameter (overrule any earlier) */
1529 if (args[arg]!=NULL)
1534 args[arg]=(unsigned char*)malloc(len+1);
1535 if (args[arg]==NULL)
1536 error(123); /* insufficient memory */
1537 strlcpy((char*)args[arg],(char*)s,len+1);
1538 /* character behind the pattern was matched too */
1541 } else if (*e=='\n' && *p==';' && *(p+1)=='\0' && !sc_needsemicolon) {
1542 s=e; /* allow a trailing ; in the pattern match to end of line */
1544 assert(*e=='\0' || *e=='\n');
1552 } else if (*p==';' && *(p+1)=='\0' && !sc_needsemicolon) {
1553 /* source may be ';' or end of the line */
1554 while (*s<=' ' && *s!='\0')
1555 s++; /* skip white space */
1556 if (*s!=';' && *s!='\0')
1558 p++; /* skip the semicolon in the pattern */
1561 /* skip whitespace between two non-alphanumeric characters, except
1562 * for two identical symbols
1564 assert((char*)p>pattern);
1565 if (!alphanum(*p) && *(p-1)!=*p)
1566 while (*s<=' ' && *s!='\0')
1567 s++; /* skip white space */
1568 ch=litchar(&p,0); /* this increments "p" */
1572 s++; /* this character matches */
1576 if (match && *p=='\0') {
1577 /* if the last character to match is an alphanumeric character, the
1578 * current character in the source may not be alphanumeric
1580 assert(p>(unsigned char*)pattern);
1581 if (alphanum(*(p-1)) && alphanum(*s))
1586 /* calculate the length of the substituted string */
1587 for (e=(unsigned char*)substitution,len=0; *e!='\0'; e++) {
1588 if (*e=='%' && isdigit(*(e+1)) && argsnum) {
1590 assert(arg>=0 && arg<=9);
1591 if (args[arg]!=NULL) {
1592 len+=strlen((char*)args[arg]);
1601 /* check length of the string after substitution */
1602 if (strlen((char*)line) + len - (int)(s-line) > buffersize) {
1603 error(75); /* line too long */
1605 /* substitute pattern */
1606 strdel((char*)line,(int)(s-line));
1607 for (e=(unsigned char*)substitution,s=line; *e!='\0'; e++) {
1608 if (*e=='%' && isdigit(*(e+1))) {
1610 assert(arg>=0 && arg<=9);
1611 if (args[arg]!=NULL) {
1612 strins((char*)s,(char*)args[arg],strlen((char*)args[arg]));
1613 s+=strlen((char*)args[arg]);
1615 error(236); /* parameter does not exist, incorrect #define pattern */
1616 strins((char*)s,(char*)e,2);
1619 e++; /* skip %, digit is skipped later */
1620 } else if (*e == '"') {
1622 if (is_startstring(e)) {
1624 strins((char*)s,(char *)p,(e-p+1));
1627 strins((char*)s,(char*)e,1);
1631 strins((char*)s,(char*)e,1);
1638 for (arg=0; arg<10; arg++)
1639 if (args[arg]!=NULL)
1645 static void substallpatterns(unsigned char *line,int buffersize)
1647 unsigned char *start, *end;
1652 while (*start!='\0') {
1653 /* find the start of a prefix (skip all non-alphabetic characters),
1656 while (!alpha(*start) && *start!='\0') {
1658 if (is_startstring(start)) {
1659 start=(unsigned char *)skipstring(start);
1661 break; /* abort loop on error */
1663 start++; /* skip non-alphapetic character (or closing quote of a string) */
1666 break; /* abort loop on error */
1667 /* if matching the operator "defined", skip it plus the symbol behind it */
1668 if (strncmp((char*)start,"defined",7)==0 && !isalpha((char)*(start+7))) {
1669 start+=7; /* skip "defined" */
1670 /* skip white space & parantheses */
1671 while (*start<=' ' && *start!='\0' || *start=='(')
1673 /* skip the symbol behind it */
1674 while (alphanum(*start))
1676 /* drop back into the main loop */
1679 /* get the prefix (length), look for a matching definition */
1682 while (alphanum(*end)) {
1686 assert(prefixlen>0);
1687 subst=find_subst((char*)start,prefixlen);
1689 /* properly match the pattern and substitute */
1690 if (!substpattern(start,buffersize-(int)(start-line),subst->first,subst->second))
1691 start=end; /* match failed, skip this prefix */
1692 /* match succeeded: do not update "start", because the substitution text
1693 * may be matched by other macros
1696 start=end; /* no macro with this prefix, skip this prefix */
1704 * Reads a line by readline() into "pline" and performs basic preprocessing:
1705 * deleting comments, skipping lines with false "#if.." code and recognizing
1706 * other compiler directives. There is an indirect recursion: lex() calls
1707 * preprocess() if a new line must be read, preprocess() calls command(),
1708 * which at his turn calls lex() to identify the token.
1710 * Global references: lptr (altered)
1712 * freading (referred to only)
1714 SC_FUNC void preprocess(void)
1722 stripcom(pline); /* ??? no need for this when reading back from list file (in the second pass) */
1723 lptr=pline; /* set "line pointer" to start of the parsing buffer */
1724 iscommand=command();
1725 if (iscommand!=CMD_NONE)
1726 errorset(sRESET,0); /* reset error flag ("panic mode") on empty line or directive */
1727 #if !defined NO_DEFINE
1728 if (iscommand==CMD_NONE) {
1729 assert(lptr!=term_expr);
1730 substallpatterns(pline,sLINEMAX);
1731 lptr=pline; /* reset "line pointer" to start of the parsing buffer */
1734 if (sc_status==statFIRST && sc_listing && freading
1735 && (iscommand==CMD_NONE || iscommand==CMD_EMPTYLINE || iscommand==CMD_DIRECTIVE))
1738 if (fline!=listline) {
1740 setlinedirect(fline);
1742 if (iscommand==CMD_EMPTYLINE)
1743 pc_writeasm(outf,"\n");
1745 pc_writeasm(outf,(char*)pline);
1747 } while (iscommand!=CMD_NONE && iscommand!=CMD_TERM && freading); /* enddo */
1750 static const unsigned char *unpackedstring(const unsigned char *lptr,int flags)
1752 while (*lptr!='\"' && *lptr!='\0') {
1753 if (*lptr=='\a') { /* ignore '\a' (which was inserted at a line concatenation) */
1757 litadd(litchar(&lptr,flags | UTF8MODE)); /* litchar() alters "lptr" */
1759 litadd(0); /* terminate string */
1763 static const unsigned char *packedstring(const unsigned char *lptr,int flags)
1768 i=0; /* start at least significant byte */
1771 while (*lptr!='\"' && *lptr!='\0') {
1772 if (*lptr=='\a') { /* ignore '\a' (which was inserted at a line concatenation) */
1776 c=litchar(&lptr,flags); /* litchar() alters "lptr" */
1777 if (c>=(ucell)(1 << sCHARBITS))
1778 error(43); /* character constant exceeds range */
1781 if (i==sizeof(ucell)-(sCHARBITS/8)) {
1789 /* save last code; make sure there is at least one terminating zero character */
1791 litadd(val); /* at least one zero character in "val" */
1793 litadd(0); /* add full cell of zeros */
1797 /* lex(lexvalue,lexsym) Lexical Analysis
1799 * lex() first deletes leading white space, then checks for multi-character
1800 * operators, keywords (including most compiler directives), numbers,
1801 * labels, symbols and literals (literal characters are converted to a number
1802 * and are returned as such). If every check fails, the line must contain
1803 * a single-character operator. So, lex() returns this character. In the other
1804 * case (something did match), lex() returns the number of the token. All
1805 * these tokens have been assigned numbers above 255.
1807 * Some tokens have "attributes":
1808 * tNUMBER the value of the number is return in "lexvalue".
1809 * tRATIONAL the value is in IEEE 754 encoding or in fixed point
1810 * encoding in "lexvalue".
1811 * tSYMBOL the first sNAMEMAX characters of the symbol are
1812 * stored in a buffer, a pointer to this buffer is
1813 * returned in "lexsym".
1814 * tLABEL the first sNAMEMAX characters of the label are
1815 * stored in a buffer, a pointer to this buffer is
1816 * returned in "lexsym".
1817 * tSTRING the string is stored in the literal pool, the index
1818 * in the literal pool to this string is stored in
1821 * lex() stores all information (the token found and possibly its attribute)
1822 * in global variables. This allows a token to be examined twice. If "_pushed"
1823 * is true, this information is returned.
1825 * Global references: lptr (altered)
1826 * fline (referred to only)
1827 * litidx (referred to only)
1828 * _lextok, _lexval, _lexstr
1834 static cell _lexval;
1835 static char _lexstr[sLINEMAX+1];
1836 static int _lexnewline;
1838 SC_FUNC void lexinit(void)
1840 stkidx=0; /* index for pushstk() and popstk() */
1841 iflevel=0; /* preprocessor: nesting of "#if" is currently 0 */
1842 skiplevel=0; /* preprocessor: not currently skipping */
1843 icomment=0; /* currently not in a multiline comment */
1844 _pushed=FALSE; /* no token pushed back into lex */
1848 char *sc_tokens[] = {
1849 "*=", "/=", "%=", "+=", "-=", "<<=", ">>>=", ">>=", "&=", "^=", "|=",
1850 "||", "&&", "==", "!=", "<=", ">=", "<<", ">>>", ">>", "++", "--",
1852 "assert", "*begin", "break", "case", "cellsof", "chars", "const", "continue", "default",
1853 "defined", "do", "else", "*end", "enum", "exit", "for", "forward", "funcenum", "functag", "goto",
1854 "if", "native", "new", "decl", "operator", "public", "return", "sizeof",
1855 "sleep", "state", "static", "stock", "struct", "switch", "tagof", "*then", "while",
1856 "#assert", "#define", "#else", "#elseif", "#emit", "#endif", "#endinput",
1857 "#endscript", "#error", "#file", "#if", "#include", "#line", "#pragma",
1858 "#tryinclude", "#undef",
1859 ";", ";", "-integer value-", "-rational value-", "-identifier-",
1860 "-label-", "-string-"
1863 SC_FUNC int lex(cell *lexvalue,char **lexsym)
1865 int i,toolong,newline,stringflags;
1867 const unsigned char *starttoken;
1870 _pushed=FALSE; /* reset "_pushed" flag */
1876 _lextok=0; /* preset all values */
1885 newline= (lptr==pline); /* does lptr point to start of line buffer */
1886 while (*lptr<=' ') { /* delete leading white space */
1888 preprocess(); /* preprocess resets "lptr" */
1891 if (lptr==term_expr) /* special sequence to terminate a pending expression */
1892 return (_lextok=tENDEXPR);
1893 _lexnewline=TRUE; /* set this after preprocess(), because
1894 * preprocess() calls lex() recursively */
1902 for (i=0; i<(int)(lptr-pline); i++)
1903 if (pline[i]=='\t' && sc_tabsize>0)
1904 stmtindent += (int)(sc_tabsize - (stmtindent+sc_tabsize) % sc_tabsize);
1911 while (i<=tMIDDLE) { /* match multi-character operators */
1912 if (*lptr==**tokptr && match(*tokptr,FALSE)) {
1914 if (pc_docexpr) /* optionally concatenate to documentation string */
1915 insert_autolist(*tokptr);
1921 while (i<=tLAST) { /* match reserved words and compiler directives */
1922 if (*lptr==**tokptr && match(*tokptr,TRUE)) {
1924 errorset(sRESET,0); /* reset error flag (clear the "panic mode")*/
1925 if (pc_docexpr) /* optionally concatenate to documentation string */
1926 insert_autolist(*tokptr);
1933 starttoken=lptr; /* save start pointer (for concatenating to documentation string) */
1934 if ((i=number(&_lexval,lptr))!=0) { /* number */
1938 } else if ((i=ftoi(&_lexval,lptr))!=0) {
1942 } else if (alpha(*lptr)) { /* symbol or label */
1943 /* Note: only sNAMEMAX characters are significant. The compiler
1944 * generates a warning if a symbol exceeds this length.
1949 while (alphanum(*lptr)){
1959 error(200,_lexstr,sNAMEMAX); /* symbol too long, truncated to sNAMEMAX chars */
1960 if (_lexstr[0]==PUBLIC_CHAR && _lexstr[1]=='\0') {
1961 _lextok=PUBLIC_CHAR; /* '@' all alone is not a symbol, it is an operator */
1962 } else if (_lexstr[0]=='_' && _lexstr[1]=='\0') {
1963 _lextok='_'; /* '_' by itself is not a symbol, it is a placeholder */
1965 if (*lptr==':' && *(lptr+1)!=':' && _lextok!=PUBLIC_CHAR) {
1967 _lextok=tLABEL; /* it wasn't a normal symbol, it was a label/tagname */
1968 lptr+=1; /* skip colon */
1969 } else if (find_constval(&tagname_tab,_lexstr,0)!=NULL) {
1970 /* this looks like a tag override (because a tag with this name
1971 * exists), but tags are not allowed right now, so it is probably an
1977 } else if (*lptr=='\"' || *lptr==sc_ctrlchar && *(lptr+1)=='\"')
1978 { /* unpacked string literal */
1980 stringflags= (*lptr==sc_ctrlchar) ? RAWMODE : 0;
1981 *lexvalue=_lexval=litidx;
1982 lptr+=1; /* skip double quote */
1983 if ((stringflags & RAWMODE)!=0)
1984 lptr+=1; /* skip "escape" character too */
1985 /* Note that this should always be packedstring() for SourcePawn */
1986 lptr=sc_packstr ? packedstring(lptr,stringflags) : unpackedstring(lptr,stringflags);
1988 lptr+=1; /* skip final quote */
1990 error(37); /* invalid (non-terminated) string */
1991 } else if (*lptr=='!' && *(lptr+1)=='\"'
1992 || *lptr=='!' && *(lptr+1)==sc_ctrlchar && *(lptr+2)=='\"'
1993 || *lptr==sc_ctrlchar && *(lptr+1)=='!' && *(lptr+2)=='\"')
1994 { /* packed string literal */
1996 stringflags= (*lptr==sc_ctrlchar || *(lptr+1)==sc_ctrlchar) ? RAWMODE : 0;
1997 *lexvalue=_lexval=litidx;
1998 lptr+=2; /* skip exclamation point and double quote */
1999 if ((stringflags & RAWMODE)!=0)
2000 lptr+=1; /* skip "escape" character too */
2001 lptr=sc_packstr ? unpackedstring(lptr,stringflags) : packedstring(lptr,stringflags);
2003 lptr+=1; /* skip final quote */
2005 error(37); /* invalid (non-terminated) string */
2006 } else if (*lptr=='\'') { /* character literal */
2007 lptr+=1; /* skip quote */
2009 *lexvalue=_lexval=litchar(&lptr,UTF8MODE);
2011 lptr+=1; /* skip final quote */
2013 error(27); /* invalid character constant (must be one character) */
2014 } else if (*lptr==';') { /* semicolumn resets "error" flag */
2017 errorset(sRESET,0); /* reset error flag (clear the "panic mode")*/
2019 _lextok=*lptr; /* if every match fails, return the character */
2020 lptr+=1; /* increase the "lptr" pointer */
2023 if (pc_docexpr) { /* optionally concatenate to documentation string */
2024 char *docstr=(char*)malloc(((int)(lptr-starttoken)+1)*sizeof(char));
2026 strlcpy(docstr,(char*)starttoken,(int)(lptr-starttoken)+1);
2027 insert_autolist(docstr);
2036 * Pushes a token back, so the next call to lex() will return the token
2037 * last examined, instead of a new token.
2039 * Only one token can be pushed back.
2041 * In fact, lex() already stores the information it finds into global
2042 * variables, so all that is to be done is set a flag that informs lex()
2043 * to read and return the information from these variables, rather than
2044 * to read in a new token from the input file.
2046 SC_FUNC void lexpush(void)
2048 assert(_pushed==FALSE);
2054 * Sets the variable "_pushed" to 0 to make sure lex() will read in a new
2055 * symbol (a not continue with some old one). This is required upon return
2056 * from Assembler mode, and in a few cases after detecting an syntax error.
2058 SC_FUNC void lexclr(int clreol)
2062 lptr=(unsigned char*)strchr((char*)pline,'\0');
2069 * This routine is useful if only a simple check is needed. If the token
2070 * differs from the one expected, it is pushed back.
2071 * This function returns 1 for "token found" and 2 for "implied statement
2072 * termination token" found --the statement termination is an end of line in
2073 * an expression where there is no pending operation. Such an implied token
2074 * (i.e. not present in the source code) should not be pushed back, which is
2075 * why it is sometimes important to distinguish the two.
2077 SC_FUNC int matchtoken(int token)
2084 if (tok==token || token==tTERM && (tok==';' || tok==tENDEXPR)) {
2086 } else if (!sc_needsemicolon && token==tTERM && (_lexnewline || !freading)) {
2087 /* Push "tok" back, because it is the token following the implicit statement
2088 * termination (newline) token.
2100 * Returns additional information of a token after using "matchtoken()"
2101 * or needtoken(). It does no harm using this routine after a call to
2102 * "lex()", but lex() already returns the same information.
2104 * The token itself is the return value. Normally, this one is already known.
2106 SC_FUNC int tokeninfo(cell *val,char **str)
2108 /* if the token was pushed back, tokeninfo() returns the token and
2109 * parameters of the *next* token, not of the *current* token.
2119 * This routine checks for a required token and gives an error message if
2120 * it isn't there (and returns 0/FALSE in that case). Like function matchtoken(),
2121 * this function returns 1 for "token found" and 2 for "statement termination
2122 * token" found; see function matchtoken() for details.
2124 * Global references: _lextok;
2126 SC_FUNC int needtoken(int token)
2131 if ((t=matchtoken(token))!=0) {
2134 /* token already pushed back */
2137 sprintf(s1,"%c",(char)token); /* single character token */
2139 strcpy(s1,sc_tokens[token-tFIRST]); /* multi-character symbol */
2141 strcpy(s2,"-end of file-");
2142 else if (_lextok<256)
2143 sprintf(s2,"%c",(char)_lextok);
2145 strcpy(s2,sc_tokens[_lextok-tFIRST]);
2146 error(1,s1,s2); /* expected ..., but found ... */
2153 * Compares a series of characters from the input file with the characters
2154 * in "st" (that contains a token). If the token on the input file matches
2155 * "st", the input file pointer "lptr" is adjusted to point to the next
2156 * token, otherwise "lptr" remains unaltered.
2158 * If the parameter "end: is true, match() requires that the first character
2159 * behind the recognized token is non-alphanumeric.
2161 * Global references: lptr (altered)
2163 static int match(char *st,int end)
2166 const unsigned char *ptr;
2171 if ((unsigned char)st[k]!=*ptr)
2176 if (end) { /* symbol must terminate with non-alphanumeric char */
2180 lptr=ptr; /* match found, skip symbol */
2184 static void chk_grow_litq(void)
2186 if (litidx>=litmax) {
2189 litmax+=sDEF_LITMAX;
2190 p=(cell *)realloc(litq,litmax*sizeof(cell));
2192 error(122,"literal table"); /* literal table overflow (fatal error) */
2199 * Adds a value at the end of the literal queue. The literal queue is used
2200 * for literal strings used in functions and for initializing array variables.
2202 * Global references: litidx (altered)
2205 SC_FUNC void litadd(cell value)
2208 assert(litidx<litmax);
2209 litq[litidx++]=value;
2214 * Inserts a value into the literal queue. This is sometimes necessary for
2215 * initializing multi-dimensional arrays.
2217 * Global references: litidx (altered)
2220 SC_FUNC void litinsert(cell value,int pos)
2223 assert(litidx<litmax);
2224 assert(pos>=0 && pos<=litidx);
2225 memmove(litq+(pos+1),litq+pos,(litidx-pos)*sizeof(cell));
2232 * Return current literal character and increase the pointer to point
2233 * just behind this literal character.
2235 * Note: standard "escape sequences" are suported, but the backslash may be
2236 * replaced by another character; the syntax '\ddd' is supported,
2237 * but ddd must be decimal!
2239 static cell litchar(const unsigned char **lptr,int flags)
2242 const unsigned char *cptr;
2245 if ((flags & RAWMODE)!=0 || *cptr!=sc_ctrlchar) { /* no escape character */
2246 #if !defined NO_UTF8
2247 if (sc_is_utf8 && (flags & UTF8MODE)!=0) {
2248 c=get_utf8_char(cptr,&cptr);
2249 assert(c>=0); /* file was already scanned for conformance to UTF-8 */
2252 #if !defined NO_CODEPAGE
2253 c=cp_translate(cptr,&cptr);
2258 #if !defined NO_UTF8
2263 if (*cptr==sc_ctrlchar) {
2264 c=*cptr; /* \\ == \ (the escape character itself) */
2268 case 'a': /* \a == audible alarm */
2272 case 'b': /* \b == backspace */
2276 case 'e': /* \e == escape */
2280 case 'f': /* \f == form feed */
2284 case 'n': /* \n == NewLine character */
2288 case 'r': /* \r == carriage return */
2292 case 't': /* \t == horizontal TAB */
2296 case 'v': /* \v == vertical TAB */
2305 while (ishex(*cptr) && digits < 2) {
2307 c=(c<<4)+(*cptr-'0');
2309 c=(c<<4)+(tolower(*cptr)-'a'+10);
2314 cptr++; /* swallow a trailing ';' */
2317 case '\'': /* \' == ' (single quote) */
2318 case '"': /* \" == " (single quote) */
2319 case '%': /* \% == % (percent) */
2324 if (isdigit(*cptr)) { /* \ddd */
2326 while (*cptr>='0' && *cptr<='9') /* decimal! */
2327 c=c*10 + *cptr++ - '0';
2329 cptr++; /* swallow a trailing ';' */
2331 error(27); /* invalid character constant */
2343 * Test if character "c" is alphabetic ("a".."z"), an underscore ("_")
2344 * or an "at" sign ("@"). The "@" is an extension to standard C.
2346 static int alpha(char c)
2348 return (isalpha(c) || c=='_' || c==PUBLIC_CHAR);
2353 * Test if character "c" is alphanumeric ("a".."z", "0".."9", "_" or "@")
2355 SC_FUNC int alphanum(char c)
2357 return (alpha(c) || isdigit(c));
2362 * Test if character "c" is a hexadecimal digit ("0".."9" or "a".."f").
2364 SC_FUNC int ishex(char c)
2366 return (c>='0' && c<='9') || (c>='a' && c<='f') || (c>='A' && c<='F');
2369 /* The local variable table must be searched backwards, so that the deepest
2370 * nesting of local variables is searched first. The simplest way to do
2371 * this is to insert all new items at the head of the list.
2372 * In the global list, the symbols are kept in sorted order, so that the
2373 * public functions are written in sorted order.
2375 static symbol *add_symbol(symbol *root,symbol *entry,int sort)
2378 int global = root==&glbtab;
2381 while (root->next!=NULL && strcmp(entry->name,root->next->name)>0)
2384 if ((newsym=(symbol *)malloc(sizeof(symbol)))==NULL) {
2388 memcpy(newsym,entry,sizeof(symbol));
2389 newsym->next=root->next;
2392 AddToHashTable(sp_Globals, newsym);
2396 static void free_symbol(symbol *sym)
2400 /* free all sub-symbol allocated memory blocks, depending on the
2401 * kind of the symbol
2404 if (sym->ident==iFUNCTN) {
2405 /* run through the argument list; "default array" arguments
2406 * must be freed explicitly; the tag list must also be freed */
2407 assert(sym->dim.arglist!=NULL);
2408 for (arg=sym->dim.arglist; arg->ident!=0; arg++) {
2409 if (arg->ident==iREFARRAY && arg->hasdefault)
2410 free(arg->defvalue.array.data);
2411 else if (arg->ident==iVARIABLE
2412 && ((arg->hasdefault & uSIZEOF)!=0 || (arg->hasdefault & uTAGOF)!=0))
2413 free(arg->defvalue.size.symname);
2414 assert(arg->tags!=NULL);
2417 free(sym->dim.arglist);
2418 if (sym->states!=NULL) {
2419 delete_consttable(sym->states);
2422 } else if (sym->ident==iVARIABLE || sym->ident==iARRAY) {
2423 if (sym->states!=NULL) {
2424 delete_consttable(sym->states);
2427 } else if (sym->ident==iCONSTEXPR && (sym->usage & uENUMROOT)==uENUMROOT) {
2428 /* free the constant list of an enum root */
2429 assert(sym->dim.enumlist!=NULL);
2430 delete_consttable(sym->dim.enumlist);
2431 free(sym->dim.enumlist);
2433 assert(sym->refer!=NULL);
2435 if (sym->documentation!=NULL)
2436 free(sym->documentation);
2440 SC_FUNC void delete_symbol(symbol *root,symbol *sym)
2442 symbol *origRoot=root;
2443 /* find the symbol and its predecessor
2444 * (this function assumes that you will never delete a symbol that is not
2445 * in the table pointed at by "root")
2448 while (root->next!=sym) {
2453 if (origRoot==&glbtab)
2454 RemoveFromHashTable(sp_Globals, sym);
2456 /* unlink it, then free it */
2457 root->next=sym->next;
2461 SC_FUNC void delete_symbols(symbol *root,int level,int delete_labels,int delete_functions)
2463 symbol *origRoot=root;
2464 symbol *sym,*parent_sym;
2465 constvalue *stateptr;
2468 /* erase only the symbols with a deeper nesting level than the
2469 * specified nesting level */
2470 while (root->next!=NULL) {
2472 if (sym->compound<level)
2474 switch (sym->ident) {
2476 mustdelete=delete_labels;
2480 /* do not delete global variables if functions are preserved */
2481 mustdelete=delete_functions;
2484 /* always delete references (only exist as function parameters) */
2488 /* a global iREFARRAY symbol is the return value of a function: delete
2489 * this only if "globals" must be deleted; other iREFARRAY instances
2490 * (locals) are also deleted
2492 mustdelete=delete_functions;
2493 for (parent_sym=sym->parent; parent_sym!=NULL && parent_sym->ident!=iFUNCTN; parent_sym=parent_sym->parent)
2494 assert(parent_sym->ident==iREFARRAY);
2495 assert(parent_sym==NULL || (parent_sym->ident==iFUNCTN && parent_sym->parent==NULL));
2496 if (parent_sym==NULL || parent_sym->ident!=iFUNCTN)
2500 /* delete constants, except predefined constants */
2501 mustdelete=delete_functions || (sym->usage & uPREDEF)==0;
2504 /* optionally preserve globals (variables & functions), but
2505 * NOT native functions
2507 mustdelete=delete_functions || (sym->usage & uNATIVE)!=0;
2508 assert(sym->parent==NULL);
2519 if (origRoot == &glbtab)
2520 RemoveFromHashTable(sp_Globals, sym);
2521 root->next=sym->next;
2524 /* if the function was prototyped, but not implemented in this source,
2525 * mark it as such, so that its use can be flagged
2527 if (sym->ident==iFUNCTN && (sym->usage & uDEFINE)==0)
2528 sym->usage |= uMISSING;
2529 if (sym->ident==iFUNCTN || sym->ident==iVARIABLE || sym->ident==iARRAY)
2530 sym->usage &= ~uDEFINE; /* clear "defined" flag */
2531 /* set all states as "undefined" too */
2532 if (sym->states!=NULL)
2533 for (stateptr=sym->states->next; stateptr!=NULL; stateptr=stateptr->next)
2535 /* for user defined operators, also remove the "prototyped" flag, as
2536 * user-defined operators *must* be declared before use
2538 if (sym->ident==iFUNCTN && !alpha(*sym->name))
2539 sym->usage &= ~uPROTOTYPED;
2540 root=sym; /* skip the symbol */
2545 static symbol *find_symbol(const symbol *root,const char *name,int fnumber,int automaton,int *cmptag)
2547 symbol *firstmatch=NULL;
2548 symbol *sym=root->next;
2550 unsigned long hash=NameHash(name);
2552 if (hash==sym->hash && strcmp(name,sym->name)==0 /* check name */
2553 && (sym->parent==NULL || sym->ident==iCONSTEXPR) /* sub-types (hierarchical types) are skipped, except for enum fields */
2554 && (sym->fnumber<0 || sym->fnumber==fnumber)) /* check file number for scope */
2556 assert(sym->states==NULL || sym->states->next!=NULL); /* first element of the state list is the "root" */
2557 if (sym->ident==iFUNCTN
2558 || automaton<0 && sym->states==NULL
2559 || automaton>=0 && sym->states!=NULL && state_getfsa(sym->states->next->index)==automaton)
2562 return sym; /* return first match */
2563 /* return closest match or first match; count number of matches */
2564 if (firstmatch==NULL)
2566 assert(cmptag!=NULL);
2569 if (*cmptag==sym->tag) {
2570 *cmptag=1; /* good match found, set number of matches to 1 */
2577 if (cmptag!=NULL && firstmatch!=NULL)
2582 static symbol *find_symbol_child(const symbol *root,const symbol *sym)
2584 symbol *ptr=root->next;
2586 if (ptr->parent==sym)
2593 /* Adds "bywhom" to the list of referrers of "entry". Typically,
2594 * bywhom will be the function that uses a variable or that calls
2597 SC_FUNC int refer_symbol(symbol *entry,symbol *bywhom)
2601 assert(bywhom!=NULL); /* it makes no sense to add a "void" referrer */
2602 assert(entry!=NULL);
2603 assert(entry->refer!=NULL);
2605 /* see if it is already there */
2606 for (count=0; count<entry->numrefers && entry->refer[count]!=bywhom; count++)
2608 if (count<entry->numrefers) {
2609 assert(entry->refer[count]==bywhom);
2613 /* see if there is an empty spot in the referrer list */
2614 for (count=0; count<entry->numrefers && entry->refer[count]!=NULL; count++)
2616 assert(count <= entry->numrefers);
2617 if (count==entry->numrefers) {
2619 int newsize=2*entry->numrefers;
2621 /* grow the referrer list */
2622 refer=(symbol**)realloc(entry->refer,newsize*sizeof(symbol*));
2624 return FALSE; /* insufficient memory */
2625 /* initialize the new entries */
2627 for (count=entry->numrefers; count<newsize; count++)
2628 entry->refer[count]=NULL;
2629 count=entry->numrefers; /* first empty spot */
2630 entry->numrefers=newsize;
2633 /* add the referrer */
2634 assert(entry->refer[count]==NULL);
2635 entry->refer[count]=bywhom;
2639 SC_FUNC void markusage(symbol *sym,int usage)
2642 sym->usage |= (char)usage;
2643 if ((usage & uWRITTEN)!=0)
2645 /* check if (global) reference must be added to the symbol */
2646 if ((usage & (uREAD | uWRITTEN))!=0) {
2647 /* only do this for global symbols */
2648 if (sym->vclass==sGLOBAL) {
2649 /* "curfunc" should always be valid, since statements may not occurs
2650 * outside functions; in the case of syntax errors, however, the
2651 * compiler may arrive through this function
2654 refer_symbol(sym,curfunc);
2662 * Returns a pointer to the global symbol (if found) or NULL (if not found)
2664 SC_FUNC symbol *findglb(const char *name,int filter)
2666 /* find a symbol with a matching automaton first */
2669 if (filter>sGLOBAL && sc_curstates>0) {
2670 /* find a symbol whose state list matches the current fsa */
2671 sym=find_symbol(&glbtab,name,fcurrent,state_getfsa(sc_curstates),NULL);
2672 if (sym!=NULL && sym->ident!=iFUNCTN) {
2673 /* if sym!=NULL, we found a variable in the automaton; now we should
2674 * also verify whether there is an intersection between the symbol's
2675 * state list and the current state list
2677 assert(sym->states!=NULL && sym->states->next!=NULL);
2678 if (!state_conflict_id(sc_curstates,sym->states->next->index))
2683 /* if no symbol with a matching automaton exists, find a variable/function
2684 * that has no state(s) attached to it
2687 sym=FindInHashTable(sp_Globals,name,fcurrent);
2693 * Returns a pointer to the local symbol (if found) or NULL (if not found).
2694 * See add_symbol() how the deepest nesting level is searched first.
2696 SC_FUNC symbol *findloc(const char *name)
2698 return find_symbol(&loctab,name,-1,-1,NULL);
2701 SC_FUNC symbol *findconst(const char *name,int *cmptag)
2705 sym=find_symbol(&loctab,name,-1,-1,cmptag); /* try local symbols first */
2706 if (sym==NULL || sym->ident!=iCONSTEXPR) { /* not found, or not a constant */
2708 sym=FindTaggedInHashTable(sp_Globals,name,fcurrent,cmptag);
2710 sym=FindInHashTable(sp_Globals,name,fcurrent);
2712 if (sym==NULL || sym->ident!=iCONSTEXPR)
2714 assert(sym->parent==NULL || (sym->usage & uENUMFIELD)!=0);
2715 /* ^^^ constants have no hierarchy, but enumeration fields may have a parent */
2719 SC_FUNC symbol *finddepend(const symbol *parent)
2723 sym=find_symbol_child(&loctab,parent); /* try local symbols first */
2724 if (sym==NULL) /* not found */
2725 sym=find_symbol_child(&glbtab,parent);
2731 * Adds a symbol to the symbol table (either global or local variables,
2732 * or global and local constants).
2734 SC_FUNC symbol *addsym(const char *name,cell addr,int ident,int vclass,int tag,int usage)
2736 symbol entry, **refer;
2738 /* labels may only be defined once */
2739 assert(ident!=iLABEL || findloc(name)==NULL);
2741 /* create an empty referrer list */
2742 if ((refer=(symbol**)malloc(sizeof(symbol*)))==NULL) {
2743 error(123); /* insufficient memory */
2748 /* first fill in the entry */
2749 memset(&entry,0,sizeof entry);
2750 strcpy(entry.name,name);
2751 entry.hash=NameHash(name);
2753 entry.codeaddr=code_idx;
2754 entry.vclass=(char)vclass;
2755 entry.ident=(char)ident;
2757 entry.usage=(char)usage;
2758 entry.fnumber=-1; /* assume global visibility (ignored for local symbols) */
2759 entry.lnumber=fline;
2763 /* then insert it in the list */
2764 if (vclass==sGLOBAL)
2765 return add_symbol(&glbtab,&entry,TRUE);
2766 return add_symbol(&loctab,&entry,FALSE);
2769 SC_FUNC symbol *addvariable(const char *name,cell addr,int ident,int vclass,int tag,
2770 int dim[],int numdim,int idxtag[])
2772 return addvariable2(name,addr,ident,vclass,tag,dim,numdim,idxtag,0);
2775 SC_FUNC symbol *addvariable2(const char *name,cell addr,int ident,int vclass,int tag,
2776 int dim[],int numdim,int idxtag[],int slength)
2780 /* global variables may only be defined once
2781 * One complication is that functions returning arrays declare an array
2782 * with the same name as the function, so the assertion must allow for
2783 * this special case. Another complication is that variables may be
2784 * "redeclared" if they are local to an automaton (and findglb() will find
2785 * the symbol without states if no symbol with states exists).
2787 assert(vclass!=sGLOBAL || (sym=findglb(name,sGLOBAL))==NULL || (sym->usage & uDEFINE)==0
2788 || sym->ident==iFUNCTN && sym==curfunc
2789 || sym->states==NULL && sc_curstates>0);
2791 if (ident==iARRAY || ident==iREFARRAY) {
2792 symbol *parent=NULL,*top;
2794 sym=NULL; /* to avoid a compiler warning */
2795 for (level=0; level<numdim; level++) {
2796 top=addsym(name,addr,ident,vclass,tag,uDEFINE);
2797 top->dim.array.length=dim[level];
2798 if (tag == pc_tag_string && level == numdim - 1) {
2800 top->dim.array.length=dim[level] * sizeof(cell);
2802 top->dim.array.slength=slength;
2804 top->dim.array.slength=0;
2806 top->dim.array.level=(short)(numdim-level-1);
2807 top->x.tags.index=idxtag[level];
2814 sym=addsym(name,addr,ident,vclass,tag,uDEFINE);
2821 * Returns te next internal label number. The global variable sc_labnum is
2822 * initialized to zero.
2824 SC_FUNC int getlabel(void)
2831 * Converts a number to a hexadecimal string and returns a pointer to that
2832 * string. This function is NOT re-entrant.
2834 SC_FUNC char *itoh(ucell val)
2836 static char itohstr[30];
2838 int i,nibble[16]; /* a 64-bit hexadecimal cell has 16 nibbles */
2841 #if PAWN_CELL_SIZE==16
2843 #elif PAWN_CELL_SIZE==32
2845 #elif PAWN_CELL_SIZE==64
2848 #error Unsupported cell size
2851 for (i=0; i<max; i+=1){
2852 nibble[i]=(int)(val & 0x0f); /* nibble 0 is lowest nibble */
2856 while (nibble[i]==0 && i>0) /* search for highest non-zero nibble */
2860 *ptr++=(char)('a'+(nibble[i]-10));
2862 *ptr++=(char)('0'+nibble[i]);
2865 *ptr='\0'; /* and a zero-terminator */