lex.c
ldmud-3.3.719/src/lex.c · 223.8 KB
From the archive ldmud-3.3.719.tar.gz
Download the archive « Back to the archive contents
/*---------------------------------------------------------------------------
* LPC-Compiler: Preprocessor and Lexical Analysis.
*
*---------------------------------------------------------------------------
* The lexer is initialised by a call to init_lexer(). This function sets
* up the internal tables and also reads the permanent defines from
* the lpc_predefs list the caller set up before the call.
*
* A new compilation is set up by a call to start_new_file(), passing
* the filedescriptor of the file to compile as argument. Control is
* then passed to the parser in prolang, which calls yylex() here to
* get the next token. After the compilation is finished, end_new_file()
* performs the cleanup.
*
* The lexer also holds the table of instructions (instrs[]) and the
* driver's own ctype tables. Both are included from the file efun_defs.c
* which is generated by the program make_func during the building
* process.
*
* For an explanation of the datastructures look at the places of
* definition of the structures - it's too much to put here, too.
*---------------------------------------------------------------------------
*/
#include "driver.h"
#include "typedefs.h"
#include "my-alloca.h"
#include <stdio.h>
#include <fcntl.h>
#include <ctype.h>
#include <stdarg.h>
#include <stddef.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "lex.h"
#include "array.h"
#include "backend.h"
#include "closure.h"
#include "comm.h"
#include "exec.h"
#include "filestat.h"
#include "gcollect.h"
#include "hash.h"
#include "instrs.h"
#include "interpret.h"
#include "lang.h"
#include "main.h"
#include "mempools.h"
#include "mstrings.h"
#include "object.h"
#include "patchlevel.h"
#include "prolang.h"
#include "simulate.h"
#include "simul_efun.h"
#include "stdstrings.h"
#include "strfuns.h"
#include "svalue.h"
#include "wiz_list.h" /* wizlist_name[] */
#include "xalloc.h"
#include "i-eval_cost.h"
#include "../mudlib/sys/driver_hook.h"
/* TODO: Implement the # and ## operators. With this, #define X(a) (a + "a")
* TODO:: can be made sane (X(b) -> 'b + "a"' instead of 'b + "b"').
* TODO: New predefs' __BASENAME__, __FUNCTION__.
* TODO: #define macro(a,b,...) -> ... is assigned to __VA_ARGS__ (see oncoming
* TODO:: C standard).
* TODO: Does Standard-C allow recursive macro expansion? If not, we
* TODO:: should disallow it, too.
*/
/* We can't use the EOF character directly, as in its (char) representation
* clashes with ISO-8859 character 0xFF. Instead we use ascii SOH (0x01),
* which in turn is not allowed as input character.
*/
#define CHAR_EOF ((char)0x01)
/*-------------------------------------------------------------------------*/
#define MLEN 4096
/* Maximum length of a macro text (definition)
*/
#define NSIZE 256
/* Maximum length of a macro (argument) name.
*/
#define NARGS 25
/* Max number of macro arguments
*/
#define EXPANDMAX 25000
/* Maximum number of expansions per line.
*/
#define MAXLINE 2048
/* Maximum length of an input line.
*/
#define MAX_ANSI_CONCAT 4096
/* Maximum length of an ANSI-style string literal concatenation.
*/
#define INC_OPEN_BUFSIZE 1024
/* Maximum length of an include filename.
*/
#ifndef DEFMAX
# define DEFMAX 12000
#endif
/* Maximum length of an expanded macro.
*/
#define MAX_TOTAL_BUF 400000
/* Maximum length of macro expansion buffer
*/
#define DEFBUF_1STLEN (DEFMAX+MAXLINE+1)
/* Initial length of macro expansion buffer, enough
* to allow DEFMAX + an input line + '\0'
*/
/*-------------------------------------------------------------------------*/
source_loc_t current_loc;
/* The current compilation location.
*/
int total_lines;
/* Total number of lines compiled so far (used to compute the average
* compiled lines/s)
*/
static const char *object_file;
/* Name of the file for which the lexer was originally called.
*/
Bool pragma_use_local_scopes;
/* True: treat all local scopes as one.
*/
Bool pragma_warn_missing_return;
/* True: generate a runtime warning if a value-returning function
* does end with an explicit return statement.
*/
Bool pragma_check_overloads;
/* TRUE if function redefinitions have to match the originals in their
* types. This pragma is meant mainly to ease the adaption of old
* mudlibs.
*/
Bool pragma_strict_types;
/* Type enforcing mode: PRAGMA_WEAK_TYPES, PRAGMA_STRONG_TYPES
* and PRAGMA_STRICT_TYPES.
*/
Bool pragma_save_types;
/* True: save argument types after compilation.
*/
Bool pragma_combine_strings;
/* True: perform '+'-addition of constant strings at compile time.
*/
Bool pragma_verbose_errors;
/* True: give info on the context of an error.
*/
Bool pragma_no_clone;
/* True: prevent the object from being clone.
*/
Bool pragma_no_inherit;
/* True: prevent the program from being inherited.
*/
Bool pragma_no_shadow;
/* True: prevent the program from being shadowed.
*/
Bool pragma_pedantic;
/* True: treat a number of sloppy language constructs as errors.
*/
Bool pragma_warn_deprecated;
/* True: warn if deprecated efuns are used.
*/
Bool pragma_range_check;
/* True: warn (at runtime) if array ranges are invalid.
*/
Bool pragma_share_variables;
/* TRUE: Share the blueprint's variables with its clones.
*/
Bool pragma_warn_empty_casts;
/* True: warn if a type is casted to itself.
*/
string_t *last_lex_string;
/* When lexing string literals, this is the (shared) string lexed
* so far. It is used to pass string values to lang.c and may be
* freed there.
*/
struct lpc_predef_s *lpc_predefs = NULL;
/* List of macros predefined by other parts of the driver, especially from
* main.c for the '-D' commandline option.
*/
static source_file_t * src_file_list = NULL;
/* List of source_file structures during a compile.
*/
static Mempool lexpool = NULL;
/* Fifopool to hold the allocations for the include and lpc_ifstate_t stacks.
*/
/*-------------------------------------------------------------------------*/
/* The lexer can take data from either a file or a string buffer.
* The handling is unified using the struct source_s structure.
* TODO: Use this source similar to auto-include to expand macros in the
* TODO:: the compile. This would make it easier to find errors caused
* TODO:: by macro replacements.
*/
typedef struct source_s
{
int fd; /* Filedescriptor or -1 */
string_t * str; /* The source string (referenced), or NULL */
size_t current; /* Current position in .str */
} source_t;
static source_t yyin;
/* Current input source.
*/
/*-------------------------------------------------------------------------*/
/* The lexer uses a combined file-input/macro-expansion buffer
* called defbuf[] of length <defbuf_len>. Within this buffer, the last
* MAXLINE bytes are reserved as (initial) file-input buffer, its beginning
* and end marked with the pointers linebufstart and linebufend. In this
* space, pointer outp points to the next character to process.
*
* The file-input buffer may contain several textlines, all terminated
* with a '\n'. After the last (complete) textline, a '\0' is set as
* sentinel. Usually this will overwrite the first character of the
* incomplete line right at the end of the input buffer, therefore this
* character is stored in the variable saved_char.
*
* When all lines in the buffer have been processed (ie. outp points to
* the '\0' sentinel), the remaining fragment of the yet incomplete line
* is copied _before_ linebufstart (and outp set accordingly), then
* the next MAXLINE bytes are read into the buffer starting at
* linebufstart.
*
* If there are less than MAXLINE bytes left to read, the end of the file
* is marked in the buffer with the CHAR_EOF character (a \0 sentinel is not
* necessary as compilation and thus lexing will end with the CHAR_EOF
* character).
*
* When including files, a new area of MAXLINE bytes is reserved in defbuf,
* which ends exactly at the current outp. The position of the current
* area is recorded with the current position of linebufstart relative to
* the end of defbuf. Obviously this can be repeated until the max size
* of defbuf (MAX_TOTAL_BUF) is reached.
*
* Macro expansions are done such that the replacement text for a macro
* copied right before outp (which at that time points at the character
* after the macro use), then outp is set back to point at the beginning
* of the added text, lexing the just expanded text next.
*
#ifndef USE_NEW_INLINES
* Functionals (inline functions) are somewhat similar to macros. When a
* definition '(: ... :)' is encountered, a copy of text between the
* delimiters is stored verbatim in the list of inline functions, starting at
* first_inline_fun. To the compiler the lexer returns L_INLINE_FUN with the
* synthetic identifier of the function. Whenever such functions are pending
* and the compiler is at a safe place to accept a function definition
* (signalled in insert_inline_fun_now), the text of the pending functions is
* inserted into the input stream like a macro.
#endif
*/
static char *defbuf = NULL;
/* The combined input/expansion buffer.
*/
static unsigned long defbuf_len = 0;
/* Current length of defbuf.
*/
static char *outp;
/* Pointer to the next character in defbuf[] to be processed.
*/
static char *linebufstart;
/* Begin of the input line buffer within defbuf[].
*/
static char *linebufend;
/* End of the input line buffer within defbuf[].
*/
static char saved_char;
/* The first character of the incomplete line after the last complete
* one in the input buffer. Saved here because in the buffer itself
* it is overwritten with '\0'.
*/
/*-------------------------------------------------------------------------*/
static Bool lex_fatal;
/* True: lexer encountered fatal error.
*/
static svalue_t *inc_list;
/* An array of pathnames to search for <>-include files.
* This is a pointer to the vector.item[] held in the driver_hook[]
* array.
*/
static size_t inc_list_size;
/* The number of names in <inc_list>.
*/
static mp_int inc_list_maxlen;
/* The lenght of the longest name in <inc_list>.
*/
static int nexpands;
/* Number of macro expansions on this line so far.
*/
static char yytext[MAXLINE];
/* Temporary buffer used to collect data.
*/
/*-------------------------------------------------------------------------*/
/* Enforce an appropriate range for ITABLE_SIZE
* The hash used in ident_s is of type short. Therefore the hash table must
* not contain more hash chains than SHRT_MAX.
*/
#if ITABLE_SIZE < 256 || ITABLE_SIZE > SHRT_MAX
#error "ITABLE_SIZE must be within the range of 256 and SHRT_MAX (usually 32768)."
This is the end...
#endif
static ident_t *ident_table[ITABLE_SIZE];
/* The lexer stores all encountered identifiers in a hashtable of struct
* idents. The table follows the usual structure: the index (hash value)
* is computed from the name of the identifier, the indexed table element
* the points to the head of a chain of different identifier values with
* identical hash. The most recently used identifier is always moved to
* the head of the chain.
*
* The table is used to store all identifiers and their value: starting
* from efun names and reserved words (like 'while') over preprocessor
* macros to 'normal' lfun and variable names. The identifiers are
* distinguished by the .type field in the ident structure. Should one
* identifier used with several different types at the same time, one entry
* is generated for each type, and they are all linked together by their
* .inferior pointers into a list ordered by falling type value. The entry
* with the highest type value is the one put into the hashtable's chain.
*/
#if ITABLE_SIZE == 256
# define identhash(s) chashstr((s), 12)
#else
# define identhash(s) (whashstr((s), 12) % ITABLE_SIZE)
#endif
/* Hash an identifier name (c-string) into a table index.
*/
/* In addition to this, the lexer keeps two lists for all efuns and
* preprocessor defines: all_efuns and all_defines. These are linked
* together with the .next_all field in the ident structure.
*/
ident_t *all_efuns = NULL;
/* The list of efuns. */
static ident_t *all_defines = NULL;
/* The list of all non-permanent macro defines.
* Entries with a NULL .name are undefined macros.
*/
static ident_t *permanent_defines = NULL;
/* The list of all permanent macro defines. */
static ident_t *undefined_permanent_defines = NULL;
/* 'Parking list' for permanent defines which have been #undef'ined.
* After the compilation is complete, they will be put back into
* the ident_table.
*/
#ifndef USE_NEW_INLINES
/*-------------------------------------------------------------------------*/
struct inline_fun * first_inline_fun = NULL;
/* Linked list of the saved function text for inline functions.
*/
Bool insert_inline_fun_now = MY_FALSE;
/* This is TRUE when we are at a suitable point to insert the
* saved inline functions. Usually this is at the end of a function,
* or after a global variable definition.
*/
unsigned int next_inline_fun = 0;
/* The running count of inline functions, used to 'name' the next
* function to generate.
*/
#endif /* USE_NEW_INLINES */
/*-------------------------------------------------------------------------*/
/* The stack to handle nested #if...#else...#endif constructs.
*/
typedef struct lpc_ifstate_s
{
struct lpc_ifstate_s *next;
int state; /* which token to expect */
} lpc_ifstate_t;
/* lpc_ifstate_t.state values: */
#define EXPECT_ELSE 1
#define EXPECT_ENDIF 2
static lpc_ifstate_t *iftop = NULL;
/*-------------------------------------------------------------------------*/
/* The stack to save important state information when handling
* nested includes.
*/
static struct incstate
{
struct incstate * next;
source_t yyin; /* The current input source */
source_loc_t loc; /* Current source location */
ptrdiff_t linebufoffset; /* Position of linebufstart */
mp_uint inc_offset; /* Handle returned by store_include_info() */
char saved_char;
} *inctop = NULL;
/*-------------------------------------------------------------------------*/
/* Translation table of reserved words into the lexcodes assigned by yacc
* in lang.h.
*/
struct s_reswords
{
char *name; /* The reserved word */
int code; /* The assigned code */
};
static struct s_reswords reswords[]
= { { "break", L_BREAK }
, { "case", L_CASE }
, { "catch", L_CATCH }
, { "closure", L_CLOSURE_DECL }
, { "continue", L_CONTINUE }
, { "default", L_DEFAULT }
, { "do", L_DO }
, { "else", L_ELSE }
, { "float", L_FLOAT_DECL }
, { "for", L_FOR }
, { "foreach", L_FOREACH }
#ifdef USE_NEW_INLINES
, { "function", L_FUNC }
#endif
, { "if", L_IF }
#ifdef L_IN
, { "in", L_IN }
#endif
, { "inherit", L_INHERIT }
, { "int", L_INT }
, { "mapping", L_MAPPING }
, { "mixed", L_MIXED }
, { "nomask", L_NO_MASK }
, { "nosave", L_NOSAVE }
, { "object", L_OBJECT }
#ifdef USE_PARSE_COMMAND
, { "parse_command", L_PARSE_COMMAND }
#endif
, { "private", L_PRIVATE }
, { "protected", L_PROTECTED }
, { "public", L_PUBLIC }
, { "return", L_RETURN }
, { "sscanf", L_SSCANF }
, { "static", L_STATIC }
, { "status", L_STATUS }
#ifdef USE_STRUCTS
, { "struct", L_STRUCT }
#endif
, { "string", L_STRING_DECL }
, { "switch", L_SWITCH }
, { "symbol", L_SYMBOL_DECL }
, { "varargs", L_VARARGS }
, { "virtual", L_VIRTUAL }
, { "void", L_VOID }
, { "while", L_WHILE }
};
/*-------------------------------------------------------------------------*/
/* The definitions and tables for the preprocessor expression evaluator.
*/
#define BNOT 1 /* Unary operator opcodes*/
#define LNOT 2
#define UMINUS 3
#define UPLUS 4
#define MULT 1 /* Binary operator opcodes */
#define DIV 2
#define MOD 3
#define BPLUS 4
#define BMINUS 5
#define LSHIFT 6
#define RSHIFT 7
#define LESS 8
#define LEQ 9
#define GREAT 10
#define GEQ 11
#define EQ 12
#define NEQ 13
#define BAND 14
#define XOR 15
#define BOR 16
#define LAND 17
#define LOR 18
#define QMARK 19
/* lookup table for initial operator characters.
* The table covers the characters [' '..'~'].
* 0 for no operator, else index into optab2.
*/
static char _optab[]
= {0,6,0,0,0,46,50,0,0,0,2,18,0,14,0,10,0,0,0,0,0,0,0,0,0,0,0,0,22,42,32,68,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,57,0,1
};
/* Lookup table for the complete operator data in a serial format.
*
* optab2[index-1] : operation code for unary operator, 0 for none.
* optab2[index+0 .. +3 .. +6 ...] :
* two character binary operators: second character, operation code, prio
* one character binary operator & end: 0, operation code, prio
* end: 0, 0
*
* Note that some entries overlap.
*/
static char optab2[]
= { BNOT, 0 /* 1: ~ */
, 0, MULT, 11 /* 2: * */
, LNOT, '=', NEQ, 7 /* 6: !, != */
, 0, 0, DIV, 11 /* 10: / */
, UMINUS, 0, BMINUS, 10 /* 14: -x, x-y */
, UPLUS, 0, BPLUS, 10 /* 18: +x, x+y */
, 0, '<', LSHIFT, 9, '=', LEQ, 8, 0, LESS, 8
/* 22: <<, <=, < */
, 0, '>', RSHIFT, 9, '=', GEQ, 8, 0, GREAT, 8
/* 32: >>, >=, > */
, 0, '=', EQ, 7 /* 42: == */
, 0, 0, MOD, 11 /* 46: % */
, 0, '&', LAND, 3, 0, BAND, 6 /* 50: &&, & */
, 0, '|', LOR, 2, 0, BOR, 4 /* 57: ||, | */
, 0, 0, XOR, 5 /* 64: ^ */
, 0, 0, QMARK, 1 /* 68: ? */
};
#define optab1(c) (_optab[(c)-' '])
/* Use optab1 to index _optab with raw characters.
*/
/*-------------------------------------------------------------------------*/
/* A handy macro to statically determine the number of
* elements in an array.
*/
#define NELEM(a) (sizeof (a) / sizeof (a)[0])
/* Save the character in variable 'c' in the yytext buffer, if
* there is enough space left.
*/
#define SAVEC \
if (yyp < yytext+MAXLINE-5)\
*yyp++ = (char)c;\
else {\
lexerror("Line too long");\
break;\
}
/* The magic character used for function macros to mark the places
* in the replacement text where the macro arguments are to be
* inserted.
* The marking sequence for argument n is { '@', '@'+n+1 }, and
* the character '@' itself is stored as { '@', '@' }.
*/
#define MARKS '@'
/*-------------------------------------------------------------------------*/
/* Forward declarations */
static INLINE int number(long);
static INLINE int string(char *, size_t);
static void handle_define(char *, Bool);
static void add_define(char *, short, char *, source_loc_t);
static void add_permanent_define(char *, short, void *, Bool);
static Bool expand_define(void);
static Bool _expand_define(struct defn*, ident_t*);
static INLINE void myungetc(char);
static int cond_get_exp(int, svalue_t *);
static int exgetc(void);
static char *get_current_file(char **);
static char *get_current_line(char **);
static char *get_version(char **);
static char *get_hostname(char **);
static char *get_domainname(char **);
static char *get_current_dir(char **);
static char *get_sub_path(char **);
static char *efun_defined(char **);
static void lexerrorf VARPROT((char *, ...), printf, 1, 2);
static void lexerror(char *);
static ident_t *lookup_define(char *);
/*-------------------------------------------------------------------------*/
#include "efun_defs.c"
/* struct instr instrs[] = { ... };
*
* Information about all instructions and efuns, generated by make_func.
* Also included are the table for our own ctype functions.
*
* The numbers of arguments are used by the compiler.
* If min == max, then no information has to be coded about the
* actual number of arguments. Otherwise, the actual number of arguments
* will be stored in the byte after the instruction.
* A maximum value of -1 means unlimited maximum value.
*
* If an argument has type 0 (T_INVALID) specified, then no checks will
* be done at run time.
*
* The argument types are checked by the compiler if type checking is enabled,
* and always at runtime.
*/
/*-------------------------------------------------------------------------*/
void
init_lexer(void)
/* Initialize the various lexer tables, including the predefined macros
* from the commandline given in lpc_predefs.
* The lpc_predefs list is deallocated by this call.
*/
{
size_t i, n;
char mtext[MLEN];
/* Allocate enough memory for 20 nested includes/ifs */
lexpool = new_lifopool(size_lifopool( sizeof(lpc_ifstate_t)
+sizeof(struct incstate)));
if (!lexpool)
fatal("Out of memory.\n");
current_loc.file = NULL;
current_loc.line = 0;
/* Clear the table of identifiers */
for (i = 0; i < ITABLE_SIZE; i++)
ident_table[i] = NULL;
/* For every efun, create a global entry in ident_table[] */
for (n = 0; n < NELEM(instrs); n++)
{
ident_t *p;
if (instrs[n].Default == -1)
continue;
/* In !compat mode, skip certain efuns */
if (!compat_mode
&& ( !strcmp(instrs[n].name, "creator")
#ifdef USE_DEPRECATED
|| n == F_TRANSFER
#endif /* USE_DEPRECATED */
)
)
continue;
p = make_shared_identifier(instrs[n].name, I_TYPE_GLOBAL, 0);
if (!p)
fatal("Out of memory\n");
if (p->type != I_TYPE_UNKNOWN)
{
fatal("Duplicate efun '%s'.\n", instrs[n].name);
/* NOTREACHED */
continue;
}
init_global_identifier(p, /* bVariable: */ MY_FALSE);
p->u.global.efun = (short)n;
p->next_all = all_efuns;
all_efuns = p;
}
/* For every reserved word, create a global entry in ident_table[] */
for (i = 0; i < NELEM(reswords); i++)
{
ident_t *p;
p = make_shared_identifier(reswords[i].name, I_TYPE_RESWORD, 0);
if (!p)
fatal("Out of memory\n");
p->type = I_TYPE_RESWORD;
p->u.code = reswords[i].code;
}
/* Add the standard permanent macro definitions */
/* TODO: Make the strings tabled */
add_permanent_define("LPC3", -1, string_copy(""), MY_FALSE);
add_permanent_define("__LDMUD__", -1, string_copy(""), MY_FALSE);
if (compat_mode)
{
add_permanent_define("COMPAT_FLAG", -1, string_copy(""), MY_FALSE);
add_permanent_define("__COMPAT_MODE__", -1, string_copy(""), MY_FALSE);
}
add_permanent_define("__EUIDS__", -1, string_copy(""), MY_FALSE);
if (allow_filename_spaces)
add_permanent_define("__FILENAME_SPACES__", -1, string_copy(""), MY_FALSE);
if (strict_euids)
add_permanent_define("__STRICT_EUIDS__", -1, string_copy(""), MY_FALSE);
if (compat_mode)
{
mtext[0] = '"';
strcpy(mtext+1, master_name);
strcat(mtext+1, "\"");
}
else
{
mtext[0] = '"';
mtext[1] = '/';
strcpy(mtext+2, master_name);
strcat(mtext+2, "\"");
}
add_permanent_define("__MASTER_OBJECT__", -1, string_copy(mtext), MY_FALSE);
add_permanent_define("__FILE__", -1, (void *)get_current_file, MY_TRUE);
add_permanent_define("__DIR__", -1, (void *)get_current_dir, MY_TRUE);
add_permanent_define("__PATH__", 1, (void *)get_sub_path, MY_TRUE);
add_permanent_define("__LINE__", -1, (void *)get_current_line, MY_TRUE);
add_permanent_define("__VERSION__", -1, (void *)get_version, MY_TRUE);
add_permanent_define("__VERSION_MAJOR__", -1, string_copy(VERSION_MAJOR), MY_FALSE);
add_permanent_define("__VERSION_MINOR__", -1, string_copy(VERSION_MINOR), MY_FALSE);
add_permanent_define("__VERSION_MICRO__", -1, string_copy(VERSION_MICRO), MY_FALSE);
add_permanent_define("__VERSION_PATCH__", -1, string_copy("0"), MY_FALSE);
add_permanent_define("__HOST_NAME__", -1, (void *)get_hostname, MY_TRUE);
add_permanent_define("__DOMAIN_NAME__", -1, (void *)get_domainname, MY_TRUE);
add_permanent_define("__HOST_IP_NUMBER__", -1
, (void*)get_host_ip_number, MY_TRUE);
sprintf(mtext, "%d", MAX_USER_TRACE);
add_permanent_define("__MAX_RECURSION__", -1, string_copy(mtext), MY_FALSE);
add_permanent_define("__EFUN_DEFINED__", 1, (void *)efun_defined, MY_TRUE);
#ifdef ERQ_DEMON
sprintf(mtext, "%d", ERQ_MAX_SEND);
add_permanent_define("__ERQ_MAX_SEND__", -1, string_copy(mtext), MY_FALSE);
sprintf(mtext, "%d", ERQ_MAX_REPLY);
add_permanent_define("__ERQ_MAX_REPLY__", -1, string_copy(mtext), MY_FALSE);
#endif
sprintf(mtext, "%"PRIdMPINT, get_memory_limit(MALLOC_HARD_LIMIT));
add_permanent_define("__MAX_MALLOC__", -1, string_copy(mtext), MY_FALSE);
sprintf(mtext, "%"PRId32, def_eval_cost);
add_permanent_define("__MAX_EVAL_COST__", -1, string_copy(mtext), MY_FALSE);
sprintf(mtext, "%ld", (long)CATCH_RESERVED_COST);
add_permanent_define("__CATCH_EVAL_COST__", -1, string_copy(mtext), MY_FALSE);
sprintf(mtext, "%ld", (long)MASTER_RESERVED_COST);
add_permanent_define("__MASTER_EVAL_COST__", -1, string_copy(mtext), MY_FALSE);
sprintf(mtext, "%ld", time_to_reset);
add_permanent_define("__RESET_TIME__", -1, string_copy(mtext), MY_FALSE);
sprintf(mtext, "%ld", time_to_cleanup);
add_permanent_define("__CLEANUP_TIME__", -1, string_copy(mtext), MY_FALSE);
sprintf(mtext, "%ld", alarm_time);
add_permanent_define("__ALARM_TIME__", -1, string_copy(mtext), MY_FALSE);
sprintf(mtext, "%ld", heart_beat_interval);
add_permanent_define("__HEART_BEAT_INTERVAL__", -1, string_copy(mtext), MY_FALSE);
if (synch_heart_beats)
add_permanent_define("__SYNCHRONOUS_HEART_BEAT__", -1, string_copy("1"), MY_FALSE);
sprintf(mtext, "%zu", (size_t)MAX_COMMAND_LENGTH - 1);
add_permanent_define("__MAX_COMMAND_LENGTH__", -1, string_copy(mtext),
MY_FALSE);
#ifdef EVAL_COST_TRACE
add_permanent_define("__EVAL_COST_TRACE__", -1, string_copy("1"), MY_FALSE);
#endif
#ifdef HAS_IDN
add_permanent_define("__IDNA__", -1, string_copy("1"), MY_FALSE);
#endif
#ifdef USE_IPV6
add_permanent_define("__IPV6__", -1, string_copy("1"), MY_FALSE);
#endif
#ifdef USE_MCCP
add_permanent_define("__MCCP__", -1, string_copy("1"), MY_FALSE);
#endif
#ifdef USE_MYSQL
add_permanent_define("__MYSQL__", -1, string_copy("1"), MY_FALSE);
#endif
#ifdef USE_PGSQL
add_permanent_define("__PGSQL__", -1, string_copy("1"), MY_FALSE);
#endif
#ifdef USE_SQLITE
add_permanent_define("__SQLITE__", -1, string_copy("1"), MY_FALSE);
#endif
#ifdef USE_XML
add_permanent_define("__XML_DOM__", -1, string_copy("1"), MY_FALSE);
#endif
#ifdef USE_ALISTS
add_permanent_define("__ALISTS__", -1, string_copy("1"), MY_FALSE);
#endif
add_permanent_define("__PCRE__", -1, string_copy("1"), MY_FALSE);
add_permanent_define("__LPC_NOSAVE__", -1, string_copy("1"), MY_FALSE);
#ifdef USE_DEPRECATED
add_permanent_define("__DEPRECATED__", -1, string_copy("1"), MY_FALSE);
#endif
#ifdef USE_STRUCTS
add_permanent_define("__LPC_STRUCTS__", -1, string_copy("1"), MY_FALSE);
#endif
#ifdef USE_NEW_INLINES
add_permanent_define("__LPC_INLINE_CLOSURES__", -1, string_copy("1"), MY_FALSE);
#endif
#ifdef USE_ARRAY_CALLS
add_permanent_define("__LPC_ARRAY_CALLS__", -1, string_copy("1"), MY_FALSE);
#endif
#ifdef USE_TLS
add_permanent_define("__TLS__", -1, string_copy("1"), MY_FALSE);
#ifdef HAS_GNUTLS
add_permanent_define("__GNUTLS__", -1, string_copy("1"), MY_FALSE);
#endif
#ifdef HAS_OPENSSL
add_permanent_define("__OPENSSL__", -1, string_copy("1"), MY_FALSE);
#endif
#endif
#ifdef USE_GCRYPT
add_permanent_define("__GCRYPT__", -1, string_copy("1"), MY_FALSE);
#endif
if (wizlist_name[0] != '\0')
{
if (compat_mode)
{
mtext[0] = '"';
strcpy(mtext+1, wizlist_name);
strcat(mtext+1, "\"");
}
else
{
mtext[0] = '"';
mtext[1] = '/';
strcpy(mtext+2, wizlist_name);
strcat(mtext+2, "\"");
}
add_permanent_define("__WIZLIST__", -1, string_copy(mtext), MY_FALSE);
}
sprintf(mtext, "(%"PRIdPINT")", PINT_MAX);
add_permanent_define("__INT_MAX__", -1, string_copy(mtext), MY_FALSE);
sprintf(mtext, "(%"PRIdPINT")", PINT_MIN);
add_permanent_define("__INT_MIN__", -1, string_copy(mtext), MY_FALSE);
sprintf(mtext, "(%g)", DBL_MAX);
add_permanent_define("__FLOAT_MAX__", -1, string_copy(mtext), MY_FALSE);
sprintf(mtext, "(%g)", DBL_MIN);
add_permanent_define("__FLOAT_MIN__", -1, string_copy(mtext), MY_FALSE);
sprintf(mtext, "%"PRIdMPINT, get_current_time());
add_permanent_define("__BOOT_TIME__", -1, string_copy(mtext), MY_FALSE);
/* Add the permanent macro definitions given on the commandline */
while (NULL != lpc_predefs)
{
char namebuf[NSIZE];
struct lpc_predef_s *tmpf;
tmpf = lpc_predefs;
lpc_predefs = lpc_predefs->next;
*mtext = '\0';
sscanf(tmpf->flag, "%[^=]=%[ -~=]", namebuf, mtext);
if ( strlen(namebuf) >= NSIZE )
fatal("-D%s: macroname too long (>%d)\n", tmpf->flag, NSIZE);
if ( strlen(mtext) >= MLEN )
fatal("-D%s: macrotext too long (>%d)\n", tmpf->flag, MLEN);
add_permanent_define(namebuf, -1, string_copy(mtext), MY_FALSE);
xfree(tmpf->flag);
xfree(tmpf);
}
} /* init_lexer() */
/*-------------------------------------------------------------------------*/
int
symbol_operator (const char *symbol, const char **endp)
/* Analyse the text starting at <symbol> (which points to the first character
* after the assumed "#'") if it describes a closure symbol. If yes, return
* the operator code and set *<endp> to the first character after the
* recognized operator.
* If no operator can be recognized, return -1 and set *<endp> to <symbol>.
*
* The function is called from ed.c and from symbol_efun().
*
* Recognized are the following operators:
*
* #'+= -> F_ADD_EQ
* #'++ -> F_POST_INC
* #'+ -> F_ADD
* #'-= -> F_SUB_EQ
* #'-- -> F_POST_DEC
* #'- -> F_SUBTRACT
* #'*= -> F_MULT_EQ
* #'* -> F_MULTIPLY
* #'/= -> F_DIV_EQ
* #'/ -> F_DIVIDE
* #'%= -> F_MOD_EQ
* #'% -> F_MOD
* #', -> F_POP_VALUE
* #'^= -> F_XOR_EQ
* #'^ -> F_XOR
* #'|| -> F_LOR
* #'||= -> F_LOR_EQ
* #'|= -> F_OR_EQ
* #'| -> F_OR
* #'&& -> F_LAND
* #'&&= -> F_LAND_EQ
* #'&= -> F_AND_EQ
* #'& -> F_AND
* #'~ -> F_COMPL
* #'<= -> F_LE
* #'<<= -> F_LSH_EQ
* #'<< -> F_LSH
* #'< -> F_LT
* #'>= -> F_GE
* #'>>= -> F_RSH_EQ
* #'>>>= -> F_RSHL_EQ
* #'>>> -> F_RSHL
* #'>> -> F_RSH
* #'> -> F_GT
* #'== -> F_EQ
* #'= -> F_ASSIGN
* #'!= -> F_NE
* #'! -> F_NOT
* #'?! -> F_BRANCH_WHEN_NON_ZERO
* #'? -> F_BRANCH_WHEN_ZERO
* #'[..] -> F_RANGE
* #'[..<] -> F_NR_RANGE
* #'[<..] -> F_RN_RANGE
* #'[<..<] -> F_RR_RANGE
* #'[..>] -> F_NA_RANGE
* #'[>..] -> F_AN_RANGE
* #'[<..>] -> F_RA_RANGE
* #'[>..<] -> F_AR_RANGE
* #'[>..>] -> F_AA_RANGE
* #'[.. -> F_NX_RANGE
* #'[<.. -> F_RX_RANGE
* #'[>.. -> F_AX_RANGE
* #'[,] -> F_MAP_INDEX
* #'[ -> F_INDEX
* #'[< -> F_RINDEX
* #'[> -> F_AINDEX
* #'({ -> F_AGGREGATE
* #'([ -> F_M_CAGGREGATE
#ifdef USE_STRUCTS
* #'-> -> F_S_INDEX
* #'(< -> F_S_AGGREGATE
#endif
*
* Note that all operators must have a instrs[].Default value of '0'.
* If necessary, update the lex::init_lexer()::binary_operators[] to
* include the operator values.
*/
{
char c;
int ret;
switch(*symbol)
{
case '+':
c = symbol[1];
if (c == '=')
{
symbol++;
ret = F_ADD_EQ;
break;
}
else if (c == '+')
{
symbol++;
ret = F_POST_INC;
break;
}
ret = F_ADD;
break;
case '-':
c = symbol[1];
if (c == '=')
{
symbol++;
ret = F_SUB_EQ;
break;
}
else if (c == '-')
{
symbol++;
ret = F_POST_DEC;
break;
}
#ifdef USE_STRUCTS
else if (c == '>')
{
symbol++;
ret = F_S_INDEX;
break;
}
#endif /* USE_STRUCTS */
ret = F_SUBTRACT;
break;
case '*':
if (symbol[1] == '=')
{
symbol++;
ret = F_MULT_EQ;
break;
}
ret = F_MULTIPLY;
break;
case '/':
if (symbol[1] == '=')
{
symbol++;
ret = F_DIV_EQ;
break;
}
ret = F_DIVIDE;
break;
case '%':
if (symbol[1] == '=')
{
symbol++;
ret = F_MOD_EQ;
break;
}
ret = F_MOD;
break;
case ',':
ret = F_POP_VALUE;
break;
case '^':
if (symbol[1] == '=')
{
symbol++;
ret = F_XOR_EQ;
break;
}
ret = F_XOR;
break;
case '|':
c = *++symbol;
if (c == '|')
{
if (symbol[1] == '=')
{
symbol++;
ret = F_LOR_EQ;
}
else
ret = F_LOR;
break;
}
else if (c == '=')
{
ret = F_OR_EQ;
break;
}
symbol--;
ret = F_OR;
break;
case '&':
c = *++symbol;
if (c == '&')
{
if (symbol[1] == '=')
{
symbol++;
ret = F_LAND_EQ;
}
else
ret = F_LAND;
break;
}
else if (c == '=')
{
ret = F_AND_EQ;
break;
}
symbol--;
ret = F_AND;
break;
case '~':
ret = F_COMPL;
break;
case '<':
c = *++symbol;
if (c == '=')
{
ret = F_LE;
break;
}
else if (c == '<')
{
if (symbol[1] == '=')
{
symbol++;
ret = F_LSH_EQ;
break;
}
ret = F_LSH;
break;
}
symbol--;
ret = F_LT;
break;
case '>':
c = *++symbol;
if (c == '=')
{
ret = F_GE;
break;
}
else if (c == '>')
{
if (symbol[1] == '=')
{
symbol++;
ret = F_RSH_EQ;
break;
}
if (symbol[1] == '>')
{
symbol++;
if (symbol[1] == '=')
{
symbol++;
ret = F_RSHL_EQ;
break;
}
ret = F_RSHL;
break;
}
ret = F_RSH;
break;
}
symbol--;
ret = F_GT;
break;
case '=':
if (symbol[1] == '=')
{
symbol++;
ret = F_EQ;
break;
}
ret = F_ASSIGN;
break;
case '!':
if (symbol[1] == '=')
{
symbol++;
ret = F_NE;
break;
}
ret = F_NOT;
break;
case '?':
if (symbol[1] == '!')
{
symbol++;
ret = F_BRANCH_WHEN_NON_ZERO;
break;
}
ret = F_BRANCH_WHEN_ZERO;
break;
case '[':
c = *++symbol;
if (c == '<')
{
if (symbol[1] == '.' && symbol[2] == '.')
{
c = *(symbol+=3);
if (c == ']')
{
ret = F_RN_RANGE;
break;
}
else if (c == '>' && symbol[1] == ']')
{
symbol++;
ret = F_RA_RANGE;
break;
}
else if (c == '<' && symbol[1] == ']')
{
symbol++;
ret = F_RR_RANGE;
break;
}
symbol--;
ret = F_RX_RANGE;
break;
}
ret = F_RINDEX;
break;
}
else if (c == '>')
{
if (symbol[1] == '.' && symbol[2] == '.')
{
c = *(symbol+=3);
if (c == ']')
{
ret = F_AN_RANGE;
break;
}
else if (c == '>' && symbol[1] == ']')
{
symbol++;
ret = F_AA_RANGE;
break;
}
else if (c == '<' && symbol[1] == ']')
{
symbol++;
ret = F_AR_RANGE;
break;
}
symbol--;
ret = F_AX_RANGE;
break;
}
ret = F_AINDEX;
break;
}
else if (c == '.' && symbol[1] == '.')
{
c = *(symbol+=2);
if (c == ']') {
ret = F_RANGE;
break;
} else if (c == '>' && symbol[1] == ']') {
symbol++;
ret = F_NA_RANGE;
break;
} else if (c == '<' && symbol[1] == ']') {
symbol++;
ret = F_NR_RANGE;
break;
}
symbol--;
ret = F_NX_RANGE;
break;
}
else if (c == ',' && symbol[1] == ']')
{
symbol++;
ret = F_MAP_INDEX;
break;
}
symbol--;
ret = F_INDEX;
break;
case '(':
c = *++symbol;
if (c == '{')
{
ret = F_AGGREGATE;
break;
}
else if (c == '[')
{
ret = F_M_CAGGREGATE;
break;
}
#ifdef USE_STRUCTS
else if (c == '<')
{
ret = F_S_AGGREGATE;
break;
}
#endif /* USE_STRUCTS */
symbol--;
/* FALL THROUGH */
default:
ret = -1;
symbol--;
break;
}
/* Symbol is not an operator */
*endp = symbol+1;
return ret;
} /* symbol_operator() */
/*-------------------------------------------------------------------------*/
static INLINE int
symbol_resword (ident_t *p)
/* This function implements the resword lookup for closures.
*
* If ident <p> is a reserved word with a closure representation, return
* the corresponding instruction code:
*
* #'if -> F_BRANCH_WHEN_ZERO
* #'do -> F_BBRANCH_WHEN_NON_ZERO
* #'while -> F_BBRANCH_WHEN_ZERO
* #'foreach -> F_FOREACH
* #'continue -> F_BRANCH
* #'default -> F_CSTRING0
* #'switch -> F_SWITCH
* #'break -> F_BREAK
* #'return -> F_RETURN
* #'sscanf -> F_SSCANF
* #'catch -> F_CATCH
*
* If ident <p> is not a reserved word, or a word without closure
* representation, return 0.
*/
{
int code = 0;
if (p->type != I_TYPE_RESWORD)
return 0;
switch(p->u.code)
{
default:
/* Unimplemented reserved word */
code = 0;
break;
case L_IF:
code = F_BRANCH_WHEN_ZERO;
break;
case L_DO:
code = F_BBRANCH_WHEN_NON_ZERO;
break;
case L_WHILE:
/* the politically correct code was already taken, see above. */
code = F_BBRANCH_WHEN_ZERO;
break;
case L_FOREACH:
code = F_FOREACH;
break;
case L_CONTINUE:
code = F_BRANCH;
break;
case L_DEFAULT:
code = F_CSTRING0;
break;
case L_SWITCH:
code = F_SWITCH;
break;
case L_BREAK:
code = F_BREAK;
break;
case L_RETURN:
code = F_RETURN;
break;
case L_SSCANF:
code = F_SSCANF;
break;
#ifdef USE_PARSE_COMMAND
case L_PARSE_COMMAND:
code = F_PARSE_COMMAND;
break;
#endif
case L_CATCH:
code = F_CATCH;
break;
}
return code;
} /* symbol_resword() */
/*-------------------------------------------------------------------------*/
void
symbol_efun_str (const char * str, size_t len, svalue_t *sp, Bool is_efun)
/* This function implements the efun/operator/sefun part of efun
* symbol_function().
*
* It is also called by parse_command to lookup the (simul)efuns find_living()
* and find_player() at runtime, and by restore_svalue().
*
* The function takes the string <str> of length <len> and looks up the named
* efun, sefun or operator. If the efun/operator is found, the value <sp> is
* turned into the proper closure value, otherwise it is set to the numeric
* value 0. If <is_efun> is TRUE, <str> is resolved as an efun even if it
* doesn't contain the 'efun::' prefix.
*
* inter_sp must be set properly before the call.
*
* Accepted symbols are:
*
* #'<operator>: see lex::symbol_operator()
*
* #'if -> F_BRANCH_WHEN_ZERO +CLOSURE_OPERATOR
* #'do -> F_BBRANCH_WHEN_NON_ZERO +CLOSURE_OPERATOR
* #'while -> F_BBRANCH_WHEN_ZERO +CLOSURE_OPERATOR
* #'foreach -> F_FOREACH +CLOSURE_OPERATOR
* #'continue -> F_BRANCH +CLOSURE_OPERATOR
* #'default -> F_CSTRING0 +CLOSURE_OPERATOR
* #'switch -> F_SWITCH +CLOSURE_OPERATOR
* #'break -> F_BREAK +CLOSURE_OPERATOR
* #'return -> F_RETURN +CLOSURE_OPERATOR
* #'sscanf -> F_SSCANF +CLOSURE_OPERATOR
* #'catch -> F_CATCH +CLOSURE_OPERATOR
*
* #'<efun> -> F_<efun> +CLOSURE_EFUN
* #'<sefun> -> <function-index> +CLOSURE_SIMUL_EFUN
*/
{
Bool efun_override = is_efun;
/* If the first character is alphanumeric, the string names a function,
* otherwise an operator.
*/
if (isalunum(*str))
{
/* It is a function or keyword.
*/
ident_t *p;
char *cstr;
/* Take care of an leading efun override */
if ( len >= 6 && !strncmp(str, "efun::", 6) )
{
str += 6;
len -= 6;
efun_override = MY_TRUE;
}
/* Convert the string_t into a C string for local purposes */
cstr = alloca(len+1);
if (!cstr)
{
outofmem(len, "identifier");
}
memcpy(cstr, str, len);
cstr[len] = '\0';
/* Lookup the identifier in the string in the global table
* of identifers.
*/
if ( !(p = make_shared_identifier(cstr, I_TYPE_GLOBAL, 0)) )
{
outofmem(len, "identifier");
}
/* Loop through the possible multiple definitions.
*/
while (p->type > I_TYPE_GLOBAL)
{
/* Is it a reserved word? */
if (p->type == I_TYPE_RESWORD)
{
int code = symbol_resword(p);
if (!code)
{
/* Unimplemented reserved word */
if ( NULL != (p = p->inferior) )
continue;
goto undefined_function;
}
/* Got the reserved word: return the closure value */
sp->type = T_CLOSURE;
sp->x.closure_type = (short)(code + CLOSURE_OPERATOR);
sp->u.ob = ref_object(current_object, "symbol_efun");
return;
}
if ( !(p = p->inferior) )
break; /* Found a valid definition */
}
/* It is a real identifier */
if (!p || p->type < I_TYPE_GLOBAL
|| (( efun_override || p->u.global.sim_efun < 0 )
&& p->u.global.efun < 0)
)
{
/* But it's a (new) local identifier or a non-existing function */
if (p && p->type == I_TYPE_UNKNOWN)
free_shared_identifier(p);
undefined_function:
put_number(sp, 0);
return;
}
/* Attempting to override a 'nomask' simul efun?
* Check it with a privilege violation.
*/
if (efun_override && p->u.global.sim_efun >= 0
&& simul_efunp[p->u.global.sim_efun].flags & TYPE_MOD_NO_MASK)
{
svalue_t *res;
push_ref_string(inter_sp, STR_NOMASK_SIMUL_EFUN);
push_ref_valid_object(inter_sp, current_object, "nomask simul_efun");
push_ref_string(inter_sp, p->name);
res = apply_master(STR_PRIVILEGE, 3);
if (!res || res->type != T_NUMBER || res->u.number < 0)
{
/* Override attempt is fatal */
errorf(
"Privilege violation: nomask simul_efun %s\n",
get_txt(p->name)
);
}
else if (!res->u.number)
{
/* Override attempt not fatal, but rejected nevertheless */
efun_override = MY_FALSE;
}
}
/* Symbol is ok - create the closure value */
sp->type = T_CLOSURE;
if (!efun_override && p->u.global.sim_efun >= 0)
{
/* Handle non-overridden simul efuns */
sp->x.closure_type = (short)(p->u.global.sim_efun + CLOSURE_SIMUL_EFUN);
sp->u.ob = ref_object(current_object, "symbol_efun");
}
else
{
/* Handle efuns (possibly aliased).
* We know that p->u.global.efun >= 0 here.
*/
sp->x.closure_type = (short)(p->u.global.efun + CLOSURE_EFUN);
if (sp->x.closure_type > LAST_INSTRUCTION_CODE + CLOSURE_EFUN)
sp->x.closure_type = (short)(CLOSURE_EFUN +
efun_aliases[
sp->x.closure_type - CLOSURE_EFUN - LAST_INSTRUCTION_CODE - 1]);
sp->u.ob = ref_object(current_object, "symbol_efun");
}
}
else
{
int i;
const char *end;
i = symbol_operator(str, &end);
/* If there was a valid operator with trailing junk, *end, but i >= 0.
* On the other hand, if we passed the empty string, i < 0, but !*end.
* Thus, we have to test for (*end || i < 0) .
*/
if (*end || i < 0)
{
put_number(sp, 0);
return;
}
sp->type = T_CLOSURE;
if (instrs[i].Default == -1) {
sp->x.closure_type = (short)(i + CLOSURE_OPERATOR);
} else {
sp->x.closure_type = (short)(i + CLOSURE_EFUN);
}
sp->u.ob = ref_object(current_object, "symbol_efun");
}
} /* symbol_efun_str() */
/*-------------------------------------------------------------------------*/
void
symbol_efun (string_t *name, svalue_t *sp)
/* This function is a wrapper around symbol_efun_str(), taking a regular
* string <name> as argument.
*/
{
symbol_efun_str(get_txt(name), mstrsize(name), sp, MY_FALSE);
} /* symbol_efun() */
/*-------------------------------------------------------------------------*/
source_file_t *
new_source_file (const char * name, source_loc_t * parent)
/* Create a new source_file structure for file <name>.
*
* If <name> is non-NULL, a new string is allocated and the content of <name>
* is copied. If <name> is NULL, the caller has to set the filename in
* the returned structure.
*
* If <parent> is non-NULL, it denotes the parent file location this source was
* included from.
*
* Result is the new structure, or NULL if out of memory.
*
* Once allocated, the structure can be removed only through the general
* cleanup routined cleanup_source_files().
*/
{
source_file_t * rc;
rc = xalloc(sizeof(*rc));
if (!rc)
return NULL;
if (name)
{
rc->name = string_copy(name);
if (!rc->name)
{
xfree(rc);
return NULL;
}
}
else
rc->name = NULL;
if (parent)
rc->parent = *parent;
else
{
rc->parent.file = NULL;
rc->parent.line = 0;
}
rc->next = src_file_list;
src_file_list = rc;
return rc;
} /* new_source_file() */
/*-------------------------------------------------------------------------*/
static void
cleanup_source_files (void)
/* Deallocate all listed source_file structures.
*/
{
source_file_t * this;
while ((this = src_file_list) != NULL)
{
src_file_list = this->next;
if (this->name)
xfree(this->name);
xfree(this);
}
current_loc.file = NULL;
current_loc.line = 0;
} /* cleanup_source_files() */
/*-------------------------------------------------------------------------*/
void
init_global_identifier (ident_t * ident, Bool bVariable)
/* The (newly created or to be reused) identifier <ident> is set up
* to be a global identifier, with all the .global.* fields set to
* a suitable default. The caller has to fill in the information specifying
* what kind of global this is.
*
* <bVariable> is to be TRUE if the caller intends to use the identifier
* for a (local or global) variable or lfun; and FALSE if it is for a
* efun/sefun.
*
* The function is rather small, but having it here makes it easier to
* guarantee that all fields are set to a proper default.
*/
{
ident->type = I_TYPE_GLOBAL;
ident->u.global.function = I_GLOBAL_FUNCTION_OTHER;
if (bVariable)
ident->u.global.variable = I_GLOBAL_VARIABLE_OTHER;
else
ident->u.global.variable = I_GLOBAL_VARIABLE_FUN;
ident->u.global.efun = I_GLOBAL_EFUN_OTHER;
ident->u.global.sim_efun = I_GLOBAL_SEFUN_OTHER;
#ifdef USE_STRUCTS
ident->u.global.struct_id = I_GLOBAL_STRUCT_NONE;
#endif
} /* init_global_identifier() */
/*-------------------------------------------------------------------------*/
ident_t *
lookfor_shared_identifier (char *s, int n, int depth, Bool bCreate)
/* Aliases: make_shared_identifier(): bCreate passed as MY_TRUE
* find_shared_identifier(): bCreate passed as MY_FALSE
*
* Find and/or add identifier <s> of type <n> to the ident_table, and
* return a pointer to the found/generated struct ident. Local identifiers
* (<n> == I_TYPE_LOCAL) are additionally distinguished by their definition
* <depth>.
*
* If bCreate is FALSE, the function just checks if the given identfier
* exists in the table. The identifier is considered found, if there
* is an entry in the table for this very name, and with a type equal
* or greater than <n>. If <n> is LOCAL and the found identifier is LOCAL
* as well, the identifier is considered found if <depth> is equal or smaller
* than the depth of the found identifier. The result is the pointer to the
* found identifier, or NULL if not found.
*
* If bCreate is TRUE, the identifier is created if not found. If an
* identifier with the same name but a lower type exists in the table,
* it is shifted down: a new entry for this name created and put into the
* table, the original entry is referenced by the .inferior pointer in the
* new entry. The same happens when a new LOCAL of greater depth is
* added to an existing LOCAL of smaller depth. New generated
* entries have their type set to I_TYPE_UNKNOWN regardless of <n>.
* The result is the pointer to the found/new entry, or NULL when out
* of memory.
*/
{
ident_t *curr, *prev;
int h;
string_t *str;
#if defined(LEXDEBUG)
printf("%s lookfor_shared_identifier called: %s\n", time_stamp(), s);
#endif
h = identhash(s); /* the identifiers hash code */
/* look for the identifier in the table */
curr = ident_table[h];
prev = NULL;
while (curr)
{
#if defined(LEXDEBUG)
printf("%s checking %s.\n", time_stamp(), get_txt(curr->name));
#endif
if (!strcmp(get_txt(curr->name), s)) /* found it */
{
#if defined(LEXDEBUG)
printf("%s -> found.\n", time_stamp());
#endif
/* Move the found entry to the head of the chain */
if (prev) /* not at head of chain */
{
prev->next = curr->next;
curr->next = ident_table[h];
ident_table[h] = curr;
}
/* If the found entry is of inferior type, shift it down */
if (n > curr->type
|| ( I_TYPE_LOCAL == curr->type && I_TYPE_LOCAL == n
&& depth > curr->u.local.depth)
)
{
if (bCreate)
{
ident_t *inferior = curr;
#if defined(LEXDEBUG)
printf("%s shifting down inferior.\n", time_stamp());
#endif
curr = xalloc(sizeof *curr);
if ( NULL != curr )
{
curr->name = ref_mstring(inferior->name);
curr->next = inferior->next;
curr->type = I_TYPE_UNKNOWN;
curr->inferior = inferior;
curr->hash = (short)h;
ident_table[h] = curr;
}
}
else
curr = NULL;
}
/* Return the found (or generated) entry */
return curr;
}
prev = curr;
curr = curr->next;
}
if (bCreate)
{
/* Identifier is not in table, so create a new entry */
str = new_tabled(s);
if (!str)
return NULL;
curr = xalloc(sizeof *curr);
if (!curr)
{
free_mstring(str);
return NULL;
}
curr->name = str;
curr->next = ident_table[h];
curr->type = I_TYPE_UNKNOWN;
curr->inferior = NULL;
curr->hash = (short)h;
ident_table[h] = curr;
}
/* else curr is NULL */
return curr;
} /* lookfor_shared_identifier() */
/*-------------------------------------------------------------------------*/
ident_t *
make_global_identifier (char *s, int n)
/* Create an identifier <s> on level I_TYPE_GLOBAL, after searching for it
* using type <n>.
*
* The difference to make_shared_identifier() is that if an identifier for
* this name already exists and is of higher level than I_TYPE_GLOBAL (e.g.
* somebody created a #define for this name), the function will insert
* an appropriate I_TYPE_GLOBAL entry into the inferior list.
*
* Result is the pointer to the identifier, or NULL when out of memory
* (yyerror() is called in that situation, too).
*/
{
ident_t *ip, *q;
ip = make_shared_identifier(s, n, 0);
if (!ip)
{
yyerrorf("Out of memory: identifer '%s'", s);
return NULL;
}
if (ip->type > I_TYPE_GLOBAL)
{
/* Somebody created a #define with this name.
* Back-insert an ident-table entry.
*/
do {
q = ip;
ip = ip->inferior;
} while (ip && ip->type > I_TYPE_GLOBAL);
if (!ip)
{
ip = xalloc(sizeof(ident_t));
if (!ip) {
yyerrorf("Out of memory: identifier (%zu bytes)",
sizeof(ident_t));
return NULL;
}
ip->name = ref_mstring(q->name);
ip->type = I_TYPE_UNKNOWN;
ip->inferior = NULL;
ip->hash = q->hash;
q->inferior = ip;
}
}
return ip;
} /* make_global_identifier() */
/*-------------------------------------------------------------------------*/
static INLINE void
free_identifier (ident_t *p)
/* Deallocate the identifier <p> which must not be in any list or table
* anymore.
* It is a fatal error if it can't be found.
*/
{
free_mstring(p->name);
xfree(p);
} /* free_identifier() */
/*-------------------------------------------------------------------------*/
static INLINE void
unlink_shared_identifier (ident_t *p)
/* Unlink the identifier <p> (which may be an inferior entry ) from the
* identifier table.
* It is a fatal error if it can't be found.
*/
{
ident_t *curr, **q;
int h;
string_t *s;
h = p->hash;
q = &ident_table[h];
curr = *q;
s = p->name;
#if defined(LEXDEBUG)
printf("%s unlinking '%s'\n", time_stamp(), get_txt(s));
fflush(stdout);
#endif
/* Look for the hashed entry with the same name */
while (curr)
{
if (curr->name == s
#ifdef DEBUG
|| mstreq(curr->name, s)
#endif
) /* found matching name */
{
ident_t *first = curr;
/* Search the list of inferiors for entry <p> */
while (curr)
{
if (curr == p) /* this is the right one */
{
/* Remove the entry from the inferior list */
if (first == curr)
{
if (curr->inferior)
{
curr->inferior->next = curr->next;
*q = curr->inferior;
return; /* success */
}
*q = curr->next;
return;
}
*q = curr->inferior;
return; /* success */
}
q = &curr->inferior;
curr = *q;
}
fatal("free_shared_identifier: entry '%s' not found!\n"
, get_txt(p->name));
/* NOTREACHED */
}
q = &curr->next;
curr = *q;
} /* not found */
fatal("free_shared_identifier: name '%s' not found!\n", get_txt(p->name));
/* NOTREACHED */
} /* unlink_shared_identifier() */
/*-------------------------------------------------------------------------*/
void
free_shared_identifier (ident_t *p)
/* Remove the identifier <p> (which may be an inferior entry ) from the
* identifier table.
* It is a fatal error if it can't be found.
*/
{
#if defined(LEXDEBUG)
printf("%s freeing '%s'\n", time_stamp(), get_txt(p->name));
fflush(stdout);
#endif
unlink_shared_identifier(p);
free_identifier(p);
} /* free_shared_identifier() */
/*-------------------------------------------------------------------------*/
static void
realloc_defbuf (void)
/* Increase the size of defbuf[] (unless it would exceed MAX_TOTAL_BUF).
* The old content of defbuf[] is copied to the end of the new buffer.
* outp is corrected to the new position, other pointers into defbuf
* become invalid.
*/
{
char * old_defbuf = defbuf;
size_t old_defbuf_len = defbuf_len;
char * old_outp = outp;
ptrdiff_t outp_off;
if (MAX_TOTAL_BUF <= defbuf_len)
return;
outp_off = &defbuf[defbuf_len] - outp;
/* Double the current size of defbuf, but top off at MAX_TOTAL_BUF. */
if (defbuf_len > (MAX_TOTAL_BUF >> 1) )
{
defbuf_len = MAX_TOTAL_BUF;
} else {
defbuf_len <<= 1;
}
if (comp_flag)
fprintf(stderr, "%s (reallocating defbuf from %zu (%td left) to %lu) "
, time_stamp(), old_defbuf_len, (ptrdiff_t)(old_outp-defbuf)
, defbuf_len);
defbuf = xalloc(defbuf_len);
memcpy(defbuf+defbuf_len-old_defbuf_len, old_defbuf, old_defbuf_len);
xfree(old_defbuf);
outp = &defbuf[defbuf_len] - outp_off;
} /* realloc_defbuf() */
/*-------------------------------------------------------------------------*/
static void
set_input_source (int fd, string_t * str)
/* Set the current input source to <fd>/<str>.
* If <str> is given, it will be referenced.
*/
{
yyin.fd = fd;
yyin.str = str ? ref_mstring(str) : NULL;
yyin.current = 0;
} /* set_input_source() */
/*-------------------------------------------------------------------------*/
static void
close_input_source (void)
/* Close the current input source: a file is closed, a string is deallocated
*/
{
if (yyin.fd != -1) close(yyin.fd); yyin.fd = -1;
if (yyin.str != NULL) free_mstring(yyin.str); yyin.str = NULL;
yyin.current = 0;
} /* close_input_source() */
/*-------------------------------------------------------------------------*/
static /* NO inline */ char *
_myfilbuf (void)
/* Read the next MAXLINE bytes from the input source <yyin> and store
* them in the input-buffer. If there were the beginning of an incomplete
* line left in the buffer, they are copied right before linebufstart.
* The end of the last complete line in the buffer is marked with a '\0'
* sentinel, or, if the file is exhausted, the end of data is marked
* with the CHAR_EOF char.
*
* outp is set to point to the new data (which may be the copied remnants
* from the incomplete line) and also returned as result.
*
* The function must not be called unless all lines in the buffer have
* been processed. This macro */
#define myfilbuf() (*outp?0:_myfilbuf())
/* takes care of that.
*/
{
int i;
char *p;
/* Restore the data clobbered by the old sentinel */
*outp = saved_char;
/* Copy any remnants of an incomplete line before the buffer begin
* and reset outp.
*/
if (linebufend < outp)
fatal("(lex.c) linebufend %p < outp %p\n", linebufend, outp);
if (linebufend - outp)
memcpy(outp-MAXLINE, outp, (size_t)(linebufend - outp));
outp -= MAXLINE;
*(outp-1) = '\n'; /* so an ungetc() gives a sensible result */
/* Read the next block of data */
p = linebufstart; /* == linebufend - MAXLINE */
if (yyin.fd != -1)
i = read(yyin.fd, p, MAXLINE);
else
{
i = mstrsize(yyin.str) - yyin.current;
if (i > MAXLINE)
i = MAXLINE;
memcpy(p, get_txt(yyin.str)+yyin.current, i);
yyin.current += i;
}
if (i < MAXLINE)
{
/* End of file or error: put in the final EOF marker */
if (i < 0)
{
i = 0;
}
p += i;
if (p - outp ? p[-1] != '\n' : current_loc.line == 1)
*p++ = '\n';
*p++ = CHAR_EOF;
return outp;
}
/* Buffer filled: mark the last line with the '\0' sentinel */
p += i;
while (*--p != '\n') NOOP; /* find last newline */
if (p < linebufstart)
{
lexerror("line too long");
*(p = linebufend-1) = '\n';
}
p++;
saved_char = *p;
*p = '\0';
return outp;
} /* _myfilbuf() */
/*-------------------------------------------------------------------------*/
static void
add_input (char *p)
/* Copy the text <p> into defbuf[] right before the current position of
* outp and set outp back to point at the beginning of the new text.
*
* Main use is by the macro expansion routines.
*/
{
size_t l = strlen(p);
#if defined(LEXDEBUG)
if (l > 0)
fprintf(stderr, "%s add '%s'\n", time_stamp(), p);
#endif
if ((ptrdiff_t)l > outp - &defbuf[10])
{
lexerror("Macro expansion buffer overflow");
return;
}
outp -= l;
strncpy(outp, p, l);
}
/*-------------------------------------------------------------------------*/
static INLINE char
mygetc (void)
/* Retrieve the next character from the file input buffer.
*/
{
#if 0
fprintf(stderr, "c='%c' %x, ", *outp, *outp);
#endif
#if defined(LEXDEBUG)
putc(*outp, stderr);
fflush(stderr);
#endif
return *outp++;
}
/*-------------------------------------------------------------------------*/
static INLINE void
myungetc (char c)
/* Store character <c> in the file input buffer so the next mygetc()
* can retrieve it.
*/
{
*--outp = c;
}
/*-------------------------------------------------------------------------*/
static INLINE Bool
gobble (char c)
/* Skip the next character in the input buffer if it is <c> and return true.
* If the next character is not <c>, don't advance in the buffer and
* return false.
*/
{
if (c == mygetc())
return MY_TRUE;
--outp;
return MY_FALSE;
}
/*-------------------------------------------------------------------------*/
static void
lexerrorf (char *format, ...)
/* Generate an lexerror() using printf()-style arguments.
*/
{
va_list va;
char buff[5120];
char fixed_fmt[1000];
format = limit_error_format(fixed_fmt, sizeof(fixed_fmt), format);
va_start(va, format);
vsprintf(buff, format, va);
va_end(va);
lexerror(buff);
} /* lexerrorf() */
/*-------------------------------------------------------------------------*/
static void
lexerror (char *s)
/* The lexer encountered fatal error <s>. Print the error via yyerror()
* and set lex_fatal.
*/
{
yyerror(s);
lex_fatal = MY_TRUE;
}
/*-------------------------------------------------------------------------*/
static Bool
skip_to (char *token, char *atoken)
/* Skip the file linewise until one of the following preprocessor statements
* is encountered:
* #<token> : returns true, outp is set to the following line.
* #<atoken>: returns false, outp is set to the following line.
* #elif : returns false, the statement is rewritten to #if and
* outp is set to point to the '#' in the new statement.
* If an end of file occurs, an error is generated and the function returns
* true after setting outp to the character before the CHAR_EOF.
*
* Nested #if ... #endif blocks are skipped altogether.
*
* <atoken> may be the NULL pointer and is ignored in that case.
*/
{
char *p; /* Local copy of outp */
char *q; /* The start of the preprocessor statement */
char c;
char nl = '\n';
int nest; /* Current nesting depth of #if...#endif blocks */
p = outp;
for (nest = 0; ; ) {
current_loc.line++;
total_lines++;
c = *p++;
if (c == '#')
{
/* Parse the preprocessor statement */
/* Set q to the first non-blank character of the keyword */
while(lexwhite(*p++)) NOOP;
q = --p;
/* Mark the end of the preprocessor keyword with \0 */
while (isalunum(*p++)) NOOP;
c = *--p; /* needed for eventual undos */
*p = '\0';
/* Set p to the first character of the next line */
if (c != nl)
{
while (*++p != nl) NOOP;
}
p++;
/* Evaluate the token at <q> */
if (strcmp(q, "if") == 0
|| strcmp(q, "ifdef") == 0
|| strcmp(q, "ifndef") == 0)
{
nest++;
}
else if (nest > 0)
{
if (strcmp(q, "endif") == 0)
nest--;
}
else
{
if (strcmp(q, token) == 0)
{
*(p-1) = nl;
outp = p;
if (!*p)
{
_myfilbuf();
}
return MY_TRUE;
}
else if (atoken)
{
if (strcmp(q, atoken) == 0)
{
*(p-1) = nl;
outp = p;
if (!*p) {
_myfilbuf();
}
return MY_FALSE;
}
else if (strcmp(q, "elif") == 0)
{
/* Morph the 'elif' into '#if' and reparse it */
current_loc.line--;
total_lines--;
q[0] = nl;
q[1] = '#';
q[4] = c; /* undo the '\0' */
outp = q+1;
return MY_FALSE;
}
}
}
}
else /* not a preprocessor statement */
{
if (c == CHAR_EOF)
{
outp = p - 2;
current_loc.line--;
total_lines--;
lexerror("Unexpected end of file while skipping");
return MY_TRUE;
}
/* Skip the rest of the line */
while (c != nl) c = *p++;
}
/* Read new data from the file if necessary */
if (!*p)
{
outp = p;
p = _myfilbuf();
}
} /* for () */
/* NOTREACHED */
} /* skip_to() */
/*-------------------------------------------------------------------------*/
static void
handle_cond (Bool c)
/* Evaluate the boolean condition <c> of a preprocessor #if statement.
* If necessary, skip to the condition branch to read next, and/or
* push a new state onto the ifstate-stack.
*/
{
lpc_ifstate_t *p;
if (c || skip_to("else", "endif")) {
p = mempool_alloc(lexpool, sizeof(lpc_ifstate_t));
p->next = iftop;
iftop = p;
p->state = c ? EXPECT_ELSE : EXPECT_ENDIF;
}
} /* handle_cond() */
/*-------------------------------------------------------------------------*/
static Bool
start_new_include (int fd, string_t * str
, char * name, char * name_ext, char delim)
/* The lexer is about to read data from an included source (either file
* <fd> or string <str> which will be referenced) - handle setting up the
* include information. <name> is the name of the file to be read, <name_ext>
* is NULL or a string to add to <name> as " (<name_ext>)", <delim> is the
* delimiter ('"', '>' or ')') of the include filename.
*
* Return TRUE on success, FALSE if something failed.
*/
{
struct incstate *is, *ip;
source_file_t * src_file;
size_t namelen;
int inc_depth;
ptrdiff_t linebufoffset;
/* Prepare defbuf for a (nested) include */
linebufoffset = linebufstart - &defbuf[defbuf_len];
if (outp - defbuf < 3*MAXLINE)
{
realloc_defbuf();
/* linebufstart is invalid now */
if (outp - defbuf < 2*MAXLINE)
{
lexerror("Maximum total buffer size exceeded");
return MY_FALSE;
}
}
/* Copy the current state, but don't put it on the stack
* yet in case we run into an error further down.
*/
is = mempool_alloc(lexpool, sizeof(struct incstate));
if (!is) {
lexerror("Out of memory");
return MY_FALSE;
}
src_file = new_source_file(NULL, ¤t_loc);
if (!src_file)
{
mempool_free(lexpool, is);
lexerror("Out of memory");
return MY_FALSE;
}
is->yyin = yyin;
is->loc = current_loc;
is->linebufoffset = linebufoffset;
is->saved_char = saved_char;
is->next = inctop;
/* Copy the new filename into src_file */
namelen = strlen(name);
if (name_ext != NULL)
namelen += 3 + strlen(name_ext);
src_file->name = xalloc(namelen+1);
if (!src_file->name)
{
mempool_free(lexpool, is);
lexerror("Out of memory");
return MY_FALSE;
}
strcpy(src_file->name, name);
if (name_ext)
{
strcat(src_file->name, " (");
strcat(src_file->name, name_ext);
strcat(src_file->name, ")");
}
/* Now it is save to put the saved state onto the stack*/
inctop = is;
/* Compute the include depth and store the include information */
for (inc_depth = 0, ip = inctop; ip; ip = ip->next)
inc_depth++;
if (name_ext)
inctop->inc_offset = store_include_info(name_ext, src_file->name, delim, inc_depth);
else
inctop->inc_offset = store_include_info(name, src_file->name, delim, inc_depth);
/* Initialise the rest of the lexer state */
current_loc.file = src_file;
current_loc.line = 0;
linebufend = outp - 1; /* allow trailing zero */
linebufstart = linebufend - MAXLINE;
*(outp = linebufend) = '\0';
set_input_source(fd, str);
_myfilbuf();
return MY_TRUE;
} /* start_new_include() */
/*-------------------------------------------------------------------------*/
static void
add_auto_include (const char * obj_file, const char *cur_file, Bool sys_include)
/* A new file <cur_file> was opened while compiling object <object_file>.
* Add the auto-include information if available.
*
* If <cur_file> is NULL, then the <object_file> itself has just been
* opened, otherwise <cur_file> is an included file. In the latter case,
* flag <sys_include> purveys if it was a <>-type include.
*
* The global <current_loc.line> must be valid and will be modified.
*/
{
string_t * auto_include_string = NULL;
if (driver_hook[H_AUTO_INCLUDE].type == T_STRING
&& cur_file == NULL
)
{
auto_include_string = driver_hook[H_AUTO_INCLUDE].u.str;
}
else if (driver_hook[H_AUTO_INCLUDE].type == T_CLOSURE)
{
svalue_t *svp;
/* Setup and call the closure */
push_c_string(inter_sp, obj_file);
if (cur_file != NULL)
{
push_c_string(inter_sp, (char *)cur_file);
push_number(inter_sp, sys_include ? 1 : 0);
}
else
{
push_number(inter_sp, 0);
push_number(inter_sp, 0);
}
svp = secure_apply_lambda(driver_hook+H_AUTO_INCLUDE, 3);
if (svp && svp->type == T_STRING)
{
auto_include_string = svp->u.str;
}
}
if (auto_include_string != NULL)
{
/* The auto include string is handled like a normal include */
if (cur_file != NULL) /* Otherwise we already are at line 1 */
current_loc.line++; /* Make sure to restore to line 1 */
(void)start_new_include(-1, auto_include_string
, current_loc.file->name, "auto include", ')');
if (cur_file == NULL) /* Otherwise #include will increment it */
current_loc.line++; /* Make sure to start at line 1 */
}
} /* add_auto_include() */
/*-------------------------------------------------------------------------*/
static void
merge (char *name, mp_int namelen, char *deststart)
/* Take the given include file <name> of length <namelen>, make it
* a proper absolute pathname and store it into the buffer <deststart>.
* This buffer must be at least INC_OPEN_BUFSIZE bytes big.
* On a failure, return the empty string in *deststart.
*
* If <name> is a relative pathname, it is interpreted to the location
* of <currentfile>. './' and '../' sequences in the name are properly
* resolved (includes from above the mudlib are caught).
*/
{
char *from; /* Next character in <name> to process */
char *dest; /* Destination pointer into <deststart> */
from = name;
/* If <name> is an absolute pathname, skip any leading '/'.
* Else extract the pathpart from <currentfile>, put
* it into the destination buffer and set dest to point after it.
*/
if (*from == '/')
{
/* absolute path */
dest = deststart;
do from++; while (*from == '/');
}
else
{
/* relative path */
char *cp, *dp;
dest = (dp = deststart) - 1;
for (cp = current_loc.file->name; *cp; *dp++ = *cp++)
{
if (*cp == '/')
dest = dp;
}
dest++;
}
/* Make sure the bufferlimits are not overrun. */
if ((dest - deststart) + namelen >= INC_OPEN_BUFSIZE)
{
*deststart = '\0';
return;
}
/* Append the <name> to the buffer starting at <dest>,
* collapsing './' and '../' sequences while doing it.
*/
for (;;)
{
/* <from> now points to the character after the last '/'.
*/
if (*from == '.')
{
if (from[1] == '.' && from[2] == '/')
{
/* '../': remove the pathpart copied last */
if (dest == deststart)
{
/* including from above mudlib is NOT allowed */
*deststart = '\0';
return;
}
for (--dest;;)
{
if (*--dest == '/')
{
dest++;
break;
}
if (dest == deststart)
break;
}
from += 3;
continue;
} else if (from[1] == '/')
{
/* just skip these two characters */
from += 2;
continue;
}
}
/* Copy all characters up to and including the next '/'
* from <name> into the destination buffer.
* Return when at the end of the name.
*/
{
char c;
do {
c = *from++;
*dest++ = c;
if (!c)
return;
} while (c != '/');
while (*from == '/')
from++;
}
} /* for (;;) */
/* NOTREACHED */
} /* merge() */
/*-------------------------------------------------------------------------*/
static int
open_include_file (char *buf, char *name, mp_int namelen, char delim)
/* Open the include file <name> (length <namelen>) and return the file
* descriptor. On failure, generate an error message and return -1.
*
* <buf> is a buffer of size INC_OPEN_BUFSIZE and may be used to
* generate the real filename - <name> is just the name given in the
* #include statement.
*
* <delim> is '"' for #include ""-type includes, and '>' else.
* Relative "-includes are searched relative to the current file.
* <-includes are searched in the path(s) defined by the H_INCLUDE_DIRS
* driver hook.
*/
{
int fd;
int i;
struct stat aStat;
/* First, try to call master->include_file().
* Since simulate::load_object() makes sure that the master has been
* loaded, this test can only fail when the master is compiled.
*/
if (master_ob && !(master_ob->flags & O_DESTRUCTED)
&& (!EVALUATION_TOO_LONG())
)
{
svalue_t *res;
push_c_string(inter_sp, name);
if (!compat_mode)
{
char * filename;
filename = alloca(strlen(current_loc.file->name)+2);
*filename = '/';
strcpy(filename+1, current_loc.file->name);
push_c_string(inter_sp, filename);
}
else
push_c_string(inter_sp, current_loc.file->name);
push_number(inter_sp, (delim == '"') ? 0 : 1);
res = apply_master(STR_INCLUDE_FILE, 3);
if (res && !(res->type == T_NUMBER && !res->u.number))
{
/* We got a result - either a new name or a "reject it"
* value.
*/
char * cp;
if (res->type != T_STRING)
{
yyerrorf("Illegal to include file '%s'.", name);
return -1;
}
if (mstrsize(res->u.str) >= INC_OPEN_BUFSIZE)
{
yyerrorf("Include name '%s' too long.", get_txt(res->u.str));
return -1;
}
for (cp = get_txt(res->u.str); *cp == '/'; cp++) NOOP;
if (!legal_path(cp))
{
yyerrorf("Illegal path '%s'.", get_txt(res->u.str));
return -1;
}
strcpy(buf, cp);
if (!stat(buf, &aStat)
&& S_ISREG(aStat.st_mode)
&& (fd = ixopen(buf, O_RDONLY|O_BINARY)) >= 0 )
{
FCOUNT_INCL(buf);
return fd;
}
if (errno == EMFILE) lexerror("File descriptors exhausted");
#if ENFILE
if (errno == ENFILE) lexerror("File table overflow");
#endif
/* If we come here, we fail: file not found */
return -1;
}
}
else if (EVALUATION_TOO_LONG())
{
yyerrorf("Can't call master::%s for '%s': eval cost too big"
, get_txt(STR_INCLUDE_FILE), name);
}
/* The master apply didn't succeed, try the manual handling */
if (delim == '"') /* It's a "-include */
{
/* Merge the <name> with the current filename. */
merge(name, namelen, buf);
/* Test the file and open it */
if (!stat(buf, &aStat)
&& S_ISREG(aStat.st_mode)
&& (fd = ixopen(buf, O_RDONLY|O_BINARY)) >= 0)
{
FCOUNT_INCL(buf);
return fd;
}
if (errno == EMFILE)
lexerror("File descriptors exhausted");
#ifdef ENFILE
if (errno == ENFILE)
lexerror("File table overflow");
#endif
/* Include not found - fall back onto <> search pattern */
}
/* Handle a '<'-include. */
if (driver_hook[H_INCLUDE_DIRS].type == T_POINTER)
{
char * cp;
/* H_INCLUDE_DIRS is a vector of include directories.
*/
if (namelen + inc_list_maxlen >= INC_OPEN_BUFSIZE)
{
yyerror("Include name too long.");
return -1;
}
for (cp = name; *cp == '/'; cp++) NOOP;
/* The filename must not specifiy parent directories */
if (!check_no_parentdirs(cp))
return -1;
/* Search all include dirs specified.
*/
for (i = 0; (size_t)i < inc_list_size; i++)
{
char * iname;
sprintf(buf, "%s%s", get_txt(inc_list[i].u.str), name);
for (iname = buf; *iname == '/'; iname++) NOOP;
if (!stat(iname, &aStat)
&& S_ISREG(aStat.st_mode)
&& (fd = ixopen(iname, O_RDONLY|O_BINARY)) >= 0 )
{
FCOUNT_INCL(iname);
return fd;
}
if (errno == EMFILE) lexerror("File descriptors exhausted");
#if ENFILE
if (errno == ENFILE) lexerror("File table overflow");
#endif
}
/* If we come here, the include file was not found */
}
else if (driver_hook[H_INCLUDE_DIRS].type == T_CLOSURE)
{
/* H_INCLUDE_DIRS is a function generating the full
* include file name.
*/
svalue_t *svp;
/* Setup and call the closure */
push_c_string(inter_sp, name);
push_c_string(inter_sp, current_loc.file->name);
if (driver_hook[H_INCLUDE_DIRS].x.closure_type == CLOSURE_LAMBDA)
{
free_object(driver_hook[H_INCLUDE_DIRS].u.lambda->ob, "open_include_file");
driver_hook[H_INCLUDE_DIRS].u.lambda->ob = ref_object(current_object, "open_include_file");
}
svp = secure_apply_lambda(&driver_hook[H_INCLUDE_DIRS], 2);
/* The result must be legal relative pathname */
if (svp && svp->type == T_STRING
&& mstrsize(svp->u.str) < INC_OPEN_BUFSIZE)
{
char * cp;
for (cp = get_txt(svp->u.str); *cp == '/'; cp++) NOOP;
strcpy(buf, cp);
if (legal_path(buf))
{
if (!stat(buf, &aStat)
&& S_ISREG(aStat.st_mode)
&& (fd = ixopen(buf, O_RDONLY|O_BINARY)) >= 0 )
{
FCOUNT_INCL(buf);
return fd;
}
if (errno == EMFILE) lexerror("File descriptors exhausted");
#if ENFILE
if (errno == ENFILE) lexerror("File table overflow");
#endif
}
}
/* If we come here, the include file was not found */
}
/* File not found */
return -1;
} /* open_include_file() */
/*-------------------------------------------------------------------------*/
#ifdef USE_NEW_INLINES
void *
get_include_handle (void)
/* Helper function for inline closures: return the current inctop
* setting so that the compiler can check if a closures spans files.
*/
{
return (void*)inctop;
} /* get_include_handle() */
#endif /* USE_NEW_INLINES */
/*-------------------------------------------------------------------------*/
static INLINE void
handle_include (char *name)
/* Handle an #include statement, <name> points to the first non-blank
* character after the '#include'.
* If the include succeeds, a new incstate is created and pushed
* onto the include stack. Else an error message is generated.
*/
{
char *p;
int fd; /* fd of new include file */
char delim; /* Filename end-delimiter ('"' or '>'). */
char *old_outp; /* Save the original outp */
Bool in_buffer = MY_FALSE; /* True if macro was expanded */
char buf[INC_OPEN_BUFSIZE];
#if 0
if (nbuf) {
lexerror("Internal preprocessor error");
return;
}
#endif
old_outp = outp;
/* If <name> doesn't start with '"' or '<', assume that it
* is a macro. Attempt to expand these macros until <name>
* starts with a proper delimiter.
*/
while (*name != '"' && *name != '<')
{
char c;
ident_t *d;
/* Locate the end of the macro and look it up */
for (p = name; isalunum(*p); p++) NOOP;
c = *p;
*p = '\0';
d = lookup_define(name);
*p = c;
/* Prepare to expand the macro */
if (in_buffer)
{
outp = p;
}
else
{
myungetc('\n');
add_input(p);
in_buffer = MY_TRUE;
}
/* Expand the macro */
if (!d || !_expand_define(&d->u.define, d) ) {
yyerror("Missing leading \" or < in #include");
return;
}
/* Set name to the first non-blank of the expansion */
name = outp;
while (lexwhite(*name))
name++;
}
/* Store the delimiter and set p to the closing delimiter */
delim = (char)((*name++ == '"') ? '"' : '>');
for(p = name; *p && *p != delim; p++) NOOP;
if (!*p) {
yyerror("Missing trailing \" or > in #include");
outp = old_outp;
return;
}
*p = '\0';
/* For "-includes, look for following macros or "<path>"
* fragments on the same line and append these to the <name>.
* The new name is created in the yytext[] buffer (if at all).
*/
if (delim == '"')
{
char *q;
q = p + 1;
for (;;)
{
/* Find the first non-blank character after p */
while(lexwhite(*q))
q++;
if (!*q || *q == '\n')
break;
/* First, try to expand a macros */
while (*q != delim)
{
char *r, c;
ident_t *d;
/* Set r to the first blank after the macro name */
for (r = q; isalunum(*r); r++) NOOP;
/* Lookup the macro */
c = *r;
*r = '\0';
d = lookup_define(q);
*r = c;
/* Prepare to expand the macro */
if (in_buffer)
{
outp = r;
if (name != yytext)
{
if ( (p - name) >= MAXLINE - 1)
{
yyerror("Include name too long.");
outp = old_outp;
return;
}
*p = '\0';
strcpy(yytext, name);
p += yytext - name;
name = yytext;
}
}
else
{
myungetc('\n');
add_input(r);
in_buffer = MY_TRUE;
}
/* Expand the macro */
if (!d || !_expand_define(&d->u.define, d) ) {
yyerror("Missing leading \" in #include");
outp = old_outp;
return;
}
q = outp;
/* Skip the blanks until the next macro/filename */
while (lexwhite(*q))
q++;
}
/* Second, try to parse a string literal */
while (*++q && *q != delim)
{
if ( (p - name) >= MAXLINE - 1)
{
yyerror("Include name too long.");
outp = old_outp;
return;
}
*p++ = *q;
}
if (!*q++) {
yyerror("Missing trailing \" in #include");
outp = old_outp;
return;
}
} /* for (;;) */
} /* if (delim == '"') */
/* p now points to the character after the parsed filename */
outp = old_outp; /* restore outp */
*p = '\0'; /* mark the end of the filename */
/* Open the include file, put the current lexer state onto
* the incstack, and set up for the new file.
*/
if ((fd = open_include_file(buf, name, p - name, delim)) >= 0)
{
if (!start_new_include(fd, NULL, buf, NULL, delim))
return;
add_auto_include(object_file, current_loc.file->name, delim != '"');
}
else
{
yyerrorf("Cannot #include '%s'", name);
}
} /* handle_include() */
/*-------------------------------------------------------------------------*/
static void
skip_comment (void)
/* Skip a block comment (/ * ... * /). The function is entered with outp
* pointing to the first character after the comment introducer, and left
* with outp pointing to the first character after the comment end delimiter.
*/
{
register char c, *p;
p = outp;
for(;;)
{
/* Skip everything until the next '*' */
while((c = *p++) != '*')
{
if (c == '\n') {
store_line_number_info();
nexpands = 0;
if ((c = *p) == CHAR_EOF) {
outp = p - 1;
lexerror("End of file (or 0x01 character) in a comment");
return;
}
current_loc.line++;
if (!c)
{
outp = p;
p = _myfilbuf();
}
}
} /* while (c == '*') */
/* Skip all '*' until we find '/' or something else */
do
{
if ((c = *p++) == '/')
{
outp = p;
return;
}
if (c == '\n') {
store_line_number_info();
nexpands = 0;
if ((c = *p) == CHAR_EOF)
{
outp = p - 1;
lexerror("End of file (or 0x01 character) in a comment");
return;
}
current_loc.line++;
if (!c)
{
outp = p;
p = _myfilbuf();
}
c = '\0'; /* Make sure to terminate the '*' loop */
}
} while(c == '*');
} /* for() */
/* NOTREACHED */
} /* skip_comment() */
/*-------------------------------------------------------------------------*/
static char *
skip_pp_comment (char *p)
/* Skip a '//' line comment. <p> points to the first character after
* the comment introducer, the function returns a pointer to the first
* character after the terminating newline. If the comment is ended
* prematurely by the end of file, the returned pointer will point at the
* EOF character.
* Note that a '\<newline>' lineend does not terminate the comment.
*/
{
char c;
for (;;)
{
c = *p++;
if (CHAR_EOF == c)
{
return p-1;
}
if (c == '\n')
{
store_line_number_info();
current_loc.line++;
if (p[-2] == '\\')
{
if (!*p)
{
outp = p;
p = _myfilbuf();
}
continue;
}
nexpands = 0;
if (!*p)
{
outp = p;
p = _myfilbuf();
}
return p;
}
}
/* NOTREACHED */
} /* skip_pp_comment() */
/*-------------------------------------------------------------------------*/
static void
deltrail (char *sp)
/* Look for the first blank character in the text starting at <sp> and
* set it to '\0'. The function is used to isolate the next word
* in '#' statements.
*/
{
char *p;
p = sp;
if (!*p)
{
lexerror("Illegal # command");
}
else
{
while(*p && !isspace((unsigned char)*p))
p++;
*p = '\0';
}
} /* deltrail() */
/*-------------------------------------------------------------------------*/
static void
handle_pragma (char *str)
/* Handle the pragma <str>. Unknown pragmas are ignored.
* One pragma string can contain multiple actual pragmas, separated
* with comma (and additional spaces).
*/
{
char * base, * next;
#if defined(LEXDEBUG)
printf("%s handle pragma:'%s'\n", time_stamp(), str);
#endif
/* Loop over the pragma(s).
* If valid, base points to the first character of the pragma name,
* or to spaces before it.
*/
for ( base = str, next = NULL
; base != NULL && *base != '\0' && *base != '\r'
; base = next
)
{
size_t namelen;
Bool validPragma;
/* Skip spaces */
base = base + strspn(base, " \t\r");
if ('\0' == *base || '\r' == *base)
break;
/* Find next delimiter, if any, and determine the
* length of the pragma name.
*/
next = strpbrk(base, " \t,\r");
if (NULL == next)
namelen = strlen(base);
else
namelen = next - base;
/* Evaluate the found pragma name */
validPragma = MY_FALSE;
if (namelen == 0)
{
if (master_ob)
{
yywarnf("Empty #pragma");
}
else
{
debug_message("Warning: Empty #pragma"
": file %s, line %d\n"
, current_loc.file->name, current_loc.line);
}
validPragma = MY_TRUE; /* Since we already issued a warning */
}
else if (strncmp(base, "strict_types", namelen) == 0)
{
pragma_strict_types = PRAGMA_STRICT_TYPES;
instrs[F_CALL_OTHER].ret_type.typeflags = TYPE_UNKNOWN;
instrs[F_CALL_DIRECT].ret_type.typeflags = TYPE_UNKNOWN;
validPragma = MY_TRUE;
}
else if (strncmp(base, "strong_types", namelen) == 0)
{
pragma_strict_types = PRAGMA_STRONG_TYPES;
instrs[F_CALL_OTHER].ret_type.typeflags = TYPE_ANY;
instrs[F_CALL_DIRECT].ret_type.typeflags = TYPE_ANY;
validPragma = MY_TRUE;
}
else if (strncmp(base, "weak_types", namelen) == 0)
{
pragma_strict_types = PRAGMA_WEAK_TYPES;
instrs[F_CALL_OTHER].ret_type.typeflags = TYPE_ANY;
instrs[F_CALL_DIRECT].ret_type.typeflags = TYPE_ANY;
validPragma = MY_TRUE;
}
else if (strncmp(base, "save_types", namelen) == 0)
{
pragma_save_types = MY_TRUE;
validPragma = MY_TRUE;
}
else if (strncmp(base, "combine_strings", namelen) == 0)
{
pragma_combine_strings = MY_TRUE;
validPragma = MY_TRUE;
}
else if (strncmp(base, "no_combine_strings", namelen) == 0)
{
pragma_combine_strings = MY_FALSE;
validPragma = MY_TRUE;
}
else if (strncmp(base, "verbose_errors", namelen) == 0)
{
pragma_verbose_errors = MY_TRUE;
validPragma = MY_TRUE;
}
else if (strncmp(base, "no_clone", namelen) == 0)
{
pragma_no_clone = MY_TRUE;
validPragma = MY_TRUE;
}
else if (strncmp(base, "no_inherit", namelen) == 0)
{
pragma_no_inherit = MY_TRUE;
validPragma = MY_TRUE;
}
else if (strncmp(base, "no_shadow", namelen) == 0)
{
pragma_no_shadow = MY_TRUE;
validPragma = MY_TRUE;
}
else if (strncmp(base, "pedantic", namelen) == 0)
{
pragma_pedantic = MY_TRUE;
validPragma = MY_TRUE;
}
else if (strncmp(base, "sloppy", namelen) == 0)
{
pragma_pedantic = MY_FALSE;
validPragma = MY_TRUE;
}
else if (strncmp(base, "no_local_scopes", namelen) == 0)
{
pragma_use_local_scopes = MY_FALSE;
validPragma = MY_TRUE;
}
else if (strncmp(base, "local_scopes", namelen) == 0)
{
pragma_use_local_scopes = MY_TRUE;
validPragma = MY_TRUE;
}
else if (strncmp(base, "warn_missing_return", namelen) == 0)
{
pragma_warn_missing_return = MY_TRUE;
validPragma = MY_TRUE;
}
else if (strncmp(base, "no_warn_missing_return", namelen) == 0)
{
pragma_warn_missing_return = MY_FALSE;
validPragma = MY_TRUE;
}
else if (strncmp(base, "warn_function_inconsistent", namelen) == 0)
{
pragma_check_overloads = MY_TRUE;
validPragma = MY_TRUE;
}
else if (strncmp(base, "no_warn_function_inconsistent", namelen) == 0)
{
pragma_check_overloads = MY_FALSE;
validPragma = MY_TRUE;
}
else if (strncmp(base, "warn_deprecated", namelen) == 0)
{
pragma_warn_deprecated = MY_TRUE;
validPragma = MY_TRUE;
}
else if (strncmp(base, "no_warn_deprecated", namelen) == 0)
{
pragma_warn_deprecated = MY_FALSE;
validPragma = MY_TRUE;
}
else if (strncmp(base, "range_check", namelen) == 0)
{
pragma_range_check = MY_TRUE;
validPragma = MY_TRUE;
}
else if (strncmp(base, "no_range_check", namelen) == 0)
{
pragma_range_check = MY_FALSE;
validPragma = MY_TRUE;
}
else if (strncmp(base, "warn_empty_casts", namelen) == 0)
{
pragma_warn_empty_casts = MY_TRUE;
validPragma = MY_TRUE;
}
else if (strncmp(base, "no_warn_empty_casts", namelen) == 0)
{
pragma_warn_empty_casts = MY_FALSE;
validPragma = MY_TRUE;
}
else if (strncmp(base, "share_variables", namelen) == 0)
{
if (variables_defined)
{
yywarnf("Can't use #pragma share_variables after defining "
"variables");
}
else
pragma_share_variables = MY_TRUE;
validPragma = MY_TRUE;
}
else if (strncmp(base, "init_variables", namelen) == 0)
{
if (variables_defined)
{
yywarnf("Can't use #pragma init_variables after defining "
"variables");
}
else
pragma_share_variables = MY_FALSE;
validPragma = MY_TRUE;
}
#if defined( DEBUG ) && defined ( TRACE_CODE )
else if (strncmp(base, "set_code_window", namelen) == 0)
{
set_code_window();
validPragma = MY_TRUE;
}
else if (strncmp(base, "show_code_window", namelen) == 0)
{
show_code_window()Showing the first 100 KB of 223.8 KB. Download the archive for the full file.