compiler-init/sc2.c
author Borja Ferrer <faluco@alliedmods.net>
Fri Jul 14 02:07:44 2006 +0000 (2006-07-14)
branchfaluco
changeset 6 abfa1699dd95
child 20 acfbfd258f7c
permissions -rw-r--r--
whoa svn is hard, sente will implode now
faluco@6
     1
/*  Pawn compiler - File input, preprocessing and lexical analysis functions
faluco@6
     2
 *
faluco@6
     3
 *  Copyright (c) ITB CompuPhase, 1997-2006
faluco@6
     4
 *
faluco@6
     5
 *  This software is provided "as-is", without any express or implied warranty.
faluco@6
     6
 *  In no event will the authors be held liable for any damages arising from
faluco@6
     7
 *  the use of this software.
faluco@6
     8
 *
faluco@6
     9
 *  Permission is granted to anyone to use this software for any purpose,
faluco@6
    10
 *  including commercial applications, and to alter it and redistribute it
faluco@6
    11
 *  freely, subject to the following restrictions:
faluco@6
    12
 *
faluco@6
    13
 *  1.  The origin of this software must not be misrepresented; you must not
faluco@6
    14
 *      claim that you wrote the original software. If you use this software in
faluco@6
    15
 *      a product, an acknowledgment in the product documentation would be
faluco@6
    16
 *      appreciated but is not required.
faluco@6
    17
 *  2.  Altered source versions must be plainly marked as such, and must not be
faluco@6
    18
 *      misrepresented as being the original software.
faluco@6
    19
 *  3.  This notice may not be removed or altered from any source distribution.
faluco@6
    20
 *
faluco@6
    21
 *  Version: $Id: sc2.c 3590 2006-06-24 14:16:39Z thiadmer $
faluco@6
    22
 */
faluco@6
    23
#include <assert.h>
faluco@6
    24
#include <stdio.h>
faluco@6
    25
#include <stdlib.h>
faluco@6
    26
#include <string.h>
faluco@6
    27
#include <ctype.h>
faluco@6
    28
#include <math.h>
faluco@6
    29
#include "lstring.h"
faluco@6
    30
#include "sc.h"
faluco@6
    31
#if defined LINUX || defined __FreeBSD__ || defined __OpenBSD__
faluco@6
    32
  #include <sclinux.h>
faluco@6
    33
#endif
faluco@6
    34
faluco@6
    35
#if defined FORTIFY
faluco@6
    36
  #include <alloc/fortify.h>
faluco@6
    37
#endif
faluco@6
    38
faluco@6
    39
/* flags for litchar() */
faluco@6
    40
#define RAWMODE         1
faluco@6
    41
#define UTF8MODE        2
faluco@6
    42
static cell litchar(const unsigned char **lptr,int flags);
faluco@6
    43
static symbol *find_symbol(const symbol *root,const char *name,int fnumber,int automaton,int *cmptag);
faluco@6
    44
faluco@6
    45
static void substallpatterns(unsigned char *line,int buffersize);
faluco@6
    46
static int match(char *st,int end);
faluco@6
    47
static int alpha(char c);
faluco@6
    48
faluco@6
    49
#define SKIPMODE      1 /* bit field in "#if" stack */
faluco@6
    50
#define PARSEMODE     2 /* bit field in "#if" stack */
faluco@6
    51
#define HANDLED_ELSE  4 /* bit field in "#if" stack */
faluco@6
    52
#define SKIPPING      (skiplevel>0 && (ifstack[skiplevel-1] & SKIPMODE)==SKIPMODE)
faluco@6
    53
faluco@6
    54
static short icomment;  /* currently in multiline comment? */
faluco@6
    55
static char ifstack[sCOMP_STACK]; /* "#if" stack */
faluco@6
    56
static short iflevel;   /* nesting level if #if/#else/#endif */
faluco@6
    57
static short skiplevel; /* level at which we started skipping (including nested #if .. #endif) */
faluco@6
    58
static unsigned char term_expr[] = "";
faluco@6
    59
static int listline=-1; /* "current line" for the list file */
faluco@6
    60
faluco@6
    61
faluco@6
    62
/*  pushstk & popstk
faluco@6
    63
 *
faluco@6
    64
 *  Uses a LIFO stack to store information. The stack is used by doinclude(),
faluco@6
    65
 *  doswitch() (to hold the state of "swactive") and some other routines.
faluco@6
    66
 *
faluco@6
    67
 *  Porting note: I made the bold assumption that an integer will not be
faluco@6
    68
 *  larger than a pointer (it may be smaller). That is, the stack element
faluco@6
    69
 *  is typedef'ed as a pointer type, but I also store integers on it. See
faluco@6
    70
 *  SC.H for "stkitem"
faluco@6
    71
 *
faluco@6
    72
 *  Global references: stack,stkidx,stktop (private to pushstk(), popstk()
faluco@6
    73
 *                     and clearstk())
faluco@6
    74
 */
faluco@6
    75
static stkitem *stack=NULL;
faluco@6
    76
static int stkidx=0,stktop=0;
faluco@6
    77
faluco@6
    78
SC_FUNC void pushstk(stkitem val)
faluco@6
    79
{
faluco@6
    80
  assert(stkidx<=stktop);
faluco@6
    81
  if (stkidx==stktop) {
faluco@6
    82
    stkitem *newstack;
faluco@6
    83
    int newsize= (stktop==0) ? 16 : 2*stktop;
faluco@6
    84
    /* try to resize the stack */
faluco@6
    85
    assert(newsize>stktop);
faluco@6
    86
    newstack=(stkitem*)malloc(newsize*sizeof(stkitem));
faluco@6
    87
    if (newstack==NULL)
faluco@6
    88
      error(102,"parser stack");  /* stack overflow (recursive include?) */
faluco@6
    89
    /* swap the stacks */
faluco@6
    90
    memcpy(newstack,stack,stkidx*sizeof(stkitem));
faluco@6
    91
    if (stack!=NULL)
faluco@6
    92
      free(stack);
faluco@6
    93
    stack=newstack;
faluco@6
    94
    stktop=newsize;
faluco@6
    95
  } /* if */
faluco@6
    96
  assert(stkidx<stktop);
faluco@6
    97
  stack[stkidx]=val;
faluco@6
    98
  stkidx+=1;
faluco@6
    99
}
faluco@6
   100
faluco@6
   101
SC_FUNC stkitem popstk(void)
faluco@6
   102
{
faluco@6
   103
  if (stkidx==0) {
faluco@6
   104
    stkitem s;
faluco@6
   105
    s.i=-1;             /* stack is empty */
faluco@6
   106
    return s;
faluco@6
   107
  } /* if */
faluco@6
   108
  stkidx--;
faluco@6
   109
  assert(stack!=NULL);
faluco@6
   110
  return stack[stkidx];
faluco@6
   111
}
faluco@6
   112
faluco@6
   113
SC_FUNC void clearstk(void)
faluco@6
   114
{
faluco@6
   115
  assert(stack!=NULL || stktop==0);
faluco@6
   116
  if (stack!=NULL) {
faluco@6
   117
    free(stack);
faluco@6
   118
    stack=NULL;
faluco@6
   119
    stktop=0;
faluco@6
   120
  } /* if */
faluco@6
   121
  assert(stktop==0);
faluco@6
   122
}
faluco@6
   123
faluco@6
   124
SC_FUNC int plungequalifiedfile(char *name)
faluco@6
   125
{
faluco@6
   126
static char *extensions[] = { ".inc", ".p", ".pawn" };
faluco@6
   127
  FILE *fp;
faluco@6
   128
  char *ext;
faluco@6
   129
  int ext_idx;
faluco@6
   130
faluco@6
   131
  ext_idx=0;
faluco@6
   132
  do {
faluco@6
   133
    fp=(FILE*)pc_opensrc(name);
faluco@6
   134
    ext=strchr(name,'\0');      /* save position */
faluco@6
   135
    if (fp==NULL) {
faluco@6
   136
      /* try to append an extension */
faluco@6
   137
      strcpy(ext,extensions[ext_idx]);
faluco@6
   138
      fp=(FILE*)pc_opensrc(name);
faluco@6
   139
      if (fp==NULL)
faluco@6
   140
        *ext='\0';              /* on failure, restore filename */
faluco@6
   141
    } /* if */
faluco@6
   142
    ext_idx++;
faluco@6
   143
  } while (fp==NULL && ext_idx<(sizeof extensions / sizeof extensions[0]));
faluco@6
   144
  if (fp==NULL) {
faluco@6
   145
    *ext='\0';                  /* restore filename */
faluco@6
   146
    return FALSE;
faluco@6
   147
  } /* if */
faluco@6
   148
  PUSHSTK_P(inpf);
faluco@6
   149
  PUSHSTK_P(inpfname);          /* pointer to current file name */
faluco@6
   150
  PUSHSTK_P(curlibrary);
faluco@6
   151
  PUSHSTK_I(iflevel);
faluco@6
   152
  assert(!SKIPPING);
faluco@6
   153
  assert(skiplevel==iflevel);   /* these two are always the same when "parsing" */
faluco@6
   154
  PUSHSTK_I(sc_is_utf8);
faluco@6
   155
  PUSHSTK_I(icomment);
faluco@6
   156
  PUSHSTK_I(fcurrent);
faluco@6
   157
  PUSHSTK_I(fline);
faluco@6
   158
  inpfname=duplicatestring(name);/* set name of include file */
faluco@6
   159
  if (inpfname==NULL)
faluco@6
   160
    error(103);             /* insufficient memory */
faluco@6
   161
  inpf=fp;                  /* set input file pointer to include file */
faluco@6
   162
  fnumber++;
faluco@6
   163
  fline=0;                  /* set current line number to 0 */
faluco@6
   164
  fcurrent=fnumber;
faluco@6
   165
  icomment=0;               /* not in a comment */
faluco@6
   166
  insert_dbgfile(inpfname);
faluco@6
   167
  setfiledirect(inpfname);
faluco@6
   168
  listline=-1;              /* force a #line directive when changing the file */
faluco@6
   169
  sc_is_utf8=(short)scan_utf8(inpf,name);
faluco@6
   170
  return TRUE;
faluco@6
   171
}
faluco@6
   172
faluco@6
   173
SC_FUNC int plungefile(char *name,int try_currentpath,int try_includepaths)
faluco@6
   174
{
faluco@6
   175
  int result=FALSE;
faluco@6
   176
faluco@6
   177
  if (try_currentpath) {
faluco@6
   178
    result=plungequalifiedfile(name);
faluco@6
   179
    if (!result) {
faluco@6
   180
      /* failed to open the file in the active directory, try to open the file
faluco@6
   181
       * in the same directory as the current file --but first check whether
faluco@6
   182
       * there is a (relative) path for the current file
faluco@6
   183
       */
faluco@6
   184
      char *ptr;
faluco@6
   185
      if ((ptr=strrchr(inpfname,DIRSEP_CHAR))!=0) {
faluco@6
   186
        int len=(int)(ptr-inpfname)+1;
faluco@6
   187
        if (len+strlen(name)<_MAX_PATH) {
faluco@6
   188
          char path[_MAX_PATH];
faluco@6
   189
          strlcpy(path,inpfname,len+1);
faluco@6
   190
          strlcat(path,name,sizeof path);
faluco@6
   191
          result=plungequalifiedfile(path);
faluco@6
   192
        } /* if */
faluco@6
   193
      } /* if */
faluco@6
   194
    } /* if */
faluco@6
   195
  } /* if */
faluco@6
   196
faluco@6
   197
  if (try_includepaths && name[0]!=DIRSEP_CHAR) {
faluco@6
   198
    int i;
faluco@6
   199
    char *ptr;
faluco@6
   200
    for (i=0; !result && (ptr=get_path(i))!=NULL; i++) {
faluco@6
   201
      char path[_MAX_PATH];
faluco@6
   202
      strlcpy(path,ptr,sizeof path);
faluco@6
   203
      strlcat(path,name,sizeof path);
faluco@6
   204
      result=plungequalifiedfile(path);
faluco@6
   205
    } /* while */
faluco@6
   206
  } /* if */
faluco@6
   207
  return result;
faluco@6
   208
}
faluco@6
   209
faluco@6
   210
static void check_empty(const unsigned char *lptr)
faluco@6
   211
{
faluco@6
   212
  /* verifies that the string contains only whitespace */
faluco@6
   213
  while (*lptr<=' ' && *lptr!='\0')
faluco@6
   214
    lptr++;
faluco@6
   215
  if (*lptr!='\0')
faluco@6
   216
    error(38);          /* extra characters on line */
faluco@6
   217
}
faluco@6
   218
faluco@6
   219
/*  doinclude
faluco@6
   220
 *
faluco@6
   221
 *  Gets the name of an include file, pushes the old file on the stack and
faluco@6
   222
 *  sets some options. This routine doesn't use lex(), since lex() doesn't
faluco@6
   223
 *  recognize file names (and directories).
faluco@6
   224
 *
faluco@6
   225
 *  Global references: inpf     (altered)
faluco@6
   226
 *                     inpfname (altered)
faluco@6
   227
 *                     fline    (altered)
faluco@6
   228
 *                     lptr     (altered)
faluco@6
   229
 */
faluco@6
   230
static void doinclude(int silent)
faluco@6
   231
{
faluco@6
   232
  char name[_MAX_PATH];
faluco@6
   233
  char symname[sNAMEMAX];
faluco@6
   234
  char *ptr;
faluco@6
   235
  char c;
faluco@6
   236
  int i, result;
faluco@6
   237
faluco@6
   238
  while (*lptr<=' ' && *lptr!='\0')         /* skip leading whitespace */
faluco@6
   239
    lptr++;
faluco@6
   240
  if (*lptr=='<' || *lptr=='\"'){
faluco@6
   241
    c=(char)((*lptr=='\"') ? '\"' : '>');   /* termination character */
faluco@6
   242
    lptr++;
faluco@6
   243
    while (*lptr<=' ' && *lptr!='\0')       /* skip whitespace after quote */
faluco@6
   244
      lptr++;
faluco@6
   245
  } else {
faluco@6
   246
    c='\0';
faluco@6
   247
  } /* if */
faluco@6
   248
faluco@6
   249
  i=0;
faluco@6
   250
  while (*lptr!=c && *lptr!='\0' && i<sizeof name - 1)  /* find the end of the string */
faluco@6
   251
    name[i++]=*lptr++;
faluco@6
   252
  while (i>0 && name[i-1]<=' ')
faluco@6
   253
    i--;                        /* strip trailing whitespace */
faluco@6
   254
  assert(i>=0 && i<sizeof name);
faluco@6
   255
  name[i]='\0';                 /* zero-terminate the string */
faluco@6
   256
faluco@6
   257
  if (*lptr!=c) {               /* verify correct string termination */
faluco@6
   258
    error(37);                  /* invalid string */
faluco@6
   259
    return;
faluco@6
   260
  } /* if */
faluco@6
   261
  if (c!='\0')
faluco@6
   262
    check_empty(lptr+1);        /* verify that the rest of the line is whitespace */
faluco@6
   263
faluco@6
   264
  /* create a symbol from the name of the include file; this allows the system
faluco@6
   265
   * to test for multiple inclusions
faluco@6
   266
   */
faluco@6
   267
  strcpy(symname,"_inc_");
faluco@6
   268
  if ((ptr=strrchr(name,DIRSEP_CHAR))!=NULL)
faluco@6
   269
    strlcat(symname,ptr+1,sizeof symname);
faluco@6
   270
  else
faluco@6
   271
    strlcat(symname,name,sizeof symname);
faluco@6
   272
  if (find_symbol(&glbtab,symname,fcurrent,-1,NULL)==NULL) {
faluco@6
   273
    /* constant is not present, so this file has not been included yet */
faluco@6
   274
faluco@6
   275
    /* Include files between "..." or without quotes are read from the current
faluco@6
   276
     * directory, or from a list of "include directories". Include files
faluco@6
   277
     * between <...> are only read from the list of include directories.
faluco@6
   278
     */
faluco@6
   279
    result=plungefile(name,(c!='>'),TRUE);
faluco@6
   280
    if (result)
faluco@6
   281
      add_constant(symname,1,sGLOBAL,0);
faluco@6
   282
    else if (!silent)
faluco@6
   283
      error(100,name);            /* cannot read from ... (fatal error) */
faluco@6
   284
  } /* if */
faluco@6
   285
}
faluco@6
   286
faluco@6
   287
/*  readline
faluco@6
   288
 *
faluco@6
   289
 *  Reads in a new line from the input file pointed to by "inpf". readline()
faluco@6
   290
 *  concatenates lines that end with a \ with the next line. If no more data
faluco@6
   291
 *  can be read from the file, readline() attempts to pop off the previous file
faluco@6
   292
 *  from the stack. If that fails too, it sets "freading" to 0.
faluco@6
   293
 *
faluco@6
   294
 *  Global references: inpf,fline,inpfname,freading,icomment (altered)
faluco@6
   295
 */
faluco@6
   296
static void readline(unsigned char *line)
faluco@6
   297
{
faluco@6
   298
  int i,num,cont;
faluco@6
   299
  unsigned char *ptr;
faluco@6
   300
faluco@6
   301
  if (lptr==term_expr)
faluco@6
   302
    return;
faluco@6
   303
  num=sLINEMAX;
faluco@6
   304
  cont=FALSE;
faluco@6
   305
  do {
faluco@6
   306
    if (inpf==NULL || pc_eofsrc(inpf)) {
faluco@6
   307
      if (cont)
faluco@6
   308
        error(49);        /* invalid line continuation */
faluco@6
   309
      if (inpf!=NULL && inpf!=inpf_org)
faluco@6
   310
        pc_closesrc(inpf);
faluco@6
   311
      i=POPSTK_I();
faluco@6
   312
      if (i==-1) {        /* All's done; popstk() returns "stack is empty" */
faluco@6
   313
        freading=FALSE;
faluco@6
   314
        *line='\0';
faluco@6
   315
        /* when there is nothing more to read, the #if/#else stack should
faluco@6
   316
         * be empty and we should not be in a comment
faluco@6
   317
         */
faluco@6
   318
        assert(iflevel>=0);
faluco@6
   319
        if (iflevel>0)
faluco@6
   320
          error(1,"#endif","-end of file-");
faluco@6
   321
        else if (icomment!=0)
faluco@6
   322
          error(1,"*/","-end of file-");
faluco@6
   323
        return;
faluco@6
   324
      } /* if */
faluco@6
   325
      fline=i;
faluco@6
   326
      fcurrent=(short)POPSTK_I();
faluco@6
   327
      icomment=(short)POPSTK_I();
faluco@6
   328
      sc_is_utf8=(short)POPSTK_I();
faluco@6
   329
      iflevel=(short)POPSTK_I();
faluco@6
   330
      skiplevel=iflevel;        /* this condition held before including the file */
faluco@6
   331
      assert(!SKIPPING);        /* idem ditto */
faluco@6
   332
      curlibrary=(constvalue *)POPSTK_P();
faluco@6
   333
      free(inpfname);           /* return memory allocated for the include file name */
faluco@6
   334
      inpfname=(char *)POPSTK_P();
faluco@6
   335
      inpf=(FILE *)POPSTK_P();
faluco@6
   336
      insert_dbgfile(inpfname);
faluco@6
   337
      setfiledirect(inpfname);
faluco@6
   338
      listline=-1;              /* force a #line directive when changing the file */
faluco@6
   339
    } /* if */
faluco@6
   340
faluco@6
   341
    if (pc_readsrc(inpf,line,num)==NULL) {
faluco@6
   342
      *line='\0';     /* delete line */
faluco@6
   343
      cont=FALSE;
faluco@6
   344
    } else {
faluco@6
   345
      /* check whether to erase leading spaces */
faluco@6
   346
      if (cont) {
faluco@6
   347
        unsigned char *ptr=line;
faluco@6
   348
        while (*ptr<=' ' && *ptr!='\0')
faluco@6
   349
          ptr++;
faluco@6
   350
        if (ptr!=line)
faluco@6
   351
          memmove(line,ptr,strlen((char*)ptr)+1);
faluco@6
   352
      } /* if */
faluco@6
   353
      cont=FALSE;
faluco@6
   354
      /* check whether a full line was read */
faluco@6
   355
      if (strchr((char*)line,'\n')==NULL && !pc_eofsrc(inpf))
faluco@6
   356
        error(75);      /* line too long */
faluco@6
   357
      /* check if the next line must be concatenated to this line */
faluco@6
   358
      if ((ptr=(unsigned char*)strchr((char*)line,'\n'))==NULL)
faluco@6
   359
        ptr=(unsigned char*)strchr((char*)line,'\r');
faluco@6
   360
      if (ptr!=NULL && ptr>line) {
faluco@6
   361
        assert(*(ptr+1)=='\0'); /* '\n' or '\r' should be last in the string */
faluco@6
   362
        while (ptr>line && *ptr<=' ')
faluco@6
   363
          ptr--;        /* skip trailing whitespace */
faluco@6
   364
        if (*ptr=='\\') {
faluco@6
   365
          cont=TRUE;
faluco@6
   366
          /* set '\a' at the position of '\\' to make it possible to check
faluco@6
   367
           * for a line continuation in a single line comment (error 49)
faluco@6
   368
           */
faluco@6
   369
          *ptr++='\a';
faluco@6
   370
          *ptr='\0';    /* erase '\n' (and any trailing whitespace) */
faluco@6
   371
        } /* if */
faluco@6
   372
      } /* if */
faluco@6
   373
      num-=strlen((char*)line);
faluco@6
   374
      line+=strlen((char*)line);
faluco@6
   375
    } /* if */
faluco@6
   376
    fline+=1;
faluco@6
   377
  } while (num>=0 && cont);
faluco@6
   378
}
faluco@6
   379
faluco@6
   380
/*  stripcom
faluco@6
   381
 *
faluco@6
   382
 *  Replaces all comments from the line by space characters. It updates
faluco@6
   383
 *  a global variable ("icomment") for multiline comments.
faluco@6
   384
 *
faluco@6
   385
 *  This routine also supports the C++ extension for single line comments.
faluco@6
   386
 *  These comments are started with "//" and end at the end of the line.
faluco@6
   387
 *
faluco@6
   388
 *  The function also detects (and manages) "documentation comments". The
faluco@6
   389
 *  global variable "icomment" is set to 2 for documentation comments.
faluco@6
   390
 *
faluco@6
   391
 *  Global references: icomment  (private to "stripcom")
faluco@6
   392
 */
faluco@6
   393
static void stripcom(unsigned char *line)
faluco@6
   394
{
faluco@6
   395
  char c;
faluco@6
   396
  #if !defined SC_LIGHT
faluco@6
   397
    #define COMMENT_LIMIT 100
faluco@6
   398
    #define COMMENT_MARGIN 40   /* length of the longest word */
faluco@6
   399
    char comment[COMMENT_LIMIT+COMMENT_MARGIN];
faluco@6
   400
    int commentidx=0;
faluco@6
   401
    int skipstar=TRUE;
faluco@6
   402
    static int prev_singleline=FALSE;
faluco@6
   403
    int singleline=prev_singleline;
faluco@6
   404
faluco@6
   405
    prev_singleline=FALSE;  /* preset */
faluco@6
   406
  #endif
faluco@6
   407
faluco@6
   408
  while (*line){
faluco@6
   409
    if (icomment!=0) {
faluco@6
   410
      if (*line=='*' && *(line+1)=='/') {
faluco@6
   411
        #if !defined SC_LIGHT
faluco@6
   412
          if (icomment==2) {
faluco@6
   413
            assert(commentidx<COMMENT_LIMIT+COMMENT_MARGIN);
faluco@6
   414
            comment[commentidx]='\0';
faluco@6
   415
            if (strlen(comment)>0)
faluco@6
   416
              insert_docstring(comment);
faluco@6
   417
          } /* if */
faluco@6
   418
        #endif
faluco@6
   419
        icomment=0;     /* comment has ended */
faluco@6
   420
        *line=' ';      /* replace '*' and '/' characters by spaces */
faluco@6
   421
        *(line+1)=' ';
faluco@6
   422
        line+=2;
faluco@6
   423
      } else {
faluco@6
   424
        if (*line=='/' && *(line+1)=='*')
faluco@6
   425
          error(216);   /* nested comment */
faluco@6
   426
        #if !defined SC_LIGHT
faluco@6
   427
          /* collect the comment characters in a string */
faluco@6
   428
          if (icomment==2) {
faluco@6
   429
            if (skipstar && (*line!='\0' && *line<=' ' || *line=='*')) {
faluco@6
   430
              /* ignore leading whitespace and '*' characters */
faluco@6
   431
            } else if (commentidx<COMMENT_LIMIT+COMMENT_MARGIN-1) {
faluco@6
   432
              comment[commentidx++]=(char)((*line!='\n') ? *line : ' ');
faluco@6
   433
              if (commentidx>COMMENT_LIMIT && *line!='\0' && *line<=' ') {
faluco@6
   434
                comment[commentidx]='\0';
faluco@6
   435
                insert_docstring(comment);
faluco@6
   436
                commentidx=0;
faluco@6
   437
              } /* if */
faluco@6
   438
              skipstar=FALSE;
faluco@6
   439
            } /* if */
faluco@6
   440
          } /* if */
faluco@6
   441
        #endif
faluco@6
   442
        *line=' ';      /* replace comments by spaces */
faluco@6
   443
        line+=1;
faluco@6
   444
      } /* if */
faluco@6
   445
    } else {
faluco@6
   446
      if (*line=='/' && *(line+1)=='*'){
faluco@6
   447
        icomment=1;     /* start comment */
faluco@6
   448
        #if !defined SC_LIGHT
faluco@6
   449
          /* there must be two "*" behind the slash and then white space */
faluco@6
   450
          if (*(line+2)=='*' && *(line+3)<=' ') {
faluco@6
   451
            /* if we are not in a function, we must attach the previous block
faluco@6
   452
             * to the global documentation
faluco@6
   453
             */
faluco@6
   454
            if (curfunc==NULL && get_docstring(0)!=NULL)
faluco@6
   455
              sc_attachdocumentation(NULL);
faluco@6
   456
            icomment=2; /* documentation comment */
faluco@6
   457
          } /* if */
faluco@6
   458
          commentidx=0;
faluco@6
   459
          skipstar=TRUE;
faluco@6
   460
        #endif
faluco@6
   461
        *line=' ';      /* replace '/' and '*' characters by spaces */
faluco@6
   462
        *(line+1)=' ';
faluco@6
   463
        line+=2;
faluco@6
   464
        if (icomment==2)
faluco@6
   465
          *line++=' ';
faluco@6
   466
      } else if (*line=='/' && *(line+1)=='/'){  /* comment to end of line */
faluco@6
   467
        if (strchr((char*)line,'\a')!=NULL)
faluco@6
   468
          error(49);    /* invalid line continuation */
faluco@6
   469
        #if !defined SC_LIGHT
faluco@6
   470
          if (*(line+2)=='/' && *(line+3)<=' ') {
faluco@6
   471
            /* documentation comment */
faluco@6
   472
            char *str=(char*)line+3;
faluco@6
   473
            char *end;
faluco@6
   474
            while (*str<=' ' && *str!='\0')
faluco@6
   475
              str++;    /* skip leading whitespace */
faluco@6
   476
            if ((end=strrchr(str,'\n'))!=NULL)
faluco@6
   477
              *end='\0';/* erase trailing '\n' */
faluco@6
   478
            /* if there is a disjunct block, we may need to attach the previous
faluco@6
   479
             * block to the global documentation
faluco@6
   480
             */
faluco@6
   481
            if (!singleline && curfunc==NULL && get_docstring(0)!=NULL)
faluco@6
   482
              sc_attachdocumentation(NULL);
faluco@6
   483
            insert_docstring(str);
faluco@6
   484
            prev_singleline=TRUE;
faluco@6
   485
          } /* if */
faluco@6
   486
        #endif
faluco@6
   487
        *line++='\n';   /* put "newline" at first slash */
faluco@6
   488
        *line='\0';     /* put "zero-terminator" at second slash */
faluco@6
   489
      } else {
faluco@6
   490
        if (*line=='\"' || *line=='\''){        /* leave literals unaltered */
faluco@6
   491
          c=*line;      /* ending quote, single or double */
faluco@6
   492
          line+=1;
faluco@6
   493
          while ((*line!=c || *(line-1)==sc_ctrlchar) && *line!='\0')
faluco@6
   494
            line+=1;
faluco@6
   495
          line+=1;      /* skip final quote */
faluco@6
   496
        } else {
faluco@6
   497
          line+=1;
faluco@6
   498
        } /* if */
faluco@6
   499
      } /* if */
faluco@6
   500
    } /* if */
faluco@6
   501
  } /* while */
faluco@6
   502
  #if !defined SC_LIGHT
faluco@6
   503
    if (icomment==2) {
faluco@6
   504
      assert(commentidx<COMMENT_LIMIT+COMMENT_MARGIN);
faluco@6
   505
      comment[commentidx]='\0';
faluco@6
   506
      if (strlen(comment)>0)
faluco@6
   507
        insert_docstring(comment);
faluco@6
   508
    } /* if */
faluco@6
   509
  #endif
faluco@6
   510
}
faluco@6
   511
faluco@6
   512
/*  btoi
faluco@6
   513
 *
faluco@6
   514
 *  Attempts to interpret a numeric symbol as a boolean value. On success
faluco@6
   515
 *  it returns the number of characters processed (so the line pointer can be
faluco@6
   516
 *  adjusted) and the value is stored in "val". Otherwise it returns 0 and
faluco@6
   517
 *  "val" is garbage.
faluco@6
   518
 *
faluco@6
   519
 *  A boolean value must start with "0b"
faluco@6
   520
 */
faluco@6
   521
static int btoi(cell *val,const unsigned char *curptr)
faluco@6
   522
{
faluco@6
   523
  const unsigned char *ptr;
faluco@6
   524
faluco@6
   525
  *val=0;
faluco@6
   526
  ptr=curptr;
faluco@6
   527
  if (*ptr=='0' && *(ptr+1)=='b') {
faluco@6
   528
    ptr+=2;
faluco@6
   529
    while (*ptr=='0' || *ptr=='1' || *ptr=='_') {
faluco@6
   530
      if (*ptr!='_')
faluco@6
   531
        *val=(*val<<1) | (*ptr-'0');
faluco@6
   532
      ptr++;
faluco@6
   533
    } /* while */
faluco@6
   534
  } else {
faluco@6
   535
    return 0;
faluco@6
   536
  } /* if */
faluco@6
   537
  if (alphanum(*ptr))   /* number must be delimited by non-alphanumeric char */
faluco@6
   538
    return 0;
faluco@6
   539
  else
faluco@6
   540
    return (int)(ptr-curptr);
faluco@6
   541
}
faluco@6
   542
faluco@6
   543
/*  dtoi
faluco@6
   544
 *
faluco@6
   545
 *  Attempts to interpret a numeric symbol as a decimal value. On success
faluco@6
   546
 *  it returns the number of characters processed and the value is stored in
faluco@6
   547
 *  "val". Otherwise it returns 0 and "val" is garbage.
faluco@6
   548
 */
faluco@6
   549
static int dtoi(cell *val,const unsigned char *curptr)
faluco@6
   550
{
faluco@6
   551
  const unsigned char *ptr;
faluco@6
   552
faluco@6
   553
  *val=0;
faluco@6
   554
  ptr=curptr;
faluco@6
   555
  if (!isdigit(*ptr))   /* should start with digit */
faluco@6
   556
    return 0;
faluco@6
   557
  while (isdigit(*ptr) || *ptr=='_') {
faluco@6
   558
    if (*ptr!='_')
faluco@6
   559
      *val=(*val*10)+(*ptr-'0');
faluco@6
   560
    ptr++;
faluco@6
   561
  } /* while */
faluco@6
   562
  if (alphanum(*ptr))   /* number must be delimited by non-alphanumerical */
faluco@6
   563
    return 0;
faluco@6
   564
  if (*ptr=='.' && isdigit(*(ptr+1)))
faluco@6
   565
    return 0;           /* but a fractional part must not be present */
faluco@6
   566
  return (int)(ptr-curptr);
faluco@6
   567
}
faluco@6
   568
faluco@6
   569
/*  htoi
faluco@6
   570
 *
faluco@6
   571
 *  Attempts to interpret a numeric symbol as a hexadecimal value. On
faluco@6
   572
 *  success it returns the number of characters processed and the value is
faluco@6
   573
 *  stored in "val". Otherwise it return 0 and "val" is garbage.
faluco@6
   574
 */
faluco@6
   575
static int htoi(cell *val,const unsigned char *curptr)
faluco@6
   576
{
faluco@6
   577
  const unsigned char *ptr;
faluco@6
   578
faluco@6
   579
  *val=0;
faluco@6
   580
  ptr=curptr;
faluco@6
   581
  if (!isdigit(*ptr))   /* should start with digit */
faluco@6
   582
    return 0;
faluco@6
   583
  if (*ptr=='0' && *(ptr+1)=='x') {     /* C style hexadecimal notation */
faluco@6
   584
    ptr+=2;
faluco@6
   585
    while (ishex(*ptr) || *ptr=='_') {
faluco@6
   586
      if (*ptr!='_') {
faluco@6
   587
        assert(ishex(*ptr));
faluco@6
   588
        *val= *val<<4;
faluco@6
   589
        if (isdigit(*ptr))
faluco@6
   590
          *val+= (*ptr-'0');
faluco@6
   591
        else
faluco@6
   592
          *val+= (tolower(*ptr)-'a'+10);
faluco@6
   593
      } /* if */
faluco@6
   594
      ptr++;
faluco@6
   595
    } /* while */
faluco@6
   596
  } else {
faluco@6
   597
    return 0;
faluco@6
   598
  } /* if */
faluco@6
   599
  if (alphanum(*ptr))
faluco@6
   600
    return 0;
faluco@6
   601
  else
faluco@6
   602
    return (int)(ptr-curptr);
faluco@6
   603
}
faluco@6
   604
faluco@6
   605
#if defined __GNUC__
faluco@6
   606
static double pow10(int value)
faluco@6
   607
{
faluco@6
   608
  double res=1.0;
faluco@6
   609
  while (value>=4) {
faluco@6
   610
    res*=10000.0;
faluco@6
   611
    value-=5;
faluco@6
   612
  } /* while */
faluco@6
   613
  while (value>=2) {
faluco@6
   614
    res*=100.0;
faluco@6
   615
    value-=2;
faluco@6
   616
  } /* while */
faluco@6
   617
  while (value>=1) {
faluco@6
   618
    res*=10.0;
faluco@6
   619
    value-=1;
faluco@6
   620
  } /* while */
faluco@6
   621
  return res;
faluco@6
   622
}
faluco@6
   623
#endif
faluco@6
   624
faluco@6
   625
/*  ftoi
faluco@6
   626
 *
faluco@6
   627
 *  Attempts to interpret a numeric symbol as a rational number, either as
faluco@6
   628
 *  IEEE 754 single/double precision floating point or as a fixed point integer.
faluco@6
   629
 *  On success it returns the number of characters processed and the value is
faluco@6
   630
 *  stored in "val". Otherwise it returns 0 and "val" is unchanged.
faluco@6
   631
 *
faluco@6
   632
 *  Pawn has stricter definition for rational numbers than most:
faluco@6
   633
 *  o  the value must start with a digit; ".5" is not a valid number, you
faluco@6
   634
 *     should write "0.5"
faluco@6
   635
 *  o  a period must appear in the value, even if an exponent is given; "2e3"
faluco@6
   636
 *     is not a valid number, you should write "2.0e3"
faluco@6
   637
 *  o  at least one digit must follow the period; "6." is not a valid number,
faluco@6
   638
 *     you should write "6.0"
faluco@6
   639
 */
faluco@6
   640
static int ftoi(cell *val,const unsigned char *curptr)
faluco@6
   641
{
faluco@6
   642
  const unsigned char *ptr;
faluco@6
   643
  double fnum,ffrac,fmult;
faluco@6
   644
  unsigned long dnum,dbase;
faluco@6
   645
  int i, ignore;
faluco@6
   646
faluco@6
   647
  assert(rational_digits>=0 && rational_digits<9);
faluco@6
   648
  for (i=0,dbase=1; i<rational_digits; i++)
faluco@6
   649
    dbase*=10;
faluco@6
   650
  fnum=0.0;
faluco@6
   651
  dnum=0L;
faluco@6
   652
  ptr=curptr;
faluco@6
   653
  if (!isdigit(*ptr))   /* should start with digit */
faluco@6
   654
    return 0;
faluco@6
   655
  while (isdigit(*ptr) || *ptr=='_') {
faluco@6
   656
    if (*ptr!='_') {
faluco@6
   657
      fnum=(fnum*10.0)+(*ptr-'0');
faluco@6
   658
      dnum=(dnum*10L)+(*ptr-'0')*dbase;
faluco@6
   659
    } /* if */
faluco@6
   660
    ptr++;
faluco@6
   661
  } /* while */
faluco@6
   662
  if (*ptr!='.')
faluco@6
   663
    return 0;           /* there must be a period */
faluco@6
   664
  ptr++;
faluco@6
   665
  if (!isdigit(*ptr))   /* there must be at least one digit after the dot */
faluco@6
   666
    return 0;
faluco@6
   667
  ffrac=0.0;
faluco@6
   668
  fmult=1.0;
faluco@6
   669
  ignore=FALSE;
faluco@6
   670
  while (isdigit(*ptr) || *ptr=='_') {
faluco@6
   671
    if (*ptr!='_') {
faluco@6
   672
      ffrac=(ffrac*10.0)+(*ptr-'0');
faluco@6
   673
      fmult=fmult/10.0;
faluco@6
   674
      dbase /= 10L;
faluco@6
   675
      dnum += (*ptr-'0')*dbase;
faluco@6
   676
      if (dbase==0L && sc_rationaltag && rational_digits>0 && !ignore) {
faluco@6
   677
        error(222);     /* number of digits exceeds rational number precision */
faluco@6
   678
        ignore=TRUE;
faluco@6
   679
      } /* if */
faluco@6
   680
    } /* if */
faluco@6
   681
    ptr++;
faluco@6
   682
  } /* while */
faluco@6
   683
  fnum += ffrac*fmult;  /* form the number so far */
faluco@6
   684
  if (*ptr=='e') {      /* optional fractional part */
faluco@6
   685
    int exp,sign;
faluco@6
   686
    ptr++;
faluco@6
   687
    if (*ptr=='-') {
faluco@6
   688
      sign=-1;
faluco@6
   689
      ptr++;
faluco@6
   690
    } else {
faluco@6
   691
      sign=1;
faluco@6
   692
    } /* if */
faluco@6
   693
    if (!isdigit(*ptr)) /* 'e' should be followed by a digit */
faluco@6
   694
      return 0;
faluco@6
   695
    exp=0;
faluco@6
   696
    while (isdigit(*ptr)) {
faluco@6
   697
      exp=(exp*10)+(*ptr-'0');
faluco@6
   698
      ptr++;
faluco@6
   699
    } /* while */
faluco@6
   700
    #if defined __GNUC__
faluco@6
   701
      fmult=pow10(exp*sign);
faluco@6
   702
    #else
faluco@6
   703
      fmult=pow(10,exp*sign);
faluco@6
   704
    #endif
faluco@6
   705
    fnum *= fmult;
faluco@6
   706
    dnum *= (unsigned long)(fmult+0.5);
faluco@6
   707
  } /* if */
faluco@6
   708
faluco@6
   709
  /* decide how to store the number */
faluco@6
   710
  if (sc_rationaltag==0) {
faluco@6
   711
    error(70);          /* rational number support was not enabled */
faluco@6
   712
    *val=0;
faluco@6
   713
  } else if (rational_digits==0) {
faluco@6
   714
    /* floating point */
faluco@6
   715
    #if PAWN_CELL_SIZE==32
faluco@6
   716
      float value=(float)fnum;
faluco@6
   717
      *val=*((cell *)&value);
faluco@6
   718
      #if !defined NDEBUG
faluco@6
   719
        /* I assume that the C/C++ compiler stores "float" values in IEEE 754
faluco@6
   720
         * format (as mandated in the ANSI standard). Test this assumption
faluco@6
   721
         * anyway.
faluco@6
   722
         * Note: problems have been reported with GCC 3.2.x, version 3.3.x works.
faluco@6
   723
         */
faluco@6
   724
        { float test1 = 0.0, test2 = 50.0, test3 = -50.0;
faluco@6
   725
          uint32_t bit = 1;
faluco@6
   726
          /* test 0.0 == all bits 0 */
faluco@6
   727
          assert(*(uint32_t*)&test1==0x00000000L);
faluco@6
   728
          /* test sign & magnitude format */
faluco@6
   729
          assert(((*(uint32_t*)&test2) ^ (*(uint32_t*)&test3)) == (bit << (PAWN_CELL_SIZE-1)));
faluco@6
   730
          /* test a known value */
faluco@6
   731
          assert(*(uint32_t*)&test2==0x42480000L);
faluco@6
   732
        }
faluco@6
   733
      #endif
faluco@6
   734
    #elif PAWN_CELL_SIZE==64
faluco@6
   735
      *val=*((cell *)&fnum);
faluco@6
   736
      #if !defined NDEBUG
faluco@6
   737
        /* I assume that the C/C++ compiler stores "double" values in IEEE 754
faluco@6
   738
         * format (as mandated in the ANSI standard).
faluco@6
   739
         */
faluco@6
   740
        { float test1 = 0.0, test2 = 50.0, test3 = -50.0;
faluco@6
   741
          uint64_t bit = 1;
faluco@6
   742
          /* test 0.0 == all bits 0 */
faluco@6
   743
          assert(*(uint64_t*)&test1==0x00000000L);
faluco@6
   744
          /* test sign & magnitude format */
faluco@6
   745
          assert(((*(uint64_t*)&test2) ^ (*(uint64_t*)&test3)) == (bit << (PAWN_CELL_SIZE-1)));
faluco@6
   746
        }
faluco@6
   747
      #endif
faluco@6
   748
    #else
faluco@6
   749
      #error Unsupported cell size
faluco@6
   750
    #endif
faluco@6
   751
  } else {
faluco@6
   752
    /* fixed point */
faluco@6
   753
    *val=(cell)dnum;
faluco@6
   754
  } /* if */
faluco@6
   755
faluco@6
   756
  return (int)(ptr-curptr);
faluco@6
   757
}
faluco@6
   758
faluco@6
   759
/*  number
faluco@6
   760
 *
faluco@6
   761
 *  Reads in a number (binary, decimal or hexadecimal). It returns the number
faluco@6
   762
 *  of characters processed or 0 if the symbol couldn't be interpreted as a
faluco@6
   763
 *  number (in this case the argument "val" remains unchanged). This routine
faluco@6
   764
 *  relies on the 'early dropout' implementation of the logical or (||)
faluco@6
   765
 *  operator.
faluco@6
   766
 *
faluco@6
   767
 *  Note: the routine doesn't check for a sign (+ or -). The - is checked
faluco@6
   768
 *        for at "hier2()" (in fact, it is viewed as an operator, not as a
faluco@6
   769
 *        sign) and the + is invalid (as in K&R C, and unlike ANSI C).
faluco@6
   770
 */
faluco@6
   771
static int number(cell *val,const unsigned char *curptr)
faluco@6
   772
{
faluco@6
   773
  int i;
faluco@6
   774
  cell value;
faluco@6
   775
faluco@6
   776
  if ((i=btoi(&value,curptr))!=0      /* binary? */
faluco@6
   777
      || (i=htoi(&value,curptr))!=0   /* hexadecimal? */
faluco@6
   778
      || (i=dtoi(&value,curptr))!=0)  /* decimal? */
faluco@6
   779
  {
faluco@6
   780
    *val=value;
faluco@6
   781
    return i;
faluco@6
   782
  } else {
faluco@6
   783
    return 0;                      /* else not a number */
faluco@6
   784
  } /* if */
faluco@6
   785
}
faluco@6
   786
faluco@6
   787
static void chrcat(char *str,char chr)
faluco@6
   788
{
faluco@6
   789
  str=strchr(str,'\0');
faluco@6
   790
  *str++=chr;
faluco@6
   791
  *str='\0';
faluco@6
   792
}
faluco@6
   793
faluco@6
   794
static int preproc_expr(cell *val,int *tag)
faluco@6
   795
{
faluco@6
   796
  int result;
faluco@6
   797
  int index;
faluco@6
   798
  cell code_index;
faluco@6
   799
  char *term;
faluco@6
   800
faluco@6
   801
  /* Disable staging; it should be disabled already because
faluco@6
   802
   * expressions may not be cut off half-way between conditional
faluco@6
   803
   * compilations. Reset the staging index, but keep the code
faluco@6
   804
   * index.
faluco@6
   805
   */
faluco@6
   806
  if (stgget(&index,&code_index)) {
faluco@6
   807
    error(57);                          /* unfinished expression */
faluco@6
   808
    stgdel(0,code_index);
faluco@6
   809
    stgset(FALSE);
faluco@6
   810
  } /* if */
faluco@6
   811
  assert((lptr-pline)<(int)strlen((char*)pline));   /* lptr must point inside the string */
faluco@6
   812
  #if !defined NO_DEFINE
faluco@6
   813
    /* preprocess the string */
faluco@6
   814
    substallpatterns(pline,sLINEMAX);
faluco@6
   815
    assert((lptr-pline)<(int)strlen((char*)pline)); /* lptr must STILL point inside the string */
faluco@6
   816
  #endif
faluco@6
   817
  /* append a special symbol to the string, so the expression
faluco@6
   818
   * analyzer won't try to read a next line when it encounters
faluco@6
   819
   * an end-of-line
faluco@6
   820
   */
faluco@6
   821
  assert(strlen((char*)pline)<sLINEMAX);
faluco@6
   822
  term=strchr((char*)pline,'\0');
faluco@6
   823
  assert(term!=NULL);
faluco@6
   824
  chrcat((char*)pline,PREPROC_TERM);    /* the "DEL" code (see SC.H) */
faluco@6
   825
  result=constexpr(val,tag,NULL);       /* get value (or 0 on error) */
faluco@6
   826
  *term='\0';                           /* erase the token (if still present) */
faluco@6
   827
  lexclr(FALSE);                        /* clear any "pushed" tokens */
faluco@6
   828
  return result;
faluco@6
   829
}
faluco@6
   830
faluco@6
   831
/* getstring
faluco@6
   832
 * Returns returns a pointer behind the closing quote or to the other
faluco@6
   833
 * character that caused the input to be ended.
faluco@6
   834
 */
faluco@6
   835
static const unsigned char *getstring(unsigned char *dest,int max,const unsigned char *line)
faluco@6
   836
{
faluco@6
   837
  assert(dest!=NULL && line!=NULL);
faluco@6
   838
  *dest='\0';
faluco@6
   839
  while (*line<=' ' && *line!='\0')
faluco@6
   840
    line++;             /* skip whitespace */
faluco@6
   841
  if (*line=='"') {
faluco@6
   842
    int len=0;
faluco@6
   843
    line++;             /* skip " */
faluco@6
   844
    while (*line!='"' && *line!='\0') {
faluco@6
   845
      if (len<max-1)
faluco@6
   846
        dest[len++]=*line;
faluco@6
   847
      line++;
faluco@6
   848
    } /* if */
faluco@6
   849
    dest[len]='\0';
faluco@6
   850
    if (*line=='"')
faluco@6
   851
      line++;           /* skip closing " */
faluco@6
   852
    else
faluco@6
   853
      error(37);        /* invalid string */
faluco@6
   854
  } else {
faluco@6
   855
    error(37);          /* invalid string */
faluco@6
   856
  } /* if */
faluco@6
   857
  return line;
faluco@6
   858
}
faluco@6
   859
faluco@6
   860
enum {
faluco@6
   861
  CMD_NONE,
faluco@6
   862
  CMD_TERM,
faluco@6
   863
  CMD_EMPTYLINE,
faluco@6
   864
  CMD_CONDFALSE,
faluco@6
   865
  CMD_INCLUDE,
faluco@6
   866
  CMD_DEFINE,
faluco@6
   867
  CMD_IF,
faluco@6
   868
  CMD_DIRECTIVE,
faluco@6
   869
};
faluco@6
   870
faluco@6
   871
/*  command
faluco@6
   872
 *
faluco@6
   873
 *  Recognizes the compiler directives. The function returns:
faluco@6
   874
 *     CMD_NONE         the line must be processed
faluco@6
   875
 *     CMD_TERM         a pending expression must be completed before processing further lines
faluco@6
   876
 *     Other value: the line must be skipped, because:
faluco@6
   877
 *     CMD_CONDFALSE    false "#if.." code
faluco@6
   878
 *     CMD_EMPTYLINE    line is empty
faluco@6
   879
 *     CMD_INCLUDE      the line contains a #include directive
faluco@6
   880
 *     CMD_DEFINE       the line contains a #subst directive
faluco@6
   881
 *     CMD_IF           the line contains a #if/#else/#endif directive
faluco@6
   882
 *     CMD_DIRECTIVE    the line contains some other compiler directive
faluco@6
   883
 *
faluco@6
   884
 *  Global variables: iflevel, ifstack (altered)
faluco@6
   885
 *                    lptr      (altered)
faluco@6
   886
 */
faluco@6
   887
static int command(void)
faluco@6
   888
{
faluco@6
   889
  int tok,ret;
faluco@6
   890
  cell val;
faluco@6
   891
  char *str;
faluco@6
   892
  int index;
faluco@6
   893
  cell code_index;
faluco@6
   894
faluco@6
   895
  while (*lptr<=' ' && *lptr!='\0')
faluco@6
   896
    lptr+=1;
faluco@6
   897
  if (*lptr=='\0')
faluco@6
   898
    return CMD_EMPTYLINE;       /* empty line */
faluco@6
   899
  if (*lptr!='#')
faluco@6
   900
    return SKIPPING ? CMD_CONDFALSE : CMD_NONE; /* it is not a compiler directive */
faluco@6
   901
  /* compiler directive found */
faluco@6
   902
  indent_nowarn=TRUE;           /* allow loose indentation" */
faluco@6
   903
  lexclr(FALSE);                /* clear any "pushed" tokens */
faluco@6
   904
  /* on a pending expression, force to return a silent ';' token and force to
faluco@6
   905
   * re-read the line
faluco@6
   906
   */
faluco@6
   907
  if (!sc_needsemicolon && stgget(&index,&code_index)) {
faluco@6
   908
    lptr=term_expr;
faluco@6
   909
    return CMD_TERM;
faluco@6
   910
  } /* if */
faluco@6
   911
  tok=lex(&val,&str);
faluco@6
   912
  ret=SKIPPING ? CMD_CONDFALSE : CMD_DIRECTIVE;  /* preset 'ret' to CMD_DIRECTIVE (most common case) */
faluco@6
   913
  switch (tok) {
faluco@6
   914
  case tpIF:                    /* conditional compilation */
faluco@6
   915
    ret=CMD_IF;
faluco@6
   916
    assert(iflevel>=0);
faluco@6
   917
    if (iflevel>=sCOMP_STACK)
faluco@6
   918
      error(102,"Conditional compilation stack"); /* table overflow */
faluco@6
   919
    iflevel++;
faluco@6
   920
    if (SKIPPING)
faluco@6
   921
      break;                    /* break out of switch */
faluco@6
   922
    skiplevel=iflevel;
faluco@6
   923
    preproc_expr(&val,NULL);    /* get value (or 0 on error) */
faluco@6
   924
    ifstack[iflevel-1]=(char)(val ? PARSEMODE : SKIPMODE);
faluco@6
   925
    check_empty(lptr);
faluco@6
   926
    break;
faluco@6
   927
  case tpELSE:
faluco@6
   928
  case tpELSEIF:
faluco@6
   929
    ret=CMD_IF;
faluco@6
   930
    assert(iflevel>=0);
faluco@6
   931
    if (iflevel==0) {
faluco@6
   932
      error(26);                /* no matching #if */
faluco@6
   933
      errorset(sRESET,0);
faluco@6
   934
    } else {
faluco@6
   935
      /* check for earlier #else */
faluco@6
   936
      if ((ifstack[iflevel-1] & HANDLED_ELSE)==HANDLED_ELSE) {
faluco@6
   937
        if (tok==tpELSEIF)
faluco@6
   938
          error(61);            /* #elseif directive may not follow an #else */
faluco@6
   939
        else
faluco@6
   940
          error(60);            /* multiple #else directives between #if ... #endif */
faluco@6
   941
        errorset(sRESET,0);
faluco@6
   942
      } else {
faluco@6
   943
        assert(iflevel>0);
faluco@6
   944
        /* if there has been a "parse mode" on this level, set "skip mode",
faluco@6
   945
         * otherwise, clear "skip mode"
faluco@6
   946
         */
faluco@6
   947
        if ((ifstack[iflevel-1] & PARSEMODE)==PARSEMODE) {
faluco@6
   948
          /* there has been a parse mode already on this level, so skip the rest */
faluco@6
   949
          ifstack[iflevel-1] |= (char)SKIPMODE;
faluco@6
   950
        } else {
faluco@6
   951
          /* previous conditions were all FALSE */
faluco@6
   952
          if (tok==tpELSEIF) {
faluco@6
   953
            /* get new expression */
faluco@6
   954
            preproc_expr(&val,NULL);  /* get value (or 0 on error) */
faluco@6
   955
            ifstack[iflevel-1]=(char)(val ? PARSEMODE : SKIPMODE);
faluco@6
   956
          } else {
faluco@6
   957
            /* a simple #else, clear skip mode */
faluco@6
   958
            ifstack[iflevel-1] &= (char)~SKIPMODE;
faluco@6
   959
          } /* if */
faluco@6
   960
        } /* if */
faluco@6
   961
      } /* if */
faluco@6
   962
    } /* if */
faluco@6
   963
    check_empty(lptr);
faluco@6
   964
    break;
faluco@6
   965
  case tpENDIF:
faluco@6
   966
    ret=CMD_IF;
faluco@6
   967
    if (iflevel==0){
faluco@6
   968
      error(26);        /* no matching "#if" */
faluco@6
   969
      errorset(sRESET,0);
faluco@6
   970
    } else {
faluco@6
   971
      iflevel--;
faluco@6
   972
      if (iflevel<skiplevel)
faluco@6
   973
        skiplevel=iflevel;
faluco@6
   974
    } /* if */
faluco@6
   975
    check_empty(lptr);
faluco@6
   976
    break;
faluco@6
   977
  case tINCLUDE:                /* #include directive */
faluco@6
   978
  case tpTRYINCLUDE:
faluco@6
   979
    ret=CMD_INCLUDE;
faluco@6
   980
    if (!SKIPPING)
faluco@6
   981
      doinclude(tok==tpTRYINCLUDE);
faluco@6
   982
    break;
faluco@6
   983
  case tpFILE:
faluco@6
   984
    if (!SKIPPING) {
faluco@6
   985
      char pathname[_MAX_PATH];
faluco@6
   986
      lptr=getstring((unsigned char*)pathname,sizeof pathname,lptr);
faluco@6
   987
      if (strlen(pathname)>0) {
faluco@6
   988
        free(inpfname);
faluco@6
   989
        inpfname=duplicatestring(pathname);
faluco@6
   990
        if (inpfname==NULL)
faluco@6
   991
          error(103);           /* insufficient memory */
faluco@6
   992
      } /* if */
faluco@6
   993
    } /* if */
faluco@6
   994
    check_empty(lptr);
faluco@6
   995
    break;
faluco@6
   996
  case tpLINE:
faluco@6
   997
    if (!SKIPPING) {
faluco@6
   998
      if (lex(&val,&str)!=tNUMBER)
faluco@6
   999
        error(8);               /* invalid/non-constant expression */
faluco@6
  1000
      fline=(int)val;
faluco@6
  1001
    } /* if */
faluco@6
  1002
    check_empty(lptr);
faluco@6
  1003
    break;
faluco@6
  1004
  case tpASSERT:
faluco@6
  1005
    if (!SKIPPING && (sc_debug & sCHKBOUNDS)!=0) {
faluco@6
  1006
      for (str=(char*)lptr; *str<=' ' && *str!='\0'; str++)
faluco@6
  1007
        /* nothing */;          /* save start of expression */
faluco@6
  1008
      preproc_expr(&val,NULL);  /* get constant expression (or 0 on error) */
faluco@6
  1009
      if (!val)
faluco@6
  1010
        error(110,str);         /* assertion failed */
faluco@6
  1011
      check_empty(lptr);
faluco@6
  1012
    } /* if */
faluco@6
  1013
    break;
faluco@6
  1014
  case tpPRAGMA:
faluco@6
  1015
    if (!SKIPPING) {
faluco@6
  1016
      if (lex(&val,&str)==tSYMBOL) {
faluco@6
  1017
        if (strcmp(str,"amxlimit")==0) {
faluco@6
  1018
          preproc_expr(&pc_amxlimit,NULL);
faluco@6
  1019
        } else if (strcmp(str,"amxram")==0) {
faluco@6
  1020
          preproc_expr(&pc_amxram,NULL);
faluco@6
  1021
        } else if (strcmp(str,"codepage")==0) {
faluco@6
  1022
          char name[sNAMEMAX+1];
faluco@6
  1023
          while (*lptr<=' ' && *lptr!='\0')
faluco@6
  1024
            lptr++;
faluco@6
  1025
          if (*lptr=='"') {
faluco@6
  1026
            lptr=getstring((unsigned char*)name,sizeof name,lptr);
faluco@6
  1027
          } else {
faluco@6
  1028
            int i;
faluco@6
  1029
            for (i=0; i<sizeof name && alphanum(*lptr); i++,lptr++)
faluco@6
  1030
              name[i]=*lptr;
faluco@6
  1031
            name[i]='\0';
faluco@6
  1032
          } /* if */
faluco@6
  1033
          if (!cp_set(name))
faluco@6
  1034
            error(108);         /* codepage mapping file not found */
faluco@6
  1035
        } else if (strcmp(str,"compress")==0) {
faluco@6
  1036
          cell val;
faluco@6
  1037
          preproc_expr(&val,NULL);
faluco@6
  1038
          sc_compress=(int)val; /* switch code packing on/off */
faluco@6
  1039
        } else if (strcmp(str,"ctrlchar")==0) {
faluco@6
  1040
          while (*lptr<=' ' && *lptr!='\0')
faluco@6
  1041
            lptr++;
faluco@6
  1042
          if (*lptr=='\0') {
faluco@6
  1043
            sc_ctrlchar=sc_ctrlchar_org;
faluco@6
  1044
          } else {
faluco@6
  1045
            if (lex(&val,&str)!=tNUMBER)
faluco@6
  1046
              error(27);          /* invalid character constant */
faluco@6
  1047
            sc_ctrlchar=(char)val;
faluco@6
  1048
          } /* if */
faluco@6
  1049
        } else if (strcmp(str,"depricated")==0) {
faluco@6
  1050
          while (*lptr<=' ' && *lptr!='\0')
faluco@6
  1051
            lptr++;
faluco@6
  1052
          pc_depricate=(char*)malloc(strlen((char*)lptr)+1);
faluco@6
  1053
          if (pc_depricate!=NULL)
faluco@6
  1054
            strcpy(pc_depricate,(char*)lptr);
faluco@6
  1055
          lptr=(unsigned char*)strchr((char*)lptr,'\0'); /* skip to end (ignore "extra characters on line") */
faluco@6
  1056
        } else if (strcmp(str,"dynamic")==0) {
faluco@6
  1057
          preproc_expr(&pc_stksize,NULL);
faluco@6
  1058
        } else if (strcmp(str,"library")==0) {
faluco@6
  1059
          char name[sNAMEMAX+1];
faluco@6
  1060
          while (*lptr<=' ' && *lptr!='\0')
faluco@6
  1061
            lptr++;
faluco@6
  1062
          if (*lptr=='"') {
faluco@6
  1063
            lptr=getstring((unsigned char*)name,sizeof name,lptr);
faluco@6
  1064
          } else {
faluco@6
  1065
            int i;
faluco@6
  1066
            for (i=0; i<sizeof name && (alphanum(*lptr) || *lptr=='-'); i++,lptr++)
faluco@6
  1067
              name[i]=*lptr;
faluco@6
  1068
            name[i]='\0';
faluco@6
  1069
          } /* if */
faluco@6
  1070
          if (strlen(name)==0) {
faluco@6
  1071
            curlibrary=NULL;
faluco@6
  1072
          } else if (strcmp(name,"-")==0) {
faluco@6
  1073
            pc_addlibtable=FALSE;
faluco@6
  1074
          } else {
faluco@6
  1075
            /* add the name if it does not yet exist in the table */
faluco@6
  1076
            if (find_constval(&libname_tab,name,0)==NULL)
faluco@6
  1077
              curlibrary=append_constval(&libname_tab,name,0,0);
faluco@6
  1078
          } /* if */
faluco@6
  1079
        } else if (strcmp(str,"pack")==0) {
faluco@6
  1080
          cell val;
faluco@6
  1081
          preproc_expr(&val,NULL);      /* default = packed/unpacked */
faluco@6
  1082
          sc_packstr=(int)val;
faluco@6
  1083
        } else if (strcmp(str,"rational")==0) {
faluco@6
  1084
          char name[sNAMEMAX+1];
faluco@6
  1085
          cell digits=0;
faluco@6
  1086
          int i;
faluco@6
  1087
          /* first gather all information, start with the tag name */
faluco@6
  1088
          while (*lptr<=' ' && *lptr!='\0')
faluco@6
  1089
            lptr++;
faluco@6
  1090
          for (i=0; i<sizeof name && alphanum(*lptr); i++,lptr++)
faluco@6
  1091
            name[i]=*lptr;
faluco@6
  1092
          name[i]='\0';
faluco@6
  1093
          /* then the precision (for fixed point arithmetic) */
faluco@6
  1094
          while (*lptr<=' ' && *lptr!='\0')
faluco@6
  1095
            lptr++;
faluco@6
  1096
          if (*lptr=='(') {
faluco@6
  1097
            preproc_expr(&digits,NULL);
faluco@6
  1098
            if (digits<=0 || digits>9) {
faluco@6
  1099
              error(68);        /* invalid rational number precision */
faluco@6
  1100
              digits=0;
faluco@6
  1101
            } /* if */
faluco@6
  1102
            if (*lptr==')')
faluco@6
  1103
              lptr++;
faluco@6
  1104
          } /* if */
faluco@6
  1105
          /* add the tag (make it public) and check the values */
faluco@6
  1106
          i=pc_addtag(name);
faluco@6
  1107
          exporttag(i);
faluco@6
  1108
          if (sc_rationaltag==0 || (sc_rationaltag==i && rational_digits==(int)digits)) {
faluco@6
  1109
            sc_rationaltag=i;
faluco@6
  1110
            rational_digits=(int)digits;
faluco@6
  1111
          } else {
faluco@6
  1112
            error(69);          /* rational number format already set, can only be set once */
faluco@6
  1113
          } /* if */
faluco@6
  1114
        } else if (strcmp(str,"semicolon")==0) {
faluco@6
  1115
          cell val;
faluco@6
  1116
          preproc_expr(&val,NULL);
faluco@6
  1117
          sc_needsemicolon=(int)val;
faluco@6
  1118
        } else if (strcmp(str,"tabsize")==0) {
faluco@6
  1119
          cell val;
faluco@6
  1120
          preproc_expr(&val,NULL);
faluco@6
  1121
          sc_tabsize=(int)val;
faluco@6
  1122
        } else if (strcmp(str,"align")==0) {
faluco@6
  1123
          sc_alignnext=TRUE;
faluco@6
  1124
        } else if (strcmp(str,"unused")==0) {
faluco@6
  1125
          char name[sNAMEMAX+1];
faluco@6
  1126
          int i,comma;
faluco@6
  1127
          symbol *sym;
faluco@6
  1128
          do {
faluco@6
  1129
            /* get the name */
faluco@6
  1130
            while (*lptr<=' ' && *lptr!='\0')
faluco@6
  1131
              lptr++;
faluco@6
  1132
            for (i=0; i<sizeof name && alphanum(*lptr); i++,lptr++)
faluco@6
  1133
              name[i]=*lptr;
faluco@6
  1134
            name[i]='\0';
faluco@6
  1135
            /* get the symbol */
faluco@6
  1136
            sym=findloc(name);
faluco@6
  1137
            if (sym==NULL)
faluco@6
  1138
              sym=findglb(name,sSTATEVAR);
faluco@6
  1139
            if (sym!=NULL) {
faluco@6
  1140
              sym->usage |= uREAD;
faluco@6
  1141
              if (sym->ident==iVARIABLE || sym->ident==iREFERENCE
faluco@6
  1142
                  || sym->ident==iARRAY || sym->ident==iREFARRAY)
faluco@6
  1143
                sym->usage |= uWRITTEN;
faluco@6
  1144
            } else {
faluco@6
  1145
              error(17,name);     /* undefined symbol */
faluco@6
  1146
            } /* if */
faluco@6
  1147
            /* see if a comma follows the name */
faluco@6
  1148
            while (*lptr<=' ' && *lptr!='\0')
faluco@6
  1149
              lptr++;
faluco@6
  1150
            comma= (*lptr==',');
faluco@6
  1151
            if (comma)
faluco@6
  1152
              lptr++;
faluco@6
  1153
          } while (comma);
faluco@6
  1154
        } else {
faluco@6
  1155
          error(207);           /* unknown #pragma */
faluco@6
  1156
        } /* if */
faluco@6
  1157
      } else {
faluco@6
  1158
        error(207);             /* unknown #pragma */
faluco@6
  1159
      } /* if */
faluco@6
  1160
      check_empty(lptr);
faluco@6
  1161
    } /* if */
faluco@6
  1162
    break;
faluco@6
  1163
  case tpENDINPUT:
faluco@6
  1164
  case tpENDSCRPT:
faluco@6
  1165
    if (!SKIPPING) {
faluco@6
  1166
      check_empty(lptr);
faluco@6
  1167
      assert(inpf!=NULL);
faluco@6
  1168
      if (inpf!=inpf_org)
faluco@6
  1169
        pc_closesrc(inpf);
faluco@6
  1170
      inpf=NULL;
faluco@6
  1171
    } /* if */
faluco@6
  1172
    break;
faluco@6
  1173
#if !defined NOEMIT
faluco@6
  1174
  case tpEMIT: {
faluco@6
  1175
    /* write opcode to output file */
faluco@6
  1176
    char name[40];
faluco@6
  1177
    int i;
faluco@6
  1178
    while (*lptr<=' ' && *lptr!='\0')
faluco@6
  1179
      lptr++;
faluco@6
  1180
    for (i=0; i<40 && (isalpha(*lptr) || *lptr=='.'); i++,lptr++)
faluco@6
  1181
      name[i]=(char)tolower(*lptr);
faluco@6
  1182
    name[i]='\0';
faluco@6
  1183
    stgwrite("\t");
faluco@6
  1184
    stgwrite(name);
faluco@6
  1185
    stgwrite(" ");
faluco@6
  1186
    code_idx+=opcodes(1);
faluco@6
  1187
    /* write parameter (if any) */
faluco@6
  1188
    while (*lptr<=' ' && *lptr!='\0')
faluco@6
  1189
      lptr++;
faluco@6
  1190
    if (*lptr!='\0') {
faluco@6
  1191
      symbol *sym;
faluco@6
  1192
      tok=lex(&val,&str);
faluco@6
  1193
      switch (tok) {
faluco@6
  1194
      case tNUMBER:
faluco@6
  1195
      case tRATIONAL:
faluco@6
  1196
        outval(val,FALSE);
faluco@6
  1197
        code_idx+=opargs(1);
faluco@6
  1198
        break;
faluco@6
  1199
      case tSYMBOL:
faluco@6
  1200
        sym=findloc(str);
faluco@6
  1201
        if (sym==NULL)
faluco@6
  1202
          sym=findglb(str,sSTATEVAR);
faluco@6
  1203
        if (sym==NULL || sym->ident!=iFUNCTN && sym->ident!=iREFFUNC && (sym->usage & uDEFINE)==0) {
faluco@6
  1204
          error(17,str);        /* undefined symbol */
faluco@6
  1205
        } else {
faluco@6
  1206
          outval(sym->addr,FALSE);
faluco@6
  1207
          /* mark symbol as "used", unknown whether for read or write */
faluco@6
  1208
          markusage(sym,uREAD | uWRITTEN);
faluco@6
  1209
          code_idx+=opargs(1);
faluco@6
  1210
        } /* if */
faluco@6
  1211
        break;
faluco@6
  1212
      default: {
faluco@6
  1213
        char s2[20];
faluco@6
  1214
        extern char *sc_tokens[];/* forward declaration */
faluco@6
  1215
        if (tok<256)
faluco@6
  1216
          sprintf(s2,"%c",(char)tok);
faluco@6
  1217
        else
faluco@6
  1218
          strcpy(s2,sc_tokens[tok-tFIRST]);
faluco@6
  1219
        error(1,sc_tokens[tSYMBOL-tFIRST],s2);
faluco@6
  1220
        break;
faluco@6
  1221
      } /* case */
faluco@6
  1222
      } /* switch */
faluco@6
  1223
    } /* if */
faluco@6
  1224
    stgwrite("\n");
faluco@6
  1225
    check_empty(lptr);
faluco@6
  1226
    break;
faluco@6
  1227
  } /* case */
faluco@6
  1228
#endif
faluco@6
  1229
#if !defined NO_DEFINE
faluco@6
  1230
  case tpDEFINE: {
faluco@6
  1231
    ret=CMD_DEFINE;
faluco@6
  1232
    if (!SKIPPING) {
faluco@6
  1233
      char *pattern,*substitution;
faluco@6
  1234
      const unsigned char *start,*end;
faluco@6
  1235
      int count,prefixlen;
faluco@6
  1236
      stringpair *def;
faluco@6
  1237
      /* find the pattern to match */
faluco@6
  1238
      while (*lptr<=' ' && *lptr!='\0')
faluco@6
  1239
        lptr++;
faluco@6
  1240
      start=lptr;       /* save starting point of the match pattern */
faluco@6
  1241
      count=0;
faluco@6
  1242
      while (*lptr>' ' && *lptr!='\0') {
faluco@6
  1243
        litchar(&lptr,0); /* litchar() advances "lptr" and handles escape characters */
faluco@6
  1244
        count++;
faluco@6
  1245
      } /* while */
faluco@6
  1246
      end=lptr;
faluco@6
  1247
      /* check pattern to match */
faluco@6
  1248
      if (!alpha(*start)) {
faluco@6
  1249
        error(74);      /* pattern must start with an alphabetic character */
faluco@6
  1250
        break;
faluco@6
  1251
      } /* if */
faluco@6
  1252
      /* store matched pattern */
faluco@6
  1253
      pattern=(char*)malloc(count+1);
faluco@6
  1254
      if (pattern==NULL)
faluco@6
  1255
        error(103);     /* insufficient memory */
faluco@6
  1256
      lptr=start;
faluco@6
  1257
      count=0;
faluco@6
  1258
      while (lptr!=end) {
faluco@6
  1259
        assert(lptr<end);
faluco@6
  1260
        assert(*lptr!='\0');
faluco@6
  1261
        pattern[count++]=(char)litchar(&lptr,0);
faluco@6
  1262
      } /* while */
faluco@6
  1263
      pattern[count]='\0';
faluco@6
  1264
      /* special case, erase trailing variable, because it could match anything */
faluco@6
  1265
      if (count>=2 && isdigit(pattern[count-1]) && pattern[count-2]=='%')
faluco@6
  1266
        pattern[count-2]='\0';
faluco@6
  1267
      /* find substitution string */
faluco@6
  1268
      while (*lptr<=' ' && *lptr!='\0')
faluco@6
  1269
        lptr++;
faluco@6
  1270
      start=lptr;       /* save starting point of the match pattern */
faluco@6
  1271
      count=0;
faluco@6
  1272
      end=NULL;
faluco@6
  1273
      while (*lptr!='\0') {
faluco@6
  1274
        /* keep position of the start of trailing whitespace */
faluco@6
  1275
        if (*lptr<=' ') {
faluco@6
  1276
          if (end==NULL)
faluco@6
  1277
            end=lptr;
faluco@6
  1278
        } else {
faluco@6
  1279
          end=NULL;
faluco@6
  1280
        } /* if */
faluco@6
  1281
        count++;
faluco@6
  1282
        lptr++;
faluco@6
  1283
      } /* while */
faluco@6
  1284
      if (end==NULL)
faluco@6
  1285
        end=lptr;
faluco@6
  1286
      /* store matched substitution */
faluco@6
  1287
      substitution=(char*)malloc(count+1);  /* +1 for '\0' */
faluco@6
  1288
      if (substitution==NULL)
faluco@6
  1289
        error(103);     /* insufficient memory */
faluco@6
  1290
      lptr=start;
faluco@6
  1291
      count=0;
faluco@6
  1292
      while (lptr!=end) {
faluco@6
  1293
        assert(lptr<end);
faluco@6
  1294
        assert(*lptr!='\0');
faluco@6
  1295
        substitution[count++]=*lptr++;
faluco@6
  1296
      } /* while */
faluco@6
  1297
      substitution[count]='\0';
faluco@6
  1298
      /* check whether the definition already exists */
faluco@6
  1299
      for (prefixlen=0,start=(unsigned char*)pattern; alphanum(*start); prefixlen++,start++)
faluco@6
  1300
        /* nothing */;
faluco@6
  1301
      assert(prefixlen>0);
faluco@6
  1302
      if ((def=find_subst(pattern,prefixlen))!=NULL) {
faluco@6
  1303
        if (strcmp(def->first,pattern)!=0 || strcmp(def->second,substitution)!=0)
faluco@6
  1304
          error(201,pattern);   /* redefinition of macro (non-identical) */
faluco@6
  1305
        delete_subst(pattern,prefixlen);
faluco@6
  1306
      } /* if */
faluco@6
  1307
      /* add the pattern/substitution pair to the list */
faluco@6
  1308
      assert(strlen(pattern)>0);
faluco@6
  1309
      insert_subst(pattern,substitution,prefixlen);
faluco@6
  1310
      free(pattern);
faluco@6
  1311
      free(substitution);
faluco@6
  1312
    } /* if */
faluco@6
  1313
    break;
faluco@6
  1314
  } /* case */
faluco@6
  1315
  case tpUNDEF:
faluco@6
  1316
    if (!SKIPPING) {
faluco@6
  1317
      if (lex(&val,&str)==tSYMBOL) {
faluco@6
  1318
        ret=delete_subst(str,strlen(str));
faluco@6
  1319
        if (!ret) {
faluco@6
  1320
          /* also undefine normal constants */
faluco@6
  1321
          symbol *sym=findconst(str,NULL);
faluco@6
  1322
          if (sym!=NULL && (sym->usage & (uENUMROOT | uENUMFIELD))==0) {
faluco@6
  1323
            delete_symbol(&glbtab,sym);
faluco@6
  1324
            ret=TRUE;
faluco@6
  1325
          } /* if */
faluco@6
  1326
        } /* if */
faluco@6
  1327
        if (!ret)
faluco@6
  1328
          error(17,str);        /* undefined symbol */
faluco@6
  1329
      } else {
faluco@6
  1330
        error(20,str);          /* invalid symbol name */
faluco@6
  1331
      } /* if */
faluco@6
  1332
      check_empty(lptr);
faluco@6
  1333
    } /* if */
faluco@6
  1334
    break;
faluco@6
  1335
#endif
faluco@6
  1336
  case tpERROR:
faluco@6
  1337
    while (*lptr<=' ' && *lptr!='\0')
faluco@6
  1338
      lptr++;
faluco@6
  1339
    if (!SKIPPING)
faluco@6
  1340
      error(111,lptr);  /* user error */
faluco@6
  1341
    break;
faluco@6
  1342
  default:
faluco@6
  1343
    error(31);          /* unknown compiler directive */
faluco@6
  1344
    ret=SKIPPING ? CMD_CONDFALSE : CMD_NONE;  /* process as normal line */
faluco@6
  1345
  } /* switch */
faluco@6
  1346
  return ret;
faluco@6
  1347
}
faluco@6
  1348
faluco@6
  1349
#if !defined NO_DEFINE
faluco@6
  1350
static int is_startstring(const unsigned char *string)
faluco@6
  1351
{
faluco@6
  1352
  if (*string=='\"' || *string=='\'')
faluco@6
  1353
    return TRUE;                        /* "..." */
faluco@6
  1354
faluco@6
  1355
  if (*string=='!') {
faluco@6
  1356
    string++;
faluco@6
  1357
    if (*string=='\"' || *string=='\'')
faluco@6
  1358
      return TRUE;                      /* !"..." */
faluco@6
  1359
    if (*string==sc_ctrlchar) {
faluco@6
  1360
      string++;
faluco@6
  1361
      if (*string=='\"' || *string=='\'')
faluco@6
  1362
        return TRUE;                    /* !\"..." */
faluco@6
  1363
    } /* if */
faluco@6
  1364
  } else if (*string==sc_ctrlchar) {
faluco@6
  1365
    string++;
faluco@6
  1366
    if (*string=='\"' || *string=='\'')
faluco@6
  1367
      return TRUE;                      /* \"..." */
faluco@6
  1368
    if (*string=='!') {
faluco@6
  1369
      string++;
faluco@6
  1370
      if (*string=='\"' || *string=='\'')
faluco@6
  1371
        return TRUE;                    /* \!"..." */
faluco@6
  1372
    } /* if */
faluco@6
  1373
  } /* if */
faluco@6
  1374
faluco@6
  1375
  return FALSE;
faluco@6
  1376
}
faluco@6
  1377
faluco@6
  1378
static const unsigned char *skipstring(const unsigned char *string)
faluco@6
  1379
{
faluco@6
  1380
  char endquote;
faluco@6
  1381
  int flags=0;
faluco@6
  1382
faluco@6
  1383
  while (*string=='!' || *string==sc_ctrlchar) {
faluco@6
  1384
    if (*string==sc_ctrlchar)
faluco@6
  1385
      flags=RAWMODE;
faluco@6
  1386
    string++;
faluco@6
  1387
  } /* while */
faluco@6
  1388
faluco@6
  1389
  endquote=*string;
faluco@6
  1390
  assert(endquote=='"' || endquote=='\'');
faluco@6
  1391
  string++;             /* skip open quote */
faluco@6
  1392
  while (*string!=endquote && *string!='\0')
faluco@6
  1393
    litchar(&string,flags);
faluco@6
  1394
  return string;
faluco@6
  1395
}
faluco@6
  1396
faluco@6
  1397
static const unsigned char *skippgroup(const unsigned char *string)
faluco@6
  1398
{
faluco@6
  1399
  int nest=0;
faluco@6
  1400
  char open=*string;
faluco@6
  1401
  char close;
faluco@6
  1402
faluco@6
  1403
  switch (open) {
faluco@6
  1404
  case '(':
faluco@6
  1405
    close=')';
faluco@6
  1406
    break;
faluco@6
  1407
  case '{':
faluco@6
  1408
    close='}';
faluco@6
  1409
    break;
faluco@6
  1410
  case '[':
faluco@6
  1411
    close=']';
faluco@6
  1412
    break;
faluco@6
  1413
  case '<':
faluco@6
  1414
    close='>';
faluco@6
  1415
    break;
faluco@6
  1416
  default:
faluco@6
  1417
    assert(0);
faluco@6
  1418
	close='\0';         /* only to avoid a compiler warning */
faluco@6
  1419
  }/* switch */
faluco@6
  1420
faluco@6
  1421
  string++;
faluco@6
  1422
  while (*string!=close || nest>0) {
faluco@6
  1423
    if (*string==open)
faluco@6
  1424
      nest++;
faluco@6
  1425
    else if (*string==close)
faluco@6
  1426
      nest--;
faluco@6
  1427
    else if (is_startstring(string))
faluco@6
  1428
      string=skipstring(string);
faluco@6
  1429
    if (*string=='\0')
faluco@6
  1430
      break;
faluco@6
  1431
    string++;
faluco@6
  1432
  } /* while */
faluco@6
  1433
  return string;
faluco@6
  1434
}
faluco@6
  1435
faluco@6
  1436
static char *strdel(char *str,size_t len)
faluco@6
  1437
{
faluco@6
  1438
  size_t length=strlen(str);
faluco@6
  1439
  if (len>length)
faluco@6
  1440
    len=length;
faluco@6
  1441
  memmove(str, str+len, length-len+1);  /* include EOS byte */
faluco@6
  1442
  return str;
faluco@6
  1443
}
faluco@6
  1444
faluco@6
  1445
static char *strins(char *dest,char *src,size_t srclen)
faluco@6
  1446
{
faluco@6
  1447
  size_t destlen=strlen(dest);
faluco@6
  1448
  assert(srclen<=strlen(src));
faluco@6
  1449
  memmove(dest+srclen, dest, destlen+1);/* include EOS byte */
faluco@6
  1450
  memcpy(dest, src, srclen);
faluco@6
  1451
  return dest;
faluco@6
  1452
}
faluco@6
  1453
faluco@6
  1454
static int substpattern(unsigned char *line,size_t buffersize,char *pattern,char *substitution)
faluco@6
  1455
{
faluco@6
  1456
  int prefixlen;
faluco@6
  1457
  const unsigned char *p,*s,*e;
faluco@6
  1458
  unsigned char *args[10];
faluco@6
  1459
  int match,arg,len;
faluco@6
  1460
faluco@6
  1461
  memset(args,0,sizeof args);
faluco@6
  1462
faluco@6
  1463
  /* check the length of the prefix */
faluco@6
  1464
  for (prefixlen=0,s=(unsigned char*)pattern; alphanum(*s); prefixlen++,s++)
faluco@6
  1465
    /* nothing */;
faluco@6
  1466
  assert(prefixlen>0);
faluco@6
  1467
  assert(strncmp((char*)line,pattern,prefixlen)==0);
faluco@6
  1468
faluco@6
  1469
  /* pattern prefix matches; match the rest of the pattern, gather
faluco@6
  1470
   * the parameters
faluco@6
  1471
   */
faluco@6
  1472
  s=line+prefixlen;
faluco@6
  1473
  p=(unsigned char*)pattern+prefixlen;
faluco@6
  1474
  match=TRUE;         /* so far, pattern matches */
faluco@6
  1475
  while (match && *s!='\0' && *p!='\0') {
faluco@6
  1476
    if (*p=='%') {
faluco@6
  1477
      p++;            /* skip '%' */
faluco@6
  1478
      if (isdigit(*p)) {
faluco@6
  1479
        arg=*p-'0';
faluco@6
  1480
        assert(arg>=0 && arg<=9);
faluco@6
  1481
        p++;          /* skip parameter id */
faluco@6
  1482
        assert(*p!='\0');
faluco@6
  1483
        /* match the source string up to the character after the digit
faluco@6
  1484
         * (skipping strings in the process
faluco@6
  1485
         */
faluco@6
  1486
        e=s;
faluco@6
  1487
        while (*e!=*p && *e!='\0' && *e!='\n') {
faluco@6
  1488
          if (is_startstring(e))              /* skip strings */
faluco@6
  1489
            e=skipstring(e);
faluco@6
  1490
          else if (strchr("({[",*e)!=NULL)    /* skip parenthized groups */
faluco@6
  1491
            e=skippgroup(e);
faluco@6
  1492
          if (*e!='\0')
faluco@6
  1493
            e++;      /* skip non-alphapetic character (or closing quote of
faluco@6
  1494
                       * a string, or the closing paranthese of a group) */
faluco@6
  1495
        } /* while */
faluco@6
  1496
        /* store the parameter (overrule any earlier) */
faluco@6
  1497
        if (args[arg]!=NULL)
faluco@6
  1498
          free(args[arg]);
faluco@6
  1499
        len=(int)(e-s);
faluco@6
  1500
        args[arg]=(unsigned char*)malloc(len+1);
faluco@6
  1501
        if (args[arg]==NULL)
faluco@6
  1502
          error(103); /* insufficient memory */
faluco@6
  1503
        strlcpy((char*)args[arg],(char*)s,len+1);
faluco@6
  1504
        /* character behind the pattern was matched too */
faluco@6
  1505
        if (*e==*p) {
faluco@6
  1506
          s=e+1;
faluco@6
  1507
        } else if (*e=='\n' && *p==';' && *(p+1)=='\0' && !sc_needsemicolon) {
faluco@6
  1508
          s=e;    /* allow a trailing ; in the pattern match to end of line */
faluco@6
  1509
        } else {
faluco@6
  1510
          assert(*e=='\0' || *e=='\n');
faluco@6
  1511
          match=FALSE;
faluco@6
  1512
          s=e;
faluco@6
  1513
        } /* if */
faluco@6
  1514
        p++;
faluco@6
  1515
      } else {
faluco@6
  1516
        match=FALSE;
faluco@6
  1517
      } /* if */
faluco@6
  1518
    } else if (*p==';' && *(p+1)=='\0' && !sc_needsemicolon) {
faluco@6
  1519
      /* source may be ';' or end of the line */
faluco@6
  1520
      while (*s<=' ' && *s!='\0')
faluco@6
  1521
        s++;          /* skip white space */
faluco@6
  1522
      if (*s!=';' && *s!='\0')
faluco@6
  1523
        match=FALSE;
faluco@6
  1524
      p++;            /* skip the semicolon in the pattern */
faluco@6
  1525
    } else {
faluco@6
  1526
      cell ch;
faluco@6
  1527
      /* skip whitespace between two non-alphanumeric characters, except
faluco@6
  1528
       * for two identical symbols
faluco@6
  1529
       */
faluco@6
  1530
      assert((char*)p>pattern);
faluco@6
  1531
      if (!alphanum(*p) && *(p-1)!=*p)
faluco@6
  1532
        while (*s<=' ' && *s!='\0')
faluco@6
  1533
          s++;                  /* skip white space */
faluco@6
  1534
      ch=litchar(&p,0);         /* this increments "p" */
faluco@6
  1535
      if (*s!=ch)
faluco@6
  1536
        match=FALSE;
faluco@6
  1537
      else
faluco@6
  1538
        s++;                    /* this character matches */
faluco@6
  1539
    } /* if */
faluco@6
  1540
  } /* while */
faluco@6
  1541
faluco@6
  1542
  if (match && *p=='\0') {
faluco@6
  1543
    /* if the last character to match is an alphanumeric character, the
faluco@6
  1544
     * current character in the source may not be alphanumeric
faluco@6
  1545
     */
faluco@6
  1546
    assert(p>(unsigned char*)pattern);
faluco@6
  1547
    if (alphanum(*(p-1)) && alphanum(*s))
faluco@6
  1548
      match=FALSE;
faluco@6
  1549
  } /* if */
faluco@6
  1550
faluco@6
  1551
  if (match) {
faluco@6
  1552
    /* calculate the length of the substituted string */
faluco@6
  1553
    for (e=(unsigned char*)substitution,len=0; *e!='\0'; e++) {
faluco@6
  1554
      if (*e=='%' && isdigit(*(e+1))) {
faluco@6
  1555
        arg=*(e+1)-'0';
faluco@6
  1556
        assert(arg>=0 && arg<=9);
faluco@6
  1557
        if (args[arg]!=NULL)
faluco@6
  1558
          len+=strlen((char*)args[arg]);
faluco@6
  1559
        else
faluco@6
  1560
          len+=2;     /* copy '%' plus digit */
faluco@6
  1561
        e++;          /* skip %, digit is skipped later */
faluco@6
  1562
      } else {
faluco@6
  1563
        len++;
faluco@6
  1564
      } /* if */
faluco@6
  1565
    } /* for */
faluco@6
  1566
    /* check length of the string after substitution */
faluco@6
  1567
    if (strlen((char*)line) + len - (int)(s-line) > buffersize) {
faluco@6
  1568
      error(75);      /* line too long */
faluco@6
  1569
    } else {
faluco@6
  1570
      /* substitute pattern */
faluco@6
  1571
      strdel((char*)line,(int)(s-line));
faluco@6
  1572
      for (e=(unsigned char*)substitution,s=line; *e!='\0'; e++) {
faluco@6
  1573
        if (*e=='%' && isdigit(*(e+1))) {
faluco@6
  1574
          arg=*(e+1)-'0';
faluco@6
  1575
          assert(arg>=0 && arg<=9);
faluco@6
  1576
          if (args[arg]!=NULL) {
faluco@6
  1577
            strins((char*)s,(char*)args[arg],strlen((char*)args[arg]));
faluco@6
  1578
            s+=strlen((char*)args[arg]);
faluco@6
  1579
          } else {
faluco@6
  1580
            error(236); /* parameter does not exist, incorrect #define pattern */
faluco@6
  1581
            strins((char*)s,(char*)e,2);
faluco@6
  1582
            s+=2;
faluco@6
  1583
          } /* if */
faluco@6
  1584
          e++;          /* skip %, digit is skipped later */
faluco@6
  1585
        } else {
faluco@6
  1586
          strins((char*)s,(char*)e,1);
faluco@6
  1587
          s++;
faluco@6
  1588
        } /* if */
faluco@6
  1589
      } /* for */
faluco@6
  1590
    } /* if */
faluco@6
  1591
  } /* if */
faluco@6
  1592
faluco@6
  1593
  for (arg=0; arg<10; arg++)
faluco@6
  1594
    if (args[arg]!=NULL)
faluco@6
  1595
      free(args[arg]);
faluco@6
  1596
faluco@6
  1597
  return match;
faluco@6
  1598
}
faluco@6
  1599
faluco@6
  1600
static void substallpatterns(unsigned char *line,int buffersize)
faluco@6
  1601
{
faluco@6
  1602
  unsigned char *start, *end;
faluco@6
  1603
  int prefixlen;
faluco@6
  1604
  stringpair *subst;
faluco@6
  1605
faluco@6
  1606
  start=line;
faluco@6
  1607
  while (*start!='\0') {
faluco@6
  1608
    /* find the start of a prefix (skip all non-alphabetic characters),
faluco@6
  1609
     * also skip strings
faluco@6
  1610
     */
faluco@6
  1611
    while (!alpha(*start) && *start!='\0') {
faluco@6
  1612
      /* skip strings */
faluco@6
  1613
      if (is_startstring(start)) {
faluco@6
  1614
        start=(unsigned char *)skipstring(start);
faluco@6
  1615
        if (*start=='\0')
faluco@6
  1616
          break;        /* abort loop on error */
faluco@6
  1617
      } /* if */
faluco@6
  1618
      start++;          /* skip non-alphapetic character (or closing quote of a string) */
faluco@6
  1619
    } /* while */
faluco@6
  1620
    if (*start=='\0')
faluco@6
  1621
      break;            /* abort loop on error */
faluco@6
  1622
    /* if matching the operator "defined", skip it plus the symbol behind it */
faluco@6
  1623
    if (strncmp((char*)start,"defined",7)==0 && *(start+7)<=' ') {
faluco@6
  1624
      start+=7;         /* skip "defined" */
faluco@6
  1625
      /* skip white space & parantheses */
faluco@6
  1626
      while (*start<=' ' && *start!='\0' || *start=='(')
faluco@6
  1627
        start++;
faluco@6
  1628
      /* skip the symbol behind it */
faluco@6
  1629
      while (alphanum(*start))
faluco@6
  1630
        start++;
faluco@6
  1631
      /* drop back into the main loop */
faluco@6
  1632
      continue;
faluco@6
  1633
    } /* if */
faluco@6
  1634
    /* get the prefix (length), look for a matching definition */
faluco@6
  1635
    prefixlen=0;
faluco@6
  1636
    end=start;
faluco@6
  1637
    while (alphanum(*end)) {
faluco@6
  1638
      prefixlen++;
faluco@6
  1639
      end++;
faluco@6
  1640
    } /* while */
faluco@6
  1641
    assert(prefixlen>0);
faluco@6
  1642
    subst=find_subst((char*)start,prefixlen);
faluco@6
  1643
    if (subst!=NULL) {
faluco@6
  1644
      /* properly match the pattern and substitute */
faluco@6
  1645
      if (!substpattern(start,buffersize-(int)(start-line),subst->first,subst->second))
faluco@6
  1646
        start=end;      /* match failed, skip this prefix */
faluco@6
  1647
      /* match succeeded: do not update "start", because the substitution text
faluco@6
  1648
       * may be matched by other macros
faluco@6
  1649
       */
faluco@6
  1650
    } else {
faluco@6
  1651
      start=end;        /* no macro with this prefix, skip this prefix */
faluco@6
  1652
    } /* if */
faluco@6
  1653
  } /* while */
faluco@6
  1654
}
faluco@6
  1655
#endif
faluco@6
  1656
faluco@6
  1657
/*  preprocess
faluco@6
  1658
 *
faluco@6
  1659
 *  Reads a line by readline() into "pline" and performs basic preprocessing:
faluco@6
  1660
 *  deleting comments, skipping lines with false "#if.." code and recognizing
faluco@6
  1661
 *  other compiler directives. There is an indirect recursion: lex() calls
faluco@6
  1662
 *  preprocess() if a new line must be read, preprocess() calls command(),
faluco@6
  1663
 *  which at his turn calls lex() to identify the token.
faluco@6
  1664
 *
faluco@6
  1665
 *  Global references: lptr     (altered)
faluco@6
  1666
 *                     pline    (altered)
faluco@6
  1667
 *                     freading (referred to only)
faluco@6
  1668
 */
faluco@6
  1669
SC_FUNC void preprocess(void)
faluco@6
  1670
{
faluco@6
  1671
  int iscommand;
faluco@6
  1672
faluco@6
  1673
  if (!freading)
faluco@6
  1674
    return;
faluco@6
  1675
  do {
faluco@6
  1676
    readline(pline);
faluco@6
  1677
    stripcom(pline);    /* ??? no need for this when reading back from list file (in the second pass) */
faluco@6
  1678
    lptr=pline;         /* set "line pointer" to start of the parsing buffer */
faluco@6
  1679
    iscommand=command();
faluco@6
  1680
    if (iscommand!=CMD_NONE)
faluco@6
  1681
      errorset(sRESET,0); /* reset error flag ("panic mode") on empty line or directive */
faluco@6
  1682
    #if !defined NO_DEFINE
faluco@6
  1683
      if (iscommand==CMD_NONE) {
faluco@6
  1684
        assert(lptr!=term_expr);
faluco@6
  1685
        substallpatterns(pline,sLINEMAX);
faluco@6
  1686
        lptr=pline;       /* reset "line pointer" to start of the parsing buffer */
faluco@6
  1687
      } /* if */
faluco@6
  1688
    #endif
faluco@6
  1689
    if (sc_status==statFIRST && sc_listing && freading
faluco@6
  1690
        && (iscommand==CMD_NONE || iscommand==CMD_EMPTYLINE || iscommand==CMD_DIRECTIVE))
faluco@6
  1691
    {
faluco@6
  1692
      listline++;
faluco@6
  1693
      if (fline!=listline) {
faluco@6
  1694
        listline=fline;
faluco@6
  1695
        setlinedirect(fline);
faluco@6
  1696
      } /* if */
faluco@6
  1697
      if (iscommand==CMD_EMPTYLINE)
faluco@6
  1698
        pc_writeasm(outf,"\n");
faluco@6
  1699
      else
faluco@6
  1700
        pc_writeasm(outf,(char*)pline);
faluco@6
  1701
    } /* if */
faluco@6
  1702
  } while (iscommand!=CMD_NONE && iscommand!=CMD_TERM && freading); /* enddo */
faluco@6
  1703
}
faluco@6
  1704
faluco@6
  1705
static const unsigned char *unpackedstring(const unsigned char *lptr,int flags)
faluco@6
  1706
{
faluco@6
  1707
  while (*lptr!='\"' && *lptr!='\0') {
faluco@6
  1708
    if (*lptr=='\a') {          /* ignore '\a' (which was inserted at a line concatenation) */
faluco@6
  1709
      lptr++;
faluco@6
  1710
      continue;
faluco@6
  1711
    } /* if */
faluco@6
  1712
    litadd(litchar(&lptr,flags | UTF8MODE));  /* litchar() alters "lptr" */
faluco@6
  1713
  } /* while */
faluco@6
  1714
  litadd(0);                    /* terminate string */
faluco@6
  1715
  return lptr;
faluco@6
  1716
}
faluco@6
  1717
faluco@6
  1718
static const unsigned char *packedstring(const unsigned char *lptr,int flags)
faluco@6
  1719
{
faluco@6
  1720
  int i;
faluco@6
  1721
  ucell val,c;
faluco@6
  1722
faluco@6
  1723
  i=sizeof(ucell)-(sCHARBITS/8); /* start at most significant byte */
faluco@6
  1724
  val=0;
faluco@6
  1725
  while (*lptr!='\"' && *lptr!='\0') {
faluco@6
  1726
    if (*lptr=='\a') {          /* ignore '\a' (which was inserted at a line concatenation) */
faluco@6
  1727
      lptr++;
faluco@6
  1728
      continue;
faluco@6
  1729
    } /* if */
faluco@6
  1730
    c=litchar(&lptr,flags);     /* litchar() alters "lptr" */
faluco@6
  1731
    if (c>=(ucell)(1 << sCHARBITS))
faluco@6
  1732
      error(43);                /* character constant exceeds range */
faluco@6
  1733
    val |= (c << 8*i);
faluco@6
  1734
    if (i==0) {
faluco@6
  1735
      litadd(val);
faluco@6
  1736
      val=0;
faluco@6
  1737
    } /* if */
faluco@6
  1738
    i=(i+sizeof(ucell)-(sCHARBITS/8)) % sizeof(ucell);
faluco@6
  1739
  } /* if */
faluco@6
  1740
  /* save last code; make sure there is at least one terminating zero character */
faluco@6
  1741
  if (i!=(int)(sizeof(ucell)-(sCHARBITS/8)))
faluco@6
  1742
    litadd(val);        /* at least one zero character in "val" */
faluco@6
  1743
  else
faluco@6
  1744
    litadd(0);          /* add full cell of zeros */
faluco@6
  1745
  return lptr;
faluco@6
  1746
}
faluco@6
  1747
faluco@6
  1748
/*  lex(lexvalue,lexsym)        Lexical Analysis
faluco@6
  1749
 *
faluco@6
  1750
 *  lex() first deletes leading white space, then checks for multi-character
faluco@6
  1751
 *  operators, keywords (including most compiler directives), numbers,
faluco@6
  1752
 *  labels, symbols and literals (literal characters are converted to a number
faluco@6
  1753
 *  and are returned as such). If every check fails, the line must contain
faluco@6
  1754
 *  a single-character operator. So, lex() returns this character. In the other
faluco@6
  1755
 *  case (something did match), lex() returns the number of the token. All
faluco@6
  1756
 *  these tokens have been assigned numbers above 255.
faluco@6
  1757
 *
faluco@6
  1758
 *  Some tokens have "attributes":
faluco@6
  1759
 *     tNUMBER        the value of the number is return in "lexvalue".
faluco@6
  1760
 *     tRATIONAL      the value is in IEEE 754 encoding or in fixed point
faluco@6
  1761
 *                    encoding in "lexvalue".
faluco@6
  1762
 *     tSYMBOL        the first sNAMEMAX characters of the symbol are
faluco@6
  1763
 *                    stored in a buffer, a pointer to this buffer is
faluco@6
  1764
 *                    returned in "lexsym".
faluco@6
  1765
 *     tLABEL         the first sNAMEMAX characters of the label are
faluco@6
  1766
 *                    stored in a buffer, a pointer to this buffer is
faluco@6
  1767
 *                    returned in "lexsym".
faluco@6
  1768
 *     tSTRING        the string is stored in the literal pool, the index
faluco@6
  1769
 *                    in the literal pool to this string is stored in
faluco@6
  1770
 *                    "lexvalue".
faluco@6
  1771
 *
faluco@6
  1772
 *  lex() stores all information (the token found and possibly its attribute)
faluco@6
  1773
 *  in global variables. This allows a token to be examined twice. If "_pushed"
faluco@6
  1774
 *  is true, this information is returned.
faluco@6
  1775
 *
faluco@6
  1776
 *  Global references: lptr          (altered)
faluco@6
  1777
 *                     fline         (referred to only)
faluco@6
  1778
 *                     litidx        (referred to only)
faluco@6
  1779
 *                     _lextok, _lexval, _lexstr
faluco@6
  1780
 *                     _pushed
faluco@6
  1781
 */
faluco@6
  1782
faluco@6
  1783
static int _pushed;
faluco@6
  1784
static int _lextok;
faluco@6
  1785
static cell _lexval;
faluco@6
  1786
static char _lexstr[sLINEMAX+1];
faluco@6
  1787
static int _lexnewline;
faluco@6
  1788
faluco@6
  1789
SC_FUNC void lexinit(void)
faluco@6
  1790
{
faluco@6
  1791
  stkidx=0;             /* index for pushstk() and popstk() */
faluco@6
  1792
  iflevel=0;            /* preprocessor: nesting of "#if" is currently 0 */
faluco@6
  1793
  skiplevel=0;          /* preprocessor: not currently skipping */
faluco@6
  1794
  icomment=0;           /* currently not in a multiline comment */
faluco@6
  1795
  _pushed=FALSE;        /* no token pushed back into lex */
faluco@6
  1796
  _lexnewline=FALSE;
faluco@6
  1797
}
faluco@6
  1798
faluco@6
  1799
char *sc_tokens[] = {
faluco@6
  1800
         "*=", "/=", "%=", "+=", "-=", "<<=", ">>>=", ">>=", "&=", "^=", "|=",
faluco@6
  1801
         "||", "&&", "==", "!=", "<=", ">=", "<<", ">>>", ">>", "++", "--",
faluco@6
  1802
         "...", "..", "::",
faluco@6
  1803
         "assert", "break", "case", "char", "const", "continue", "default",
faluco@6
  1804
         "defined", "do", "else", "enum", "exit", "for", "forward", "goto",
faluco@6
  1805
         "if", "native", "new", "decl", "operator", "public", "return", "sizeof",
faluco@6
  1806
         "sleep", "state", "static", "stock", "switch", "tagof", "while",
faluco@6
  1807
         "#assert", "#define", "#else", "#elseif", "#emit", "#endif", "#endinput",
faluco@6
  1808
         "#endscript", "#error", "#file", "#if", "#include", "#line", "#pragma",
faluco@6
  1809
         "#tryinclude", "#undef",
faluco@6
  1810
         ";", ";", "-integer value-", "-rational value-", "-identifier-",
faluco@6
  1811
         "-label-", "-string-"
faluco@6
  1812
       };
faluco@6
  1813
faluco@6
  1814
SC_FUNC int lex(cell *lexvalue,char **lexsym)
faluco@6
  1815
{
faluco@6
  1816
  int i,toolong,newline,stringflags;
faluco@6
  1817
  char **tokptr;
faluco@6
  1818
  const unsigned char *starttoken;
faluco@6
  1819
faluco@6
  1820
  if (_pushed) {
faluco@6
  1821
    _pushed=FALSE;      /* reset "_pushed" flag */
faluco@6
  1822
    *lexvalue=_lexval;
faluco@6
  1823
    *lexsym=_lexstr;
faluco@6
  1824
    return _lextok;
faluco@6
  1825
  } /* if */
faluco@6
  1826
faluco@6
  1827
  _lextok=0;            /* preset all values */
faluco@6
  1828
  _lexval=0;
faluco@6
  1829
  _lexstr[0]='\0';
faluco@6
  1830
  *lexvalue=_lexval;
faluco@6
  1831
  *lexsym=_lexstr;
faluco@6
  1832
  _lexnewline=FALSE;
faluco@6
  1833
  if (!freading)
faluco@6
  1834
    return 0;
faluco@6
  1835
faluco@6
  1836
  newline= (lptr==pline);       /* does lptr point to start of line buffer */
faluco@6
  1837
  while (*lptr<=' ') {          /* delete leading white space */
faluco@6
  1838
    if (*lptr=='\0') {
faluco@6
  1839
      preprocess();             /* preprocess resets "lptr" */
faluco@6
  1840
      if (!freading)
faluco@6
  1841
        return 0;
faluco@6
  1842
      if (lptr==term_expr)      /* special sequence to terminate a pending expression */
faluco@6
  1843
        return (_lextok=tENDEXPR);
faluco@6
  1844
      _lexnewline=TRUE;         /* set this after preprocess(), because
faluco@6
  1845
                                 * preprocess() calls lex() recursively */
faluco@6
  1846
      newline=TRUE;
faluco@6
  1847
    } else {
faluco@6
  1848
      lptr+=1;
faluco@6
  1849
    } /* if */
faluco@6
  1850
  } /* while */
faluco@6
  1851
  if (newline) {
faluco@6
  1852
    stmtindent=0;
faluco@6
  1853
    for (i=0; i<(int)(lptr-pline); i++)
faluco@6
  1854
      if (pline[i]=='\t' && sc_tabsize>0)
faluco@6
  1855
        stmtindent += (int)(sc_tabsize - (stmtindent+sc_tabsize) % sc_tabsize);
faluco@6
  1856
      else
faluco@6
  1857
        stmtindent++;
faluco@6
  1858
  } /* if */
faluco@6
  1859
faluco@6
  1860
  i=tFIRST;
faluco@6
  1861
  tokptr=sc_tokens;
faluco@6
  1862
  while (i<=tMIDDLE) {  /* match multi-character operators */
faluco@6
  1863
    if (*lptr==**tokptr && match(*tokptr,FALSE)) {
faluco@6
  1864
      _lextok=i;
faluco@6
  1865
      if (pc_docexpr)   /* optionally concatenate to documentation string */
faluco@6
  1866
        insert_autolist(*tokptr);
faluco@6
  1867
      return _lextok;
faluco@6
  1868
    } /* if */
faluco@6
  1869
    i+=1;
faluco@6
  1870
    tokptr+=1;
faluco@6
  1871
  } /* while */
faluco@6
  1872
  while (i<=tLAST) {    /* match reserved words and compiler directives */
faluco@6
  1873
    if (*lptr==**tokptr && match(*tokptr,TRUE)) {
faluco@6
  1874
      _lextok=i;
faluco@6
  1875
      errorset(sRESET,0); /* reset error flag (clear the "panic mode")*/
faluco@6
  1876
      if (pc_docexpr)   /* optionally concatenate to documentation string */
faluco@6
  1877
        insert_autolist(*tokptr);
faluco@6
  1878
      return _lextok;
faluco@6
  1879
    } /* if */
faluco@6
  1880
    i+=1;
faluco@6
  1881
    tokptr+=1;
faluco@6
  1882
  } /* while */
faluco@6
  1883
faluco@6
  1884
  starttoken=lptr;      /* save start pointer (for concatenating to documentation string) */
faluco@6
  1885
  if ((i=number(&_lexval,lptr))!=0) {   /* number */
faluco@6
  1886
    _lextok=tNUMBER;
faluco@6
  1887
    *lexvalue=_lexval;
faluco@6
  1888
    lptr+=i;
faluco@6
  1889
  } else if ((i=ftoi(&_lexval,lptr))!=0) {
faluco@6
  1890
    _lextok=tRATIONAL;
faluco@6
  1891
    *lexvalue=_lexval;
faluco@6
  1892
    lptr+=i;
faluco@6
  1893
  } else if (alpha(*lptr)) {            /* symbol or label */
faluco@6
  1894
    /*  Note: only sNAMEMAX characters are significant. The compiler
faluco@6
  1895
     *        generates a warning if a symbol exceeds this length.
faluco@6
  1896
     */
faluco@6
  1897
    _lextok=tSYMBOL;
faluco@6
  1898
    i=0;
faluco@6
  1899
    toolong=0;
faluco@6
  1900
    while (alphanum(*lptr)){
faluco@6
  1901
      _lexstr[i]=*lptr;
faluco@6
  1902
      lptr+=1;
faluco@6
  1903
      if (i<sNAMEMAX)
faluco@6
  1904
        i+=1;
faluco@6
  1905
      else
faluco@6
  1906
        toolong=1;
faluco@6
  1907
    } /* while */
faluco@6
  1908
    _lexstr[i]='\0';
faluco@6
  1909
    if (toolong)
faluco@6
  1910
      error(200,_lexstr,sNAMEMAX);  /* symbol too long, truncated to sNAMEMAX chars */
faluco@6
  1911
    if (_lexstr[0]==PUBLIC_CHAR && _lexstr[1]=='\0') {
faluco@6
  1912
      _lextok=PUBLIC_CHAR;  /* '@' all alone is not a symbol, it is an operator */
faluco@6
  1913
    } else if (_lexstr[0]=='_' && _lexstr[1]=='\0') {
faluco@6
  1914
      _lextok='_';      /* '_' by itself is not a symbol, it is a placeholder */
faluco@6
  1915
    } /* if */
faluco@6
  1916
    if (*lptr==':' && *(lptr+1)!=':' && _lextok!=PUBLIC_CHAR) {
faluco@6
  1917
      if (sc_allowtags) {
faluco@6
  1918
        _lextok=tLABEL; /* it wasn't a normal symbol, it was a label/tagname */
faluco@6
  1919
        lptr+=1;        /* skip colon */
faluco@6
  1920
      } else if (find_constval(&tagname_tab,_lexstr,0)!=NULL) {
faluco@6
  1921
        /* this looks like a tag override (because a tag with this name
faluco@6
  1922
         * exists), but tags are not allowed right now, so it is probably an
faluco@6
  1923
         * error
faluco@6
  1924
         */
faluco@6
  1925
        error(220);
faluco@6
  1926
      } /* if */
faluco@6
  1927
    } /* if */
faluco@6
  1928
  } else if (*lptr=='\"' || *lptr==sc_ctrlchar && *(lptr+1)=='\"')
faluco@6
  1929
  {                                     /* unpacked string literal */
faluco@6
  1930
    _lextok=tSTRING;
faluco@6
  1931
    stringflags= (*lptr==sc_ctrlchar) ? RAWMODE : 0;
faluco@6
  1932
    *lexvalue=_lexval=litidx;
faluco@6
  1933
    lptr+=1;            /* skip double quote */
faluco@6
  1934
    if ((stringflags & RAWMODE)!=0)
faluco@6
  1935
      lptr+=1;          /* skip "escape" character too */
faluco@6
  1936
    lptr=sc_packstr ? packedstring(lptr,stringflags) : unpackedstring(lptr,stringflags);
faluco@6
  1937
    if (*lptr=='\"')
faluco@6
  1938
      lptr+=1;          /* skip final quote */
faluco@6
  1939
    else
faluco@6
  1940
      error(37);        /* invalid (non-terminated) string */
faluco@6
  1941
  } else if (*lptr=='!' && *(lptr+1)=='\"'
faluco@6
  1942
             || *lptr=='!' && *(lptr+1)==sc_ctrlchar && *(lptr+2)=='\"'
faluco@6
  1943
             || *lptr==sc_ctrlchar && *(lptr+1)=='!' && *(lptr+2)=='\"')
faluco@6
  1944
  {                                     /* packed string literal */
faluco@6
  1945
    _lextok=tSTRING;
faluco@6
  1946
    stringflags= (*lptr==sc_ctrlchar || *(lptr+1)==sc_ctrlchar) ? RAWMODE : 0;
faluco@6
  1947
    *lexvalue=_lexval=litidx;
faluco@6
  1948
    lptr+=2;            /* skip exclamation point and double quote */
faluco@6
  1949
    if ((stringflags & RAWMODE)!=0)
faluco@6
  1950
      lptr+=1;          /* skip "escape" character too */
faluco@6
  1951
    lptr=sc_packstr ? unpackedstring(lptr,stringflags) : packedstring(lptr,stringflags);
faluco@6
  1952
    if (*lptr=='\"')
faluco@6
  1953
      lptr+=1;          /* skip final quote */
faluco@6
  1954
    else
faluco@6
  1955
      error(37);        /* invalid (non-terminated) string */
faluco@6
  1956
  } else if (*lptr=='\'') {             /* character literal */
faluco@6
  1957
    lptr+=1;            /* skip quote */
faluco@6
  1958
    _lextok=tNUMBER;
faluco@6
  1959
    *lexvalue=_lexval=litchar(&lptr,UTF8MODE);
faluco@6
  1960
    if (*lptr=='\'')
faluco@6
  1961
      lptr+=1;          /* skip final quote */
faluco@6
  1962
    else
faluco@6
  1963
      error(27);        /* invalid character constant (must be one character) */
faluco@6
  1964
  } else if (*lptr==';') {      /* semicolumn resets "error" flag */
faluco@6
  1965
    _lextok=';';
faluco@6
  1966
    lptr+=1;
faluco@6
  1967
    errorset(sRESET,0); /* reset error flag (clear the "panic mode")*/
faluco@6
  1968
  } else {
faluco@6
  1969
    _lextok=*lptr;      /* if every match fails, return the character */
faluco@6
  1970
    lptr+=1;            /* increase the "lptr" pointer */
faluco@6
  1971
  } /* if */
faluco@6
  1972
faluco@6
  1973
  if (pc_docexpr) {     /* optionally concatenate to documentation string */
faluco@6
  1974
    char *docstr=(char*)malloc(((int)(lptr-starttoken)+1)*sizeof(char));
faluco@6
  1975
    if (docstr!=NULL) {
faluco@6
  1976
      strlcpy(docstr,(char*)starttoken,(int)(lptr-starttoken)+1);
faluco@6
  1977
      insert_autolist(docstr);
faluco@6
  1978
      free(docstr);
faluco@6
  1979
    } /* if */
faluco@6
  1980
  } /* if */
faluco@6
  1981
  return _lextok;
faluco@6
  1982
}
faluco@6
  1983
faluco@6
  1984
/*  lexpush
faluco@6
  1985
 *
faluco@6
  1986
 *  Pushes a token back, so the next call to lex() will return the token
faluco@6
  1987
 *  last examined, instead of a new token.
faluco@6
  1988
 *
faluco@6
  1989
 *  Only one token can be pushed back.
faluco@6
  1990
 *
faluco@6
  1991
 *  In fact, lex() already stores the information it finds into global
faluco@6
  1992
 *  variables, so all that is to be done is set a flag that informs lex()
faluco@6
  1993
 *  to read and return the information from these variables, rather than
faluco@6
  1994
 *  to read in a new token from the input file.
faluco@6
  1995
 */
faluco@6
  1996
SC_FUNC void lexpush(void)
faluco@6
  1997
{
faluco@6
  1998
  assert(_pushed==FALSE);
faluco@6
  1999
  _pushed=TRUE;
faluco@6
  2000
}
faluco@6
  2001
faluco@6
  2002
/*  lexclr
faluco@6
  2003
 *
faluco@6
  2004
 *  Sets the variable "_pushed" to 0 to make sure lex() will read in a new
faluco@6
  2005
 *  symbol (a not continue with some old one). This is required upon return
faluco@6
  2006
 *  from Assembler mode, and in a few cases after detecting an syntax error.
faluco@6
  2007
 */
faluco@6
  2008
SC_FUNC void lexclr(int clreol)
faluco@6
  2009
{
faluco@6
  2010
  _pushed=FALSE;
faluco@6
  2011
  if (clreol) {
faluco@6
  2012
    lptr=(unsigned char*)strchr((char*)pline,'\0');
faluco@6
  2013
    assert(lptr!=NULL);
faluco@6
  2014
  } /* if */
faluco@6
  2015
}
faluco@6
  2016
faluco@6
  2017
/*  matchtoken
faluco@6
  2018
 *
faluco@6
  2019
 *  This routine is useful if only a simple check is needed. If the token
faluco@6
  2020
 *  differs from the one expected, it is pushed back.
faluco@6
  2021
 *  This function returns 1 for "token found" and 2 for "implied statement
faluco@6
  2022
 *  termination token" found --the statement termination is an end of line in
faluco@6
  2023
 *  an expression where there is no pending operation. Such an implied token
faluco@6
  2024
 *  (i.e. not present in the source code) should not be pushed back, which is
faluco@6
  2025
 *  why it is sometimes important to distinguish the two.
faluco@6
  2026
 */
faluco@6
  2027
SC_FUNC int matchtoken(int token)
faluco@6
  2028
{
faluco@6
  2029
  cell val;
faluco@6
  2030
  char *str;
faluco@6
  2031
  int tok;
faluco@6
  2032
faluco@6
  2033
  tok=lex(&val,&str);
faluco@6
  2034
  if (tok==token || token==tTERM && (tok==';' || tok==tENDEXPR)) {
faluco@6
  2035
    return 1;
faluco@6
  2036
  } else if (!sc_needsemicolon && token==tTERM && (_lexnewline || !freading)) {
faluco@6
  2037
    /* Push "tok" back, because it is the token following the implicit statement
faluco@6
  2038
     * termination (newline) token.
faluco@6
  2039
     */
faluco@6
  2040
    lexpush();
faluco@6
  2041
    return 2;
faluco@6
  2042
  } else {
faluco@6
  2043
    lexpush();
faluco@6
  2044
    return 0;
faluco@6
  2045
  } /* if */
faluco@6
  2046
}
faluco@6
  2047
faluco@6
  2048
/*  tokeninfo
faluco@6
  2049
 *
faluco@6
  2050
 *  Returns additional information of a token after using "matchtoken()"
faluco@6
  2051
 *  or needtoken(). It does no harm using this routine after a call to
faluco@6
  2052
 *  "lex()", but lex() already returns the same information.
faluco@6
  2053
 *
faluco@6
  2054
 *  The token itself is the return value. Normally, this one is already known.
faluco@6
  2055
 */
faluco@6
  2056
SC_FUNC int tokeninfo(cell *val,char **str)
faluco@6
  2057
{
faluco@6
  2058
  /* if the token was pushed back, tokeninfo() returns the token and
faluco@6
  2059
   * parameters of the *next* token, not of the *current* token.
faluco@6
  2060
   */
faluco@6
  2061
  assert(!_pushed);
faluco@6
  2062
  *val=_lexval;
faluco@6
  2063
  *str=_lexstr;
faluco@6
  2064
  return _lextok;
faluco@6
  2065
}
faluco@6
  2066
faluco@6
  2067
/*  needtoken
faluco@6
  2068
 *
faluco@6
  2069
 *  This routine checks for a required token and gives an error message if
faluco@6
  2070
 *  it isn't there (and returns 0/FALSE in that case). Like function matchtoken(),
faluco@6
  2071
 *  this function returns 1 for "token found" and 2 for "statement termination
faluco@6
  2072
 *  token" found; see function matchtoken() for details.
faluco@6
  2073
 *
faluco@6
  2074
 *  Global references: _lextok;
faluco@6
  2075
 */
faluco@6
  2076
SC_FUNC int needtoken(int token)
faluco@6
  2077
{
faluco@6
  2078
  char s1[20],s2[20];
faluco@6
  2079
  int t;
faluco@6
  2080
faluco@6
  2081
  if ((t=matchtoken(token))!=0) {
faluco@6
  2082
    return t;
faluco@6
  2083
  } else {
faluco@6
  2084
    /* token already pushed back */
faluco@6
  2085
    assert(_pushed);
faluco@6
  2086
    if (token<256)
faluco@6
  2087
      sprintf(s1,"%c",(char)token);        /* single character token */
faluco@6
  2088
    else
faluco@6
  2089
      strcpy(s1,sc_tokens[token-tFIRST]);  /* multi-character symbol */
faluco@6
  2090
    if (!freading)
faluco@6
  2091
      strcpy(s2,"-end of file-");
faluco@6
  2092
    else if (_lextok<256)
faluco@6
  2093
      sprintf(s2,"%c",(char)_lextok);
faluco@6
  2094
    else
faluco@6
  2095
      strcpy(s2,sc_tokens[_lextok-tFIRST]);
faluco@6
  2096
    error(1,s1,s2);     /* expected ..., but found ... */
faluco@6
  2097
    return FALSE;
faluco@6
  2098
  } /* if */
faluco@6
  2099
}
faluco@6
  2100
faluco@6
  2101
/*  match
faluco@6
  2102
 *
faluco@6
  2103
 *  Compares a series of characters from the input file with the characters
faluco@6
  2104
 *  in "st" (that contains a token). If the token on the input file matches
faluco@6
  2105
 *  "st", the input file pointer "lptr" is adjusted to point to the next
faluco@6
  2106
 *  token, otherwise "lptr" remains unaltered.
faluco@6
  2107
 *
faluco@6
  2108
 *  If the parameter "end: is true, match() requires that the first character
faluco@6
  2109
 *  behind the recognized token is non-alphanumeric.
faluco@6
  2110
 *
faluco@6
  2111
 *  Global references: lptr   (altered)
faluco@6
  2112
 */
faluco@6
  2113
static int match(char *st,int end)
faluco@6
  2114
{
faluco@6
  2115
  int k;
faluco@6
  2116
  const unsigned char *ptr;
faluco@6
  2117
faluco@6
  2118
  k=0;
faluco@6
  2119
  ptr=lptr;
faluco@6
  2120
  while (st[k]) {
faluco@6
  2121
    if ((unsigned char)st[k]!=*ptr)
faluco@6
  2122
      return 0;
faluco@6
  2123
    k+=1;
faluco@6
  2124
    ptr+=1;
faluco@6
  2125
  } /* while */
faluco@6
  2126
  if (end) {            /* symbol must terminate with non-alphanumeric char */
faluco@6
  2127
    if (alphanum(*ptr))
faluco@6
  2128
      return 0;
faluco@6
  2129
  } /* if */
faluco@6
  2130
  lptr=ptr;     /* match found, skip symbol */
faluco@6
  2131
  return 1;
faluco@6
  2132
}
faluco@6
  2133
faluco@6
  2134
static void chk_grow_litq(void)
faluco@6
  2135
{
faluco@6
  2136
  if (litidx>=litmax) {
faluco@6
  2137
    cell *p;
faluco@6
  2138
faluco@6
  2139
    litmax+=sDEF_LITMAX;
faluco@6
  2140
    p=(cell *)realloc(litq,litmax*sizeof(cell));
faluco@6
  2141
    if (p==NULL)
faluco@6
  2142
      error(102,"literal table");   /* literal table overflow (fatal error) */
faluco@6
  2143
    litq=p;
faluco@6
  2144
  } /* if */
faluco@6
  2145
}
faluco@6
  2146
faluco@6
  2147
/*  litadd
faluco@6
  2148
 *
faluco@6
  2149
 *  Adds a value at the end of the literal queue. The literal queue is used
faluco@6
  2150
 *  for literal strings used in functions and for initializing array variables.
faluco@6
  2151
 *
faluco@6
  2152
 *  Global references: litidx  (altered)
faluco@6
  2153
 *                     litq    (altered)
faluco@6
  2154
 */
faluco@6
  2155
SC_FUNC void litadd(cell value)
faluco@6
  2156
{
faluco@6
  2157
  chk_grow_litq();
faluco@6
  2158
  assert(litidx<litmax);
faluco@6
  2159
  litq[litidx++]=value;
faluco@6
  2160
}
faluco@6
  2161
faluco@6
  2162
/*  litinsert
faluco@6
  2163
 *
faluco@6
  2164
 *  Inserts a value into the literal queue. This is sometimes necessary for
faluco@6
  2165
 *  initializing multi-dimensional arrays.
faluco@6
  2166
 *
faluco@6
  2167
 *  Global references: litidx  (altered)
faluco@6
  2168
 *                     litq    (altered)
faluco@6
  2169
 */
faluco@6
  2170
SC_FUNC void litinsert(cell value,int pos)
faluco@6
  2171
{
faluco@6
  2172
  chk_grow_litq();
faluco@6
  2173
  assert(litidx<litmax);
faluco@6
  2174
  assert(pos>=0 && pos<=litidx);
faluco@6
  2175
  memmove(litq+(pos+1),litq+pos,(litidx-pos)*sizeof(cell));
faluco@6
  2176
  litidx++;
faluco@6
  2177
  litq[pos]=value;
faluco@6
  2178
}
faluco@6
  2179
faluco@6
  2180
/*  litchar
faluco@6
  2181
 *
faluco@6
  2182
 *  Return current literal character and increase the pointer to point
faluco@6
  2183
 *  just behind this literal character.
faluco@6
  2184
 *
faluco@6
  2185
 *  Note: standard "escape sequences" are suported, but the backslash may be
faluco@6
  2186
 *        replaced by another character; the syntax '\ddd' is supported,
faluco@6
  2187
 *        but ddd must be decimal!
faluco@6
  2188
 */
faluco@6
  2189
static cell litchar(const unsigned char **lptr,int flags)
faluco@6
  2190
{
faluco@6
  2191
  cell c=0;
faluco@6
  2192
  const unsigned char *cptr;
faluco@6
  2193
faluco@6
  2194
  cptr=*lptr;
faluco@6
  2195
  if ((flags & RAWMODE)!=0 || *cptr!=sc_ctrlchar) {  /* no escape character */
faluco@6
  2196
    #if !defined NO_UTF8
faluco@6
  2197
      if (sc_is_utf8 && (flags & UTF8MODE)!=0) {
faluco@6
  2198
        c=get_utf8_char(cptr,&cptr);
faluco@6
  2199
        assert(c>=0);   /* file was already scanned for conformance to UTF-8 */
faluco@6
  2200
      } else {
faluco@6
  2201
    #endif
faluco@6
  2202
      #if !defined NO_CODEPAGE
faluco@6
  2203
        c=cp_translate(cptr,&cptr);
faluco@6
  2204
      #else
faluco@6
  2205
        c=*cptr;
faluco@6
  2206
        cptr+=1;
faluco@6
  2207
      #endif
faluco@6
  2208
    #if !defined NO_UTF8
faluco@6
  2209
      } /* if */
faluco@6
  2210
    #endif
faluco@6
  2211
  } else {
faluco@6
  2212
    cptr+=1;
faluco@6
  2213
    if (*cptr==sc_ctrlchar) {
faluco@6
  2214
      c=*cptr;          /* \\ == \ (the escape character itself) */
faluco@6
  2215
      cptr+=1;
faluco@6
  2216
    } else {
faluco@6
  2217
      switch (*cptr) {
faluco@6
  2218
      case 'a':         /* \a == audible alarm */
faluco@6
  2219
        c=7;
faluco@6
  2220
        cptr+=1;
faluco@6
  2221
        break;
faluco@6
  2222
      case 'b':         /* \b == backspace */
faluco@6
  2223
        c=8;
faluco@6
  2224
        cptr+=1;
faluco@6
  2225
        break;
faluco@6
  2226
      case 'e':         /* \e == escape */
faluco@6
  2227
        c=27;
faluco@6
  2228
        cptr+=1;
faluco@6
  2229
        break;
faluco@6
  2230
      case 'f':         /* \f == form feed */
faluco@6
  2231
        c=12;
faluco@6
  2232
        cptr+=1;
faluco@6
  2233
        break;
faluco@6
  2234
      case 'n':         /* \n == NewLine character */
faluco@6
  2235
        c=10;
faluco@6
  2236
        cptr+=1;
faluco@6
  2237
        break;
faluco@6
  2238
      case 'r':         /* \r == carriage return */
faluco@6
  2239
        c=13;
faluco@6
  2240
        cptr+=1;
faluco@6
  2241
        break;
faluco@6
  2242
      case 't':         /* \t == horizontal TAB */
faluco@6
  2243
        c=9;
faluco@6
  2244
        cptr+=1;
faluco@6
  2245
        break;
faluco@6
  2246
      case 'v':         /* \v == vertical TAB */
faluco@6
  2247
        c=11;
faluco@6
  2248
        cptr+=1;
faluco@6
  2249
        break;
faluco@6
  2250
      case 'x':
faluco@6
  2251
        cptr+=1;
faluco@6
  2252
        c=0;
faluco@6
  2253
        while (ishex(*cptr)) {
faluco@6
  2254
          if (isdigit(*cptr))
faluco@6
  2255
            c=(c<<4)+(*cptr-'0');
faluco@6
  2256
          else
faluco@6
  2257
            c=(c<<4)+(tolower(*cptr)-'a'+10);
faluco@6
  2258
          cptr++;
faluco@6
  2259
        } /* while */
faluco@6
  2260
        if (*cptr==';')
faluco@6
  2261
          cptr++;       /* swallow a trailing ';' */
faluco@6
  2262
        break;
faluco@6
  2263
      case '\'':        /* \' == ' (single quote) */
faluco@6
  2264
      case '"':         /* \" == " (single quote) */
faluco@6
  2265
      case '%':         /* \% == % (percent) */
faluco@6
  2266
        c=*cptr;
faluco@6
  2267
        cptr+=1;
faluco@6
  2268
        break;
faluco@6
  2269
      default:
faluco@6
  2270
        if (isdigit(*cptr)) {   /* \ddd */
faluco@6
  2271
          c=0;
faluco@6
  2272
          while (*cptr>='0' && *cptr<='9')  /* decimal! */
faluco@6
  2273
            c=c*10 + *cptr++ - '0';
faluco@6
  2274
          if (*cptr==';')
faluco@6
  2275
            cptr++;     /* swallow a trailing ';' */
faluco@6
  2276
        } else {
faluco@6
  2277
          error(27);    /* invalid character constant */
faluco@6
  2278
        } /* if */
faluco@6
  2279
      } /* switch */
faluco@6
  2280
    } /* if */
faluco@6
  2281
  } /* if */
faluco@6
  2282
  *lptr=cptr;
faluco@6
  2283
  assert(c>=0);
faluco@6
  2284
  return c;
faluco@6
  2285
}
faluco@6
  2286
faluco@6
  2287
/*  alpha
faluco@6
  2288
 *
faluco@6
  2289
 *  Test if character "c" is alphabetic ("a".."z"), an underscore ("_")
faluco@6
  2290
 *  or an "at" sign ("@"). The "@" is an extension to standard C.
faluco@6
  2291
 */
faluco@6
  2292
static int alpha(char c)
faluco@6
  2293
{
faluco@6
  2294
  return (isalpha(c) || c=='_' || c==PUBLIC_CHAR);
faluco@6
  2295
}
faluco@6
  2296
faluco@6
  2297
/*  alphanum
faluco@6
  2298
 *
faluco@6
  2299
 *  Test if character "c" is alphanumeric ("a".."z", "0".."9", "_" or "@")
faluco@6
  2300
 */
faluco@6
  2301
SC_FUNC int alphanum(char c)
faluco@6
  2302
{
faluco@6
  2303
  return (alpha(c) || isdigit(c));
faluco@6
  2304
}
faluco@6
  2305
faluco@6
  2306
/*  ishex
faluco@6
  2307
 *
faluco@6
  2308
 *  Test if character "c" is a hexadecimal digit ("0".."9" or "a".."f").
faluco@6
  2309
 */
faluco@6
  2310
SC_FUNC int ishex(char c)
faluco@6
  2311
{
faluco@6
  2312
  return (c>='0' && c<='9') || (c>='a' && c<='f') || (c>='A' && c<='F');
faluco@6
  2313
}
faluco@6
  2314
faluco@6
  2315
/* The local variable table must be searched backwards, so that the deepest
faluco@6
  2316
 * nesting of local variables is searched first. The simplest way to do
faluco@6
  2317
 * this is to insert all new items at the head of the list.
faluco@6
  2318
 * In the global list, the symbols are kept in sorted order, so that the
faluco@6
  2319
 * public functions are written in sorted order.
faluco@6
  2320
 */
faluco@6
  2321
static symbol *add_symbol(symbol *root,symbol *entry,int sort)
faluco@6
  2322
{
faluco@6
  2323
  symbol *newsym;
faluco@6
  2324
faluco@6
  2325
  if (sort)
faluco@6
  2326
    while (root->next!=NULL && strcmp(entry->name,root->next->name)>0)
faluco@6
  2327
      root=root->next;
faluco@6
  2328
faluco@6
  2329
  if ((newsym=(symbol *)malloc(sizeof(symbol)))==NULL) {
faluco@6
  2330
    error(103);
faluco@6
  2331
    return NULL;
faluco@6
  2332
  } /* if */
faluco@6
  2333
  memcpy(newsym,entry,sizeof(symbol));
faluco@6
  2334
  newsym->next=root->next;
faluco@6
  2335
  root->next=newsym;
faluco@6
  2336
  return newsym;
faluco@6
  2337
}
faluco@6
  2338
faluco@6
  2339
static void free_symbol(symbol *sym)
faluco@6
  2340
{
faluco@6
  2341
  arginfo *arg;
faluco@6
  2342
faluco@6
  2343
  /* free all sub-symbol allocated memory blocks, depending on the
faluco@6
  2344
   * kind of the symbol
faluco@6
  2345
   */
faluco@6
  2346
  assert(sym!=NULL);
faluco@6
  2347
  if (sym->ident==iFUNCTN) {
faluco@6
  2348
    /* run through the argument list; "default array" arguments
faluco@6
  2349
     * must be freed explicitly; the tag list must also be freed */
faluco@6
  2350
    assert(sym->dim.arglist!=NULL);
faluco@6
  2351
    for (arg=sym->dim.arglist; arg->ident!=0; arg++) {
faluco@6
  2352
      if (arg->ident==iREFARRAY && arg->hasdefault)
faluco@6
  2353
        free(arg->defvalue.array.data);
faluco@6
  2354
      else if (arg->ident==iVARIABLE
faluco@6
  2355
               && ((arg->hasdefault & uSIZEOF)!=0 || (arg->hasdefault & uTAGOF)!=0))
faluco@6
  2356
        free(arg->defvalue.size.symname);
faluco@6
  2357
      assert(arg->tags!=NULL);
faluco@6
  2358
      free(arg->tags);
faluco@6
  2359
    } /* for */
faluco@6
  2360
    free(sym->dim.arglist);
faluco@6
  2361
    if (sym->states!=NULL) {
faluco@6
  2362
      delete_consttable(sym->states);
faluco@6
  2363
      free(sym->states);
faluco@6
  2364
    } /* if */
faluco@6
  2365
  } else if (sym->ident==iVARIABLE || sym->ident==iARRAY) {
faluco@6
  2366
    if (sym->states!=NULL) {
faluco@6
  2367
      delete_consttable(sym->states);
faluco@6
  2368
      free(sym->states);
faluco@6
  2369
    } /* if */
faluco@6
  2370
  } else if (sym->ident==iCONSTEXPR && (sym->usage & uENUMROOT)==uENUMROOT) {
faluco@6
  2371
    /* free the constant list of an enum root */
faluco@6
  2372
    assert(sym->dim.enumlist!=NULL);
faluco@6
  2373
    delete_consttable(sym->dim.enumlist);
faluco@6
  2374
    free(sym->dim.enumlist);
faluco@6
  2375
  } /* if */
faluco@6
  2376
  assert(sym->refer!=NULL);
faluco@6
  2377
  free(sym->refer);
faluco@6
  2378
  if (sym->documentation!=NULL)
faluco@6
  2379
    free(sym->documentation);
faluco@6
  2380
  free(sym);
faluco@6
  2381
}
faluco@6
  2382
faluco@6
  2383
SC_FUNC void delete_symbol(symbol *root,symbol *sym)
faluco@6
  2384
{
faluco@6
  2385
  /* find the symbol and its predecessor
faluco@6
  2386
   * (this function assumes that you will never delete a symbol that is not
faluco@6
  2387
   * in the table pointed at by "root")
faluco@6
  2388
   */
faluco@6
  2389
  assert(root!=sym);
faluco@6
  2390
  while (root->next!=sym) {
faluco@6
  2391
    root=root->next;
faluco@6
  2392
    assert(root!=NULL);
faluco@6
  2393
  } /* while */
faluco@6
  2394
faluco@6
  2395
  /* unlink it, then free it */
faluco@6
  2396
  root->next=sym->next;
faluco@6
  2397
  free_symbol(sym);
faluco@6
  2398
}
faluco@6
  2399
faluco@6
  2400
SC_FUNC void delete_symbols(symbol *root,int level,int delete_labels,int delete_functions)
faluco@6
  2401
{
faluco@6
  2402
  symbol *sym,*parent_sym;
faluco@6
  2403
  constvalue *stateptr;
faluco@6
  2404
  int mustdelete;
faluco@6
  2405
faluco@6
  2406
  /* erase only the symbols with a deeper nesting level than the
faluco@6
  2407
   * specified nesting level */
faluco@6
  2408
  while (root->next!=NULL) {
faluco@6
  2409
    sym=root->next;
faluco@6
  2410
    if (sym->compound<level)
faluco@6
  2411
      break;
faluco@6
  2412
    switch (sym->ident) {
faluco@6
  2413
    case iLABEL:
faluco@6
  2414
      mustdelete=delete_labels;
faluco@6
  2415
      break;
faluco@6
  2416
    case iVARIABLE:
faluco@6
  2417
    case iARRAY:
faluco@6
  2418
      /* do not delete global variables if functions are preserved */
faluco@6
  2419
      mustdelete=delete_functions;
faluco@6
  2420
      break;
faluco@6
  2421
    case iREFERENCE:
faluco@6
  2422
      /* always delete references (only exist as function parameters) */
faluco@6
  2423
      mustdelete=TRUE;
faluco@6
  2424
      break;
faluco@6
  2425
    case iREFARRAY:
faluco@6
  2426
      /* a global iREFARRAY symbol is the return value of a function: delete
faluco@6
  2427
       * this only if "globals" must be deleted; other iREFARRAY instances
faluco@6
  2428
       * (locals) are also deleted
faluco@6
  2429
       */
faluco@6
  2430
      mustdelete=delete_functions;
faluco@6
  2431
      for (parent_sym=sym->parent; parent_sym!=NULL && parent_sym->ident!=iFUNCTN; parent_sym=parent_sym->parent)
faluco@6
  2432
        assert(parent_sym->ident==iREFARRAY);
faluco@6
  2433
      assert(parent_sym==NULL || (parent_sym->ident==iFUNCTN && parent_sym->parent==NULL));
faluco@6
  2434
      if (parent_sym==NULL || parent_sym->ident!=iFUNCTN)
faluco@6
  2435
        mustdelete=TRUE;
faluco@6
  2436
      break;
faluco@6
  2437
    case iCONSTEXPR:
faluco@6
  2438
      /* delete constants, except predefined constants */
faluco@6
  2439
      mustdelete=delete_functions || (sym->usage & uPREDEF)==0;
faluco@6
  2440
      break;
faluco@6
  2441
    case iFUNCTN:
faluco@6
  2442
      /* optionally preserve globals (variables & functions), but
faluco@6
  2443
       * NOT native functions
faluco@6
  2444
       */
faluco@6
  2445
      mustdelete=delete_functions || (sym->usage & uNATIVE)!=0;
faluco@6
  2446
      assert(sym->parent==NULL);
faluco@6
  2447
      break;
faluco@6
  2448
    case iARRAYCELL:
faluco@6
  2449
    case iARRAYCHAR:
faluco@6
  2450
    case iEXPRESSION:
faluco@6
  2451
    case iVARARGS:
faluco@6
  2452
    default:
faluco@6
  2453
      assert(0);
faluco@6
  2454
      break;
faluco@6
  2455
    } /* switch */
faluco@6
  2456
    if (mustdelete) {
faluco@6
  2457
      root->next=sym->next;
faluco@6
  2458
      free_symbol(sym);
faluco@6
  2459
    } else {
faluco@6
  2460
      /* if the function was prototyped, but not implemented in this source,
faluco@6
  2461
       * mark it as such, so that its use can be flagged
faluco@6
  2462
       */
faluco@6
  2463
      if (sym->ident==iFUNCTN && (sym->usage & uDEFINE)==0)
faluco@6
  2464
        sym->usage |= uMISSING;
faluco@6
  2465
      if (sym->ident==iFUNCTN || sym->ident==iVARIABLE || sym->ident==iARRAY)
faluco@6
  2466
        sym->usage &= ~uDEFINE; /* clear "defined" flag */
faluco@6
  2467
      /* set all states as "undefined" too */
faluco@6
  2468
      if (sym->states!=NULL)
faluco@6
  2469
        for (stateptr=sym->states->next; stateptr!=NULL; stateptr=stateptr->next)
faluco@6
  2470
          stateptr->value=0;
faluco@6
  2471
      /* for user defined operators, also remove the "prototyped" flag, as
faluco@6
  2472
       * user-defined operators *must* be declared before use
faluco@6
  2473
       */
faluco@6
  2474
      if (sym->ident==iFUNCTN && !alpha(*sym->name))
faluco@6
  2475
        sym->usage &= ~uPROTOTYPED;
faluco@6
  2476
      root=sym;                 /* skip the symbol */
faluco@6
  2477
    } /* if */
faluco@6
  2478
  } /* if */
faluco@6
  2479
}
faluco@6
  2480
faluco@6
  2481
/* The purpose of the hash is to reduce the frequency of a "name"
faluco@6
  2482
 * comparison (which is costly). There is little interest in avoiding
faluco@6
  2483
 * clusters in similar names, which is why this function is plain simple.
faluco@6
  2484
 */
faluco@6
  2485
SC_FUNC uint32_t namehash(const char *name)
faluco@6
  2486
{
faluco@6
  2487
  const unsigned char *ptr=(const unsigned char *)name;
faluco@6
  2488
  int len=strlen(name);
faluco@6
  2489
  if (len==0)
faluco@6
  2490
    return 0L;
faluco@6
  2491
  assert(len<256);
faluco@6
  2492
  return (len<<24Lu) + (ptr[0]<<16Lu) + (ptr[len-1]<<8Lu) + (ptr[len>>1Lu]);
faluco@6
  2493
}
faluco@6
  2494
faluco@6
  2495
static symbol *find_symbol(const symbol *root,const char *name,int fnumber,int automaton,int *cmptag)
faluco@6
  2496
{
faluco@6
  2497
  symbol *firstmatch=NULL;
faluco@6
  2498
  symbol *sym=root->next;
faluco@6
  2499
  int count=0;
faluco@6
  2500
  unsigned long hash=namehash(name);
faluco@6
  2501
  while (sym!=NULL) {
faluco@6
  2502
    if (hash==sym->hash && strcmp(name,sym->name)==0        /* check name */
faluco@6
  2503
        && (sym->parent==NULL || sym->ident==iCONSTEXPR)    /* sub-types (hierarchical types) are skipped, except for enum fields */
faluco@6
  2504
        && (sym->fnumber<0 || sym->fnumber==fnumber))       /* check file number for scope */
faluco@6
  2505
    {
faluco@6
  2506
      assert(sym->states==NULL || sym->states->next!=NULL); /* first element of the state list is the "root" */
faluco@6
  2507
      if (sym->ident==iFUNCTN
faluco@6
  2508
          || automaton<0 && sym->states==NULL
faluco@6
  2509
          || automaton>=0 && sym->states!=NULL && state_getfsa(sym->states->next->index)==automaton)
faluco@6
  2510
      {
faluco@6
  2511
        if (cmptag==NULL)
faluco@6
  2512
          return sym;   /* return first match */
faluco@6
  2513
        /* return closest match or first match; count number of matches */
faluco@6
  2514
        if (firstmatch==NULL)
faluco@6
  2515
          firstmatch=sym;
faluco@6
  2516
        assert(cmptag!=NULL);
faluco@6
  2517
        if (*cmptag==0)
faluco@6
  2518
          count++;
faluco@6
  2519
        if (*cmptag==sym->tag) {
faluco@6
  2520
          *cmptag=1;    /* good match found, set number of matches to 1 */
faluco@6
  2521
          return sym;
faluco@6
  2522
        } /* if */
faluco@6
  2523
      } /* if */
faluco@6
  2524
    } /*  */
faluco@6
  2525
    sym=sym->next;
faluco@6
  2526
  } /* while */
faluco@6
  2527
  if (cmptag!=NULL && firstmatch!=NULL)
faluco@6
  2528
    *cmptag=count;
faluco@6
  2529
  return firstmatch;
faluco@6
  2530
}
faluco@6
  2531
faluco@6
  2532
static symbol *find_symbol_child(const symbol *root,const symbol *sym)
faluco@6
  2533
{
faluco@6
  2534
  symbol *ptr=root->next;
faluco@6
  2535
  while (ptr!=NULL) {
faluco@6
  2536
    if (ptr->parent==sym)
faluco@6
  2537
      return ptr;
faluco@6
  2538
    ptr=ptr->next;
faluco@6
  2539
  } /* while */
faluco@6
  2540
  return NULL;
faluco@6
  2541
}
faluco@6
  2542
faluco@6
  2543
/* Adds "bywhom" to the list of referrers of "entry". Typically,
faluco@6
  2544
 * bywhom will be the function that uses a variable or that calls
faluco@6
  2545
 * the function.
faluco@6
  2546
 */
faluco@6
  2547
SC_FUNC int refer_symbol(symbol *entry,symbol *bywhom)
faluco@6
  2548
{
faluco@6
  2549
  int count;
faluco@6
  2550
faluco@6
  2551
  assert(bywhom!=NULL);         /* it makes no sense to add a "void" referrer */
faluco@6
  2552
  assert(entry!=NULL);
faluco@6
  2553
  assert(entry->refer!=NULL);
faluco@6
  2554
faluco@6
  2555
  /* see if it is already there */
faluco@6
  2556
  for (count=0; count<entry->numrefers && entry->refer[count]!=bywhom; count++)
faluco@6
  2557
    /* nothing */;
faluco@6
  2558
  if (count<entry->numrefers) {
faluco@6
  2559
    assert(entry->refer[count]==bywhom);
faluco@6
  2560
    return TRUE;
faluco@6
  2561
  } /* if */
faluco@6
  2562
faluco@6
  2563
  /* see if there is an empty spot in the referrer list */
faluco@6
  2564
  for (count=0; count<entry->numrefers && entry->refer[count]!=NULL; count++)
faluco@6
  2565
    /* nothing */;
faluco@6
  2566
  assert(count <= entry->numrefers);
faluco@6
  2567
  if (count==entry->numrefers) {
faluco@6
  2568
    symbol **refer;
faluco@6
  2569
    int newsize=2*entry->numrefers;
faluco@6
  2570
    assert(newsize>0);
faluco@6
  2571
    /* grow the referrer list */
faluco@6
  2572
    refer=(symbol**)realloc(entry->refer,newsize*sizeof(symbol*));
faluco@6
  2573
    if (refer==NULL)
faluco@6
  2574
      return FALSE;             /* insufficient memory */
faluco@6
  2575
    /* initialize the new entries */
faluco@6
  2576
    entry->refer=refer;
faluco@6
  2577
    for (count=entry->numrefers; count<newsize; count++)
faluco@6
  2578
      entry->refer[count]=NULL;
faluco@6
  2579
    count=entry->numrefers;     /* first empty spot */
faluco@6
  2580
    entry->numrefers=newsize;
faluco@6
  2581
  } /* if */
faluco@6
  2582
faluco@6
  2583
  /* add the referrer */
faluco@6
  2584
  assert(entry->refer[count]==NULL);
faluco@6
  2585
  entry->refer[count]=bywhom;
faluco@6
  2586
  return TRUE;
faluco@6
  2587
}
faluco@6
  2588
faluco@6
  2589
SC_FUNC void markusage(symbol *sym,int usage)
faluco@6
  2590
{
faluco@6
  2591
  assert(sym!=NULL);
faluco@6
  2592
  sym->usage |= (char)usage;
faluco@6
  2593
  if ((usage & uWRITTEN)!=0)
faluco@6
  2594
    sym->lnumber=fline;
faluco@6
  2595
  /* check if (global) reference must be added to the symbol */
faluco@6
  2596
  if ((usage & (uREAD | uWRITTEN))!=0) {
faluco@6
  2597
    /* only do this for global symbols */
faluco@6
  2598
    if (sym->vclass==sGLOBAL) {
faluco@6
  2599
      /* "curfunc" should always be valid, since statements may not occurs
faluco@6
  2600
       * outside functions; in the case of syntax errors, however, the
faluco@6
  2601
       * compiler may arrive through this function
faluco@6
  2602
       */
faluco@6
  2603
      if (curfunc!=NULL)
faluco@6
  2604
        refer_symbol(sym,curfunc);
faluco@6
  2605
    } /* if */
faluco@6
  2606
  } /* if */
faluco@6
  2607
}
faluco@6
  2608
faluco@6
  2609
faluco@6
  2610
/*  findglb
faluco@6
  2611
 *
faluco@6
  2612
 *  Returns a pointer to the global symbol (if found) or NULL (if not found)
faluco@6
  2613
 */
faluco@6
  2614
SC_FUNC symbol *findglb(const char *name,int filter)
faluco@6
  2615
{
faluco@6
  2616
  /* find a symbol with a matching automaton first */
faluco@6
  2617
  symbol *sym=NULL;
faluco@6
  2618
faluco@6
  2619
  if (filter>sGLOBAL && sc_curstates>0) {
faluco@6
  2620
    /* find a symbol whose state list matches the current fsa */
faluco@6
  2621
    sym=find_symbol(&glbtab,name,fcurrent,state_getfsa(sc_curstates),NULL);
faluco@6
  2622
    if (sym!=NULL && sym->ident!=iFUNCTN) {
faluco@6
  2623
      /* if sym!=NULL, we found a variable in the automaton; now we should
faluco@6
  2624
       * also verify whether there is an intersection between the symbol's
faluco@6
  2625
       * state list and the current state list
faluco@6
  2626
       */
faluco@6
  2627
      assert(sym->states!=NULL && sym->states->next!=NULL);
faluco@6
  2628
      if (!state_conflict_id(sc_curstates,sym->states->next->index))
faluco@6
  2629
        sym=NULL;
faluco@6
  2630
    } /* if */
faluco@6
  2631
  } /* if */
faluco@6
  2632
faluco@6
  2633
  /* if no symbol with a matching automaton exists, find a variable/function
faluco@6
  2634
   * that has no state(s) attached to it
faluco@6
  2635
   */
faluco@6
  2636
  if (sym==NULL)
faluco@6
  2637
    sym=find_symbol(&glbtab,name,fcurrent,-1,NULL);
faluco@6
  2638
  return sym;
faluco@6
  2639
}
faluco@6
  2640
faluco@6
  2641
/*  findloc
faluco@6
  2642
 *
faluco@6
  2643
 *  Returns a pointer to the local symbol (if found) or NULL (if not found).
faluco@6
  2644
 *  See add_symbol() how the deepest nesting level is searched first.
faluco@6
  2645
 */
faluco@6
  2646
SC_FUNC symbol *findloc(const char *name)
faluco@6
  2647
{
faluco@6
  2648
  return find_symbol(&loctab,name,-1,-1,NULL);
faluco@6
  2649
}
faluco@6
  2650
faluco@6
  2651
SC_FUNC symbol *findconst(const char *name,int *cmptag)
faluco@6
  2652
{
faluco@6
  2653
  symbol *sym;
faluco@6
  2654
faluco@6
  2655
  sym=find_symbol(&loctab,name,-1,-1,cmptag);  /* try local symbols first */
faluco@6
  2656
  if (sym==NULL || sym->ident!=iCONSTEXPR)     /* not found, or not a constant */
faluco@6
  2657
    sym=find_symbol(&glbtab,name,fcurrent,-1,cmptag);
faluco@6
  2658
  if (sym==NULL || sym->ident!=iCONSTEXPR)
faluco@6
  2659
    return NULL;
faluco@6
  2660
  assert(sym->parent==NULL || (sym->usage & uENUMFIELD)!=0);
faluco@6
  2661
  /* ^^^ constants have no hierarchy, but enumeration fields may have a parent */
faluco@6
  2662
  return sym;
faluco@6
  2663
}
faluco@6
  2664
faluco@6
  2665
SC_FUNC symbol *finddepend(const symbol *parent)
faluco@6
  2666
{
faluco@6
  2667
  symbol *sym;
faluco@6
  2668
faluco@6
  2669
  sym=find_symbol_child(&loctab,parent);    /* try local symbols first */
faluco@6
  2670
  if (sym==NULL)                            /* not found */
faluco@6
  2671
    sym=find_symbol_child(&glbtab,parent);
faluco@6
  2672
  return sym;
faluco@6
  2673
}
faluco@6
  2674
faluco@6
  2675
/*  addsym
faluco@6
  2676
 *
faluco@6
  2677
 *  Adds a symbol to the symbol table (either global or local variables,
faluco@6
  2678
 *  or global and local constants).
faluco@6
  2679
 */
faluco@6
  2680
SC_FUNC symbol *addsym(const char *name,cell addr,int ident,int vclass,int tag,int usage)
faluco@6
  2681
{
faluco@6
  2682
  symbol entry, **refer;
faluco@6
  2683
faluco@6
  2684
  /* labels may only be defined once */
faluco@6
  2685
  assert(ident!=iLABEL || findloc(name)==NULL);
faluco@6
  2686
faluco@6
  2687
  /* create an empty referrer list */
faluco@6
  2688
  if ((refer=(symbol**)malloc(sizeof(symbol*)))==NULL) {
faluco@6
  2689
    error(103);         /* insufficient memory */
faluco@6
  2690
    return NULL;
faluco@6
  2691
  } /* if */
faluco@6
  2692
  *refer=NULL;
faluco@6
  2693
faluco@6
  2694
  /* first fill in the entry */
faluco@6
  2695
  memset(&entry,0,sizeof entry);
faluco@6
  2696
  strcpy(entry.name,name);
faluco@6
  2697
  entry.hash=namehash(name);
faluco@6
  2698
  entry.addr=addr;
faluco@6
  2699
  entry.codeaddr=code_idx;
faluco@6
  2700
  entry.vclass=(char)vclass;
faluco@6
  2701
  entry.ident=(char)ident;
faluco@6
  2702
  entry.tag=tag;
faluco@6
  2703
  entry.usage=(char)usage;
faluco@6
  2704
  entry.fnumber=-1;     /* assume global visibility (ignored for local symbols) */
faluco@6
  2705
  entry.lnumber=fline;
faluco@6
  2706
  entry.numrefers=1;
faluco@6
  2707
  entry.refer=refer;
faluco@6
  2708
faluco@6
  2709
  /* then insert it in the list */
faluco@6
  2710
  if (vclass==sGLOBAL)
faluco@6
  2711
    return add_symbol(&glbtab,&entry,TRUE);
faluco@6
  2712
  else
faluco@6
  2713
    return add_symbol(&loctab,&entry,FALSE);
faluco@6
  2714
}
faluco@6
  2715
faluco@6
  2716
SC_FUNC symbol *addvariable(const char *name,cell addr,int ident,int vclass,int tag,
faluco@6
  2717
                            int dim[],int numdim,int idxtag[])
faluco@6
  2718
{
faluco@6
  2719
  symbol *sym;
faluco@6
  2720
faluco@6
  2721
  /* global variables may only be defined once
faluco@6
  2722
   * One complication is that functions returning arrays declare an array
faluco@6
  2723
   * with the same name as the function, so the assertion must allow for
faluco@6
  2724
   * this special case. Another complication is that variables may be
faluco@6
  2725
   * "redeclared" if they are local to an automaton (and findglb() will find
faluco@6
  2726
   * the symbol without states if no symbol with states exists).
faluco@6
  2727
   */
faluco@6
  2728
  assert(vclass!=sGLOBAL || (sym=findglb(name,sGLOBAL))==NULL || (sym->usage & uDEFINE)==0
faluco@6
  2729
         || sym->ident==iFUNCTN && sym==curfunc
faluco@6
  2730
         || sym->states==NULL && sc_curstates>0);
faluco@6
  2731
faluco@6
  2732
  if (ident==iARRAY || ident==iREFARRAY) {
faluco@6
  2733
    symbol *parent=NULL,*top;
faluco@6
  2734
    int level;
faluco@6
  2735
    sym=NULL;                   /* to avoid a compiler warning */
faluco@6
  2736
    for (level=0; level<numdim; level++) {
faluco@6
  2737
      top=addsym(name,addr,ident,vclass,tag,uDEFINE);
faluco@6
  2738
      top->dim.array.length=dim[level];
faluco@6
  2739
      top->dim.array.level=(short)(numdim-level-1);
faluco@6
  2740
      top->x.tags.index=idxtag[level];
faluco@6
  2741
      top->parent=parent;
faluco@6
  2742
      parent=top;
faluco@6
  2743
      if (level==0)
faluco@6
  2744
        sym=top;
faluco@6
  2745
    } /* for */
faluco@6
  2746
  } else {
faluco@6
  2747
    sym=addsym(name,addr,ident,vclass,tag,uDEFINE);
faluco@6
  2748
  } /* if */
faluco@6
  2749
  return sym;
faluco@6
  2750
}
faluco@6
  2751
faluco@6
  2752
/*  getlabel
faluco@6
  2753
 *
faluco@6
  2754
 *  Returns te next internal label number. The global variable sc_labnum is
faluco@6
  2755
 *  initialized to zero.
faluco@6
  2756
 */
faluco@6
  2757
SC_FUNC int getlabel(void)
faluco@6
  2758
{
faluco@6
  2759
  return sc_labnum++;
faluco@6
  2760
}
faluco@6
  2761
faluco@6
  2762
/*  itoh
faluco@6
  2763
 *
faluco@6
  2764
 *  Converts a number to a hexadecimal string and returns a pointer to that
faluco@6
  2765
 *  string. This function is NOT re-entrant.
faluco@6
  2766
 */
faluco@6
  2767
SC_FUNC char *itoh(ucell val)
faluco@6
  2768
{
faluco@6
  2769
static char itohstr[30];
faluco@6
  2770
  char *ptr;
faluco@6
  2771
  int i,nibble[16];             /* a 64-bit hexadecimal cell has 16 nibbles */
faluco@6
  2772
  int max;
faluco@6
  2773
faluco@6
  2774
  #if PAWN_CELL_SIZE==16
faluco@6
  2775
    max=4;
faluco@6
  2776
  #elif PAWN_CELL_SIZE==32
faluco@6
  2777
    max=8;
faluco@6
  2778
  #elif PAWN_CELL_SIZE==64
faluco@6
  2779
    max=16;
faluco@6
  2780
  #else
faluco@6
  2781
    #error Unsupported cell size
faluco@6
  2782
  #endif
faluco@6
  2783
  ptr=itohstr;
faluco@6
  2784
  for (i=0; i<max; i+=1){
faluco@6
  2785
    nibble[i]=(int)(val & 0x0f);        /* nibble 0 is lowest nibble */
faluco@6
  2786
    val>>=4;
faluco@6
  2787
  } /* endfor */
faluco@6
  2788
  i=max-1;
faluco@6
  2789
  while (nibble[i]==0 && i>0)   /* search for highest non-zero nibble */
faluco@6
  2790
    i-=1;
faluco@6
  2791
  while (i>=0){
faluco@6
  2792
    if (nibble[i]>=10)
faluco@6
  2793
      *ptr++=(char)('a'+(nibble[i]-10));
faluco@6
  2794
    else
faluco@6
  2795
      *ptr++=(char)('0'+nibble[i]);
faluco@6
  2796
    i-=1;
faluco@6
  2797
  } /* while */
faluco@6
  2798
  *ptr='\0';            /* and a zero-terminator */
faluco@6
  2799
  return itohstr;
faluco@6
  2800
}
faluco@6
  2801