prolang.y
ldmud-3.2.9/src/prolang.y · 379.5 KB
From the archive ldmud-329.tar.gz
Download the archive « Back to the archive contents
%{
%line
/*---------------------------------------------------------------------------
* LPC compiler
*
*---------------------------------------------------------------------------
* TODO: Some code parts 'know' which instructions are xcodes and which normal.
* TODO:: Conditional compiles would be nice there.
* TODO: The handling of virtual inherits is a bit vague, too.
*
* This is the grammar definition and bytecode compiler of LPC. However, this
* file is not passed to byacc directly, but first preprocessed by make_func,
* among other things to synchronise the tokens with the other bytecodes
* (reason being that yacc doesn't know an include construct). The following
* keywords are recognized and replaced by make_func:
*
* %line: generates a #line statement to synchronize the C compiler.
*
* %typemap TYPE<name>:<value>,...,TYPE_<name>:<value>
* Generates a lookup table TYPE_<name> -> <value>. Unspecified
* TYPEs are given the value 0.
*
* %hookmap <hookname>:<value>,...,<hookname>:<value>
* Generates a lookup table <hookname> -> <value>. Unspecified
* driverhook entries are given the value 0.
*
* In addition, make_func implements a simple preprocessor using the
* keywords %if, %elif, %else and %endif; mainly to activate the proper
* parsing rules for INITIALIZATION_BY___INIT.
*---------------------------------------------------------------------------
* A compile file, set its filename into <current_file>, open it to yield a
* filedescriptor 'fd', then call
*
* compile_file(fd);
*
* then close the file again. The compiled program is 'returned' in
* the global compiled_prog - on error, this variable is returned as NULL.
* If after the compilation the variable inherit_file is
* not NULL, the compilation failed because it encountered an
* "inherit 'name'" statement for which no object could be found: the
* 'name' was stored in inherit_file and has to be compiled first.
*
* It is the task of the caller to make sure not to call the compiler
* recursively.
*
%ifdef INITIALIZATION_BY___INIT
* If there is any initialization of a global variable, a function '__INIT'
* is generated with the initialization code. The code is generated in
* fragments whenever a variable initialization is encountered; the fragments
* are therefore potentially spread over the whole program code. The fragments
* are linked by JUMP instructions with jump to the next fragment, just
* the last fragment ends in a RETURN0.
*
* When inheriting from another object, a call will automatically be made
* to call __INIT in that code from the current __INIT.
%else
* The variable initializers are returned as svalue_t[] in the global
* variable prog_variable_values. It is the task of the call to free
* that memory.
%endif
*---------------------------------------------------------------------------
* The compiler is a simple one-pass compiler with immediate code generation.
* The problem of forward references is solved with various backpatching
* structures (explained where declared).
*
* The most tricky part is that of lvalue (and with it reference) generation
* in contexts where rvalues are sensible as well. This is so especially
* because the order of arguments on the stack differs between the
* instructions :-(. The approach is to generate rvalues, but keep the
* position, and size and alternatives of the instruction(s) in a struct
* lrvalue, so that a later change into lvalues is possible. Additionally
* these instructions can be modified to generated protected lvalues as well.
* TODO: This whole thing is quite complex and not very well documented.
* TODO:: It's propably easier to rewrite interpreter and compiler...
*---------------------------------------------------------------------------
*/
#undef lint /* undef so that precompiled headers can be used */
#include "driver.h"
#include "typedefs.h"
#include "my-alloca.h"
#include <stdio.h>
#include <stdarg.h>
#include "prolang.h"
#include "array.h"
#include "backend.h"
#include "closure.h"
#include "exec.h"
#include "gcollect.h"
#include "interpret.h"
#include "instrs.h"
#include "lex.h"
#include "main.h"
#include "mapping.h"
#include "object.h"
#include "simulate.h"
#include "simul_efun.h"
#include "stdstrings.h"
#include "stralloc.h"
#include "svalue.h"
#include "swap.h"
#include "switch.h"
#include "wiz_list.h"
#include "xalloc.h"
#include "../mudlib/sys/driver_hook.h"
#define lint /* redef again to prevent spurious warnings */
#define YYMAXDEPTH 600
/*-------------------------------------------------------------------------*/
typedef struct block_scope_s block_scope_t;
typedef struct const_list_s const_list_t;
typedef struct const_list_svalue_s const_list_svalue_t;
typedef struct efun_shadow_s efun_shadow_t;
typedef struct mem_block_s mem_block_t;
/*-------------------------------------------------------------------------*/
/* Exported result variables */
int32 current_id_number = 0;
/* The id-number of the compiled program.
*/
int num_virtual_variables;
/* Number of virtual variables.
* When creating the bytecode, the non-virtual variable indices
* are offset by this value, in effect collecting the virtual
* variables at the start of the variable indices.
*/
program_t *compiled_prog;
/* After yyparse(), the finished program.
*/
char *inherit_file;
/* Used as a flag: if it is set to a string after yyparse(),
* this string should be loaded as an object, and the original object
* must be loaded again.
*/
int num_parse_error;
/* Number of errors in the compile.
*/
%ifndef INITIALIZATION_BY___INIT
svalue_t *prog_variable_values;
/* After epilog(), the variable initializers.
*/
%endif /* INITIALIZATION_BY___INIT */
/*-------------------------------------------------------------------------*/
/* Table which hook may be of which type.
* It is here because make_func has to touch this file anyway, but
* it will be used by simulate:f_set_driver_hook().
*/
#define SH(x) - -(1 << (x))
short hook_type_map[NUM_DRIVER_HOOKS] =
%hookmap \
H_MOVE_OBJECT0: 0, \
H_MOVE_OBJECT1: 0, \
H_LOAD_UIDS: SH(T_CLOSURE), \
H_CLONE_UIDS: SH(T_CLOSURE), \
H_CREATE_SUPER: SH(T_STRING), \
H_CREATE_OB: SH(T_STRING), \
H_CREATE_CLONE: SH(T_STRING), \
H_RESET: SH(T_STRING), \
H_CLEAN_UP: SH(T_CLOSURE) SH(T_STRING), \
H_MODIFY_COMMAND: SH(T_CLOSURE) SH(T_STRING) SH(T_MAPPING), \
H_NOTIFY_FAIL: SH(T_CLOSURE) SH(T_STRING), \
H_NO_IPC_SLOT: SH(T_STRING), \
H_INCLUDE_DIRS: SH(T_CLOSURE) SH(T_POINTER), \
H_TELNET_NEG: SH(T_CLOSURE) SH(T_STRING), \
H_NOECHO: SH(T_CLOSURE) SH(T_STRING), \
H_ERQ_STOP: SH(T_CLOSURE), \
H_MODIFY_COMMAND_FNAME: SH(T_STRING), \
H_COMMAND: SH(T_CLOSURE) SH(T_STRING), \
H_SEND_NOTIFY_FAIL: SH(T_CLOSURE) SH(T_STRING), \
H_AUTO_INCLUDE: SH(T_CLOSURE) SH(T_STRING), \
#undef SH
/*-------------------------------------------------------------------------*/
/* Types */
/* --- struct const_list_s: One element in a constant list ---
*
* When initializing variables statically with arrays ({ ... }),
* a list of these structures is used to collect the information about
* the array content.
*/
struct const_list_s
{
const_list_t *next;
svalue_t val;
};
/* --- struct const_list_svalue_s: Head of a constant list ---
*
* When initializing variables statically with arrays ({ ... }),
* the initializer-svalue_t* will point to an instance of this c_l_svalue_s.
* In fact, the initializer points to the .head member.
*
* The .head svalue_t is a T_ERROR_HANDLER pointing to a deallocation
* function for the list.
*/
struct const_list_svalue_s
{
svalue_t head; /* the error handler */
const_list_t list; /* First element of the list */
};
/* --- struct efun_shadow_s: Store info about masked efuns ---
*
* This structure is used when global identifiers shadow efun names.
*/
struct efun_shadow_s
{
efun_shadow_t *next; /* Linkpointer for the list of shadows */
ident_t *shadow; /* Identifier of the shadow */
};
/*-------------------------------------------------------------------------*/
/* Macros */
#define NON_VIRTUAL_OFFSET_TAG 0x4000
/* Tag or'ed on inherit.variable_index_offset for non-virtual
* inherits for the duration of the compilation.
* The variable_index_offsets of such marked variables do not
* yet the the num_virtual_variables offset into account.
*/
#define align(x) (((x) + (sizeof(char*)-1) ) & ~(sizeof(char*)-1) )
#define defined_function(s) \
((s)->type == I_TYPE_GLOBAL ? (s)->u.global.function : -1)
/* Return the index of the function <s> if global (and therefore existing),
* and -1 otherwise.
*/
#define NEW_INHERITED_INDEX (0xfffff)
/* While inserting a new inherit, this marks the newly inherited
* things.
*/
/*-------------------------------------------------------------------------*/
/* The generated information (code and otherwise) is kept in several
* memory areas, each of which can grow dynamically and independent
* from the others.
*
* The first NUMPAREAS are save with the program code after compilation,
* the others are of internal use for the compiler only.
*/
#define A_PROGRAM 0
/* (bytecode_t): Program code.
*/
#define A_STRINGS 1
/* (shared char*) Strings used by the program.
*/
#define A_VARIABLES 2
/* (variable_t) The information for all non-virtual variables.
*/
#define A_VIRTUAL_VAR 3
/* (variable_t) The information for all virtual variables.
*/
#define A_LINENUMBERS 4
/* (char) The linenumber information.
*/
#define A_INHERITS 5
/* (inherit_t) The information for the inherited programs.
*/
#define A_ARGUMENT_TYPES 6
/* (vartype_t) Types of the arguments of all functions with
* typechecking. The argument types for a specific function
* can be found using the ARGUMENT_INDEX
*/
#define A_ARGUMENT_INDEX 7
/* (unsigned short) Index of the first argument type of function <n>.
* INDEX_START_NONE is used for functions with no type information.
*/
#define A_INCLUDES 8
/* (include_t) Tabled descriptors of all included files, in the order
* of appearance.
*/
#define NUMPAREAS 9 /* Number of saved areas */
#define A_FUNCTIONS 9
/* (function_t): Function definitions
*/
%ifndef INITIALIZATION_BY___INIT
# define A_VARIABLE_VALUES 10
/* (svalue_t) Initializers for non-virtual variables.
*/
# define A_VIRTUAL_VAR_VALUES 11
/* (svalue_t) Initializers for virtual variables.
*/
%endif
#define A_STRING_NEXT 12
/* (int) During compilation, the strings in A_STRINGS are organized
* in a hash table (prog_string_indizes/_tags). The hash chains are
* linked together using the indizes in this area. The end of
* a chain is marked by a negative next-index.
*/
#define NUMAREAS 13 /* Total number of areas */
/* --- struct mem_block_s: One memory area ---
* Every mem_block keeps one memory area. As it grows by using realloc(),
* no pointers should be kept into such an area (offsets are ok).
*/
struct mem_block_s
{
char *block; /* Pointer to the allocated memory */
mp_uint current_size; /* Used size of the mem_block */
mp_uint max_size; /* Allocated size of the mem_block */
};
#define START_BLOCK_SIZE 2048
/* Initial size of an area/mem_block.
*/
static mem_block_t mem_block[NUMAREAS];
/* All memory areas.
*/
#define PROGRAM_BLOCK ((bytecode_p)(mem_block[A_PROGRAM].block))
/* The current program block, properly typed.
*/
#define CURRENT_PROGRAM_SIZE (mem_block[A_PROGRAM].current_size)
/* The current program size.
*/
#define FUNCTION(n) ((function_t *)mem_block[A_FUNCTIONS].block + (n))
/* Return the function_t* for function number <n>.
*/
#define FUNCTION_COUNT (mem_block[A_FUNCTIONS].current_size / sizeof (function_t))
/* Number of function_t stored so far in A_FUNCTIONS.
*/
#define INHERIT_COUNT (mem_block[A_INHERITS].current_size / sizeof(inherit_t))
/* Number of inherit_t stored so far in A_INHERITS.
*/
#define ARGUMENT_INDEX(n) ((unsigned short *)mem_block[A_ARGUMENT_INDEX].block)[n]
/* Lookup the start index of the types for function number <n>.
*/
#define ARGTYPE_COUNT (mem_block[A_ARGUMENT_TYPES].current_size / sizeof(vartype_t))
/* Number of vartype_t stored so far in A_ARGUMENT_TYPES.
*/
#define NV_VARIABLE(n) ((variable_t *)mem_block[A_VARIABLES].block + (n))
/* Return the variable_t* for the non-virtual variable <n>.
*/
#define NV_VARIABLE_COUNT (mem_block[A_VARIABLES].current_size / sizeof(variable_t))
#define V_VARIABLE_COUNT (mem_block[A_VIRTUAL_VAR].current_size / sizeof(variable_t))
/* Number of variables stored so var in A_VARIABLES resp. A_VIRTUAL_VAR.
*/
#define V_VARIABLE(n) ((variable_t *)mem_block[A_VIRTUAL_VAR].block + \
(n) - VIRTUAL_VAR_TAG)
/* Return the variable_t* for the virtual variable <n> (still including
* the offset).
*/
#define VARIABLE(n) ((n) & VIRTUAL_VAR_TAG ? V_VARIABLE(n) : NV_VARIABLE(n))
/* Return the variable_t* for the variable <n>, virtual or not.
*/
%ifndef INITIALIZATION_BY___INIT
#define V_VAR_VALUE(n) ((svalue_t *)mem_block[A_VARIABLE_VALUES].block + \
(n) - VIRTUAL_VAR_TAG)
/* Return the svalue_t* for the initializer of virtual variable <n>
* (still including the offset).
*/
#define NV_VAR_VALUE(n) ((svalue_t *)mem_block[A_VARIABLE_VALUES].block + (n))
/* Return the svalue_t* for the initializer of non-virtual variable <n>.
*/
%endif
#define INHERIT(n) ((inherit_t *)mem_block[A_INHERITS].block)[n]
/* Index the inherit_t <n>.
*/
#define INHERIT_COUNT (mem_block[A_INHERITS].current_size / sizeof(inherit_t))
/* Return the number of inherits encountered so far.
*/
#define PROG_STRING(n) ((char **)mem_block[A_STRINGS].block)[n]
/* Index the pointer for program string <n>.
*/
#define STRING_COUNT (mem_block[A_STRINGS].current_size / sizeof(char *))
/* Return the number of program strings encountered so far.
*/
#define PROG_STRING_NEXT(n) ((int *)mem_block[A_STRING_NEXT].block)[n]
/* Index the chain-index for program string <n>.
*/
#define INCLUDE_COUNT (mem_block[A_INCLUDES].current_size / sizeof(include_t))
/* Return the total number of include files encountered so far.
*/
/*-------------------------------------------------------------------------*/
/* Information describing nested local blocks (scopes).
*/
struct block_scope_s
{
int first_local; /* Number of first local defined in this scope */
int num_locals; /* Number of locals defined in this scope */
mp_uint addr;
/* Address of CLEAR_LOCALS instruction, needed for backpatching */
};
static block_scope_t block_scope[COMPILER_STACK_SIZE];
/* A static stack of block scopes, indexed by <block_depth>-1.
* TODO: This should be dynamic.
*/
static int block_depth;
/* The nesting depth of blocks ( '{ ... }' ), used to distinguish
* local variable definitions.
* block_depth = 0: not used, would mean 'global'
* = 1: function arguments
* = 2: function local variables
* > 2: vars of nested blocks within the function
*/
static Bool use_local_scopes;
/* Copy of pragma_use_local_scopes, updated at every entry into
* a function. Reason is that the pragma must not change inside
* a function.
*/
/*-------------------------------------------------------------------------*/
/* Other Variables */
static char *last_yalloced = NULL;
/* Head of blocklist allocated with yalloc().
*/
static program_t NULL_program;
/* Empty program_t structure for initialisations.
*/
static p_int comp_stack[COMPILER_STACK_SIZE];
/* A stack of addresses (offsets) in the generated program code for
* later backpatching.
*/
static size_t comp_stackp;
/* Index of the next unused entry in <comp_stack>.
*/
%ifdef INITIALIZATION_BY___INIT
static p_int last_initializer_end;
/* Address of the argument of the final JUMP instruction of the
* previous INIT fragment.
* A negative value if there is no previous fragment (this also means
* that the INIT functions hasn't been created yet).
*/
static p_int first_initializer_start;
/* Address of the 'num_arg' byte in the function header of the first
* INIT fragment.
*/
static Bool variables_initialized;
/* TRUE if the code for all variables has been created.
*/
%else
static svalue_t *currently_initialized;
/* The variable for which currently the initializer is compiled.
*/
%endif /* INITIALIZATION_BY___INIT */
static mem_block_t type_of_arguments;
/* The vartypes of arguments when calling functions must be saved,
* to be used afterwards for checking. And because function calls
* can be done as an argument to a function calls, a stack of argument types
* is needed. This stack does not need to be freed between compilations,
* but will be reused.
*/
static vartype_t type_of_locals[MAX_LOCAL];
/* The short type (ie: just the type, no visibility information) of
* the local variables.
*/
static fulltype_t full_type_of_locals[MAX_LOCAL];
/* The full types of the local variables.
*/
static int current_number_of_locals = 0;
/* Current (active) number of local variables at this point in the
* function.
*/
static int max_number_of_locals = 0;
/* Total number of local variables used in this function so far.
*/
static ident_t *all_locals = NULL;
/* List of defined local variables, listed in reverse order of definition.
* This also means that the variables are listed in reverse order of
* nested block scopes.
*/
fulltype_t exact_types;
/* If 0, don't check nor require argument and function types.
* Otherwise it's the full return type of the function, including
* visibility. The lexer reads this variable when scanning an
* inline closure.
*/
static fulltype_t default_varmod;
static fulltype_t default_funmod;
/* Default visibility modifiers for variables resp. function.
*/
static int heart_beat;
/* Number of the heart_beat() function, or < 0 if none.
*/
static int call_other_sefun;
/* Index of the call_other() sefun, or < 0 if none;
*/
static ident_t *all_globals = NULL;
/* List of all created global identifiers (variables and functions).
*/
static efun_shadow_t *all_efun_shadows = NULL;
/* List of all shadow markers for efuns shadowed by global identifiers.
*/
static p_int switch_pc;
/* When compiling a switch, this is the address of the first byte
* after the SWITCH instruction.
*/
static p_int current_break_address;
/* If != 0, the compiler is in a break-able environment and this
* variable points to the first offset-part of a series of LBRANCHes
* which implement the break statement. Stored in every offset-part
* is the address of the offset of the next LBRANCH in the series. The
* last LBRANCH is marked by having a negative offset value.
*
* There are a few special values/flags for this variable:
*/
#define BREAK_ON_STACK 0x04000000
/* Bitflag: true when the break-address is stored on the break stack,
* and therefore the BREAK instruction has to be used.
*/
#define BREAK_FROM_SWITCH 0x08000000
/* TODO: We are compiling a switch instruction.
*/
#define CASE_LABELS_ENABLED 0x10000000
/* The "case" and "default" statements are allowed since we're
* compiling a switch(). This flag is turned off for loops or
* conditions embedded in a switch().
*/
#define BREAK_DELIMITER -0x20000000
/* Special value: no break encountered (yet).
*/
static p_int current_continue_address;
/* If != 0, the compiler is in a continue-able environment and this
* variable points to the first offset-part of a series of LBRANCHes
* which implement the continue statement. Stored in every offset-part
* is the address of the offset of the next LBRANCH in the series. The
* last LBRANCH is marked by having a negative offset value.
*
* A special case are continues inside a switch, as for these the
* switch()es have to be terminated too using the BREAK_CONTINUE
* instructions (which also have an offset-part). The c_c_a therefore
* also encodes the switch()-nesting depth in the top bits of the
* variable.
*/
#define CONTINUE_ADDRESS_MASK 0x0003ffff
/* Mask for the offset-address part of the variable.
*/
#define SWITCH_DEPTH_UNIT 0x00040000
/* The switch depth is encoded in multiples of this value.
* This way we don't have to shift.
*/
#define SWITCH_DEPTH_MASK 0x3ffc0000
/* Mask for the switch-nesting depth part of the variable.
*/
#define CONTINUE_DELIMITER -0x40000000
/* Special value: no continue encountered (yet).
*/
static fulltype_t current_type;
/* The current basic type.
*/
static p_uint last_expression;
/* If >= 0, the address of the last instruction which by itself left
* a value on the stack. If there is no such instruction, the value
* is negative.
*/
static Bool last_string_is_new;
/* TRUE: the last string stored with store_prog_string() was indeed
* a new string.
*/
static int prog_string_indizes[0x100];
/* Hash table for the program strings holding the initial indices
* for the hash chains.
*/
static char prog_string_tags[32];
/* Bitflags showing which entries in prog_string_indizes[] are valid:
* if (_tags[n] & (1 << b)) then _indizes[n*8 + b] is valid.
*/
static char *last_string_constant = NULL;
/* The current (last) string constant, a shared string.
* It is also used to optimize "foo"+"bar" constructs.
*/
static int current_break_stack_need = 0;
/* Current depth of the required switch/break stack at this point
* in a function.
*/
static int max_break_stack_need = 0;
/* Total depth of the required switch/break stack for this function.
* This information is required when computing the 'num_locals'
* for the function header.
*/
static p_int stored_bytes;
/* Size of the program at the last time of store_line_number_info().
*/
static p_int stored_lines;
/* Current linenumber at the last time of store_line_number_info().
*/
static int simple_includes;
/* Number of simple includes since the last real one.
*/
static p_uint last_include_start;
/* Address in A_LINENUMBERS of the last include information.
* It is used to remove information about includes which do
* not generate information ('simple includes').
*/
/*-------------------------------------------------------------------------*/
/* Forward declarations */
struct lvalue_s; /* Defined within YYSTYPE aka %union */
static Bool add_lvalue_code ( struct lvalue_s * lv, int instruction);
static void insert_pop_value(void);
static void arrange_protected_lvalue(p_int, int, p_int, int);
static int insert_inherited(char *,char *, program_t **, function_t *, int, bytecode_p);
/* Returnvalues from insert_inherited(): */
# define INHERITED_NOT_FOUND (-1)
# define INHERITED_WILDCARDED_ARGS (-2)
# define INHERITED_WILDCARDED_NOT_FOUND (-3)
static void store_line_number_relocation(int relocated_from);
int yyparse(void);
%ifdef INITIALIZATION_BY___INIT
static void add_new_init_jump(void);
static void transfer_init_control(void);
static void copy_variables(program_t *, fulltype_t);
static int copy_functions(program_t *, fulltype_t type);
%else
static void copy_variables(program_t *, fulltype_t, svalue_t *);
static void copy_functions(program_t *, fulltype_t type);
%endif
static void fix_function_inherit_indices(program_t *);
static void fix_variable_index_offsets(program_t *);
/*-------------------------------------------------------------------------*/
void
yyerror (char *str)
/* Raise the parse error <str>: usually generate the error message and log it.
* If this is the first error in this file, account the wizard with an error.
* If too many errors occured already, do nothing.
*/
{
char *context;
if (num_parse_error > 5)
return;
context = lex_error_context();
fprintf(stderr, "%s %s line %d: %s%s.\n"
, time_stamp(), current_file, current_line, str, context);
/* TODO: lex should implement a function get_include_stack() which
* TODO:: returns an svalue-array with the current include stack.
* TODO:: This could be printed, and also passed to parse_error().
*/
fflush(stderr);
parse_error(MY_FALSE, current_file, current_line, str, context);
if (num_parse_error == 0)
save_error(str, current_file, current_line);
num_parse_error++;
} /* yyerror() */
/*-------------------------------------------------------------------------*/
void
yyerrorf (char *format, ...)
/* Generate an yyerror() 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);
yyerror(buff);
} /* yyerrorf() */
/*-------------------------------------------------------------------------*/
void
yywarn (char *str)
/* Raise the parse warning <str>: usually generate the warning message and
* log it.
*/
{
char *context;
context = lex_error_context();
fprintf(stderr, "%s %s line %d: Warning: %s%s\n"
, time_stamp(), current_file, current_line, str, context);
/* TODO: lex should implement a function get_include_stack() which
* TODO:: returns an svalue-array with the current include stack.
* TODO:: This could be printed, and also passed to parse_error().
*/
fflush(stderr);
parse_error(MY_TRUE, current_file, current_line, str, context);
if (num_parse_error == 0)
save_error(str, current_file, current_line);
} /* yywarn() */
/*-------------------------------------------------------------------------*/
void
yywarnf (char *format, ...)
/* Generate an yywarn() 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);
yywarn(buff);
} /* yywarnf() */
/*-------------------------------------------------------------------------*/
static void *
yalloc (size_t size)
/* Allocate a block of <size>, add it at the head of the last_yalloced
* list, and return the pointer.
*
* Together with yfree(), this allocator is able to free intermediate
* results in the epilog() which were thrown away due to an error.
* TODO: A stack'ish mempool could do this?
*/
{
char **p;
p = xalloc(size+sizeof(char*));
if (!p)
{
fatal("Out of memory in compiler.\n");
return NULL;
}
*p++ = last_yalloced;
last_yalloced = (char *)p;
return p;
} /* yalloc() */
/*-------------------------------------------------------------------------*/
static void
yfree (void *block)
/* Free the block last allocated by yalloc().
*/
{
char **p;
p = (char **)block;
if (p != (char **)last_yalloced)
{
debug_message("%s Block mismatch", time_stamp());
return;
}
last_yalloced = *--p;
xfree(p);
} /* yfree() */
/*-------------------------------------------------------------------------*/
static char *
ystring_copy (char *str)
/* Duplicate the string <str> using yalloc() and return the new one.
*/
{
char *p;
p = yalloc(strlen(str)+1);
strcpy(p, str);
return p;
} /* ystring_copy() */
/*-------------------------------------------------------------------------*/
static void
add_string_constant (void)
/* Add the string <last_lex_string> to the string in <last_string_constant>.
* This is used to optimize "foo" + "bar" constructs.
*/
{
size_t len1;
char *tmp;
len1 = strlen(last_string_constant);
tmp = alloca(len1 + strlen(last_lex_string) + 1);
strcpy(tmp, last_string_constant);
strcpy(tmp + len1, last_lex_string);
free_string(last_string_constant);
free_string(last_lex_string);
last_string_constant = make_shared_string(tmp);
last_lex_string = NULL;
} /* add_string_constant() */
/*-------------------------------------------------------------------------*/
static char *
realloc_mem_block (mem_block_t *mbp, mp_int size)
/* Resize memblock <mbp> to hold at least <size> bytes, but at least
* double its current size.
*
* Return NULL when out of memory, or a pointer to the newly allocated
* memory area (ie. mbp->block).
*/
{
mp_uint max_size;
char *p;
max_size = mbp->max_size;
do {
max_size *= 2;
} while (size > max_size);
p = rexalloc(mbp->block, max_size);
if (!p)
{
lex_close("Out of memory");
return NULL;
}
mbp->block = p;
mbp->max_size = max_size;
return p;
} /* realloc_mem_block() */
/*-------------------------------------------------------------------------*/
static INLINE void
add_to_mem_block (int n, void *data, size_t size)
/* Add the <data> block of <size> bytes to the memory area <n>.
*/
{
mem_block_t *mbp = &mem_block[n];
if (size)
{
if (mbp->current_size + size > mbp->max_size)
{
if (!realloc_mem_block(mbp, mbp->current_size + size))
return;
}
memcpy(mbp->block + mbp->current_size, data, size);
mbp->current_size += size;
}
} /* add_to_mem_block() */
/*-------------------------------------------------------------------------*/
#define byte_to_mem_block(n, b) \
((void)((mem_block[n].current_size == mem_block[n].max_size \
? !!realloc_mem_block(&mem_block[n],0) : 1) \
? (mem_block[n].block[mem_block[n].current_size++] = (char)(b)) \
: 0)\
)
/* Add the byte <b> to the memory area <n>, which is resized
* if necessary.
*/
/* ============================== TYPES ============================== */
/*-------------------------------------------------------------------------*/
#define BASIC_TYPE(e,t) \
((e) == TYPE_ANY || (e) == (t) || (t) == TYPE_ANY)
/* Return TRUE if <e> and <t> are compatible basic types.
*/
#define TYPE(e,t) \
( BASIC_TYPE((e) & TYPE_MOD_MASK, (t) & TYPE_MOD_MASK) \
|| ( ((e) & TYPE_MOD_POINTER) && ((t) & TYPE_MOD_POINTER) \
&& BASIC_TYPE((e) & (TYPE_MOD_MASK & ~TYPE_MOD_POINTER),\
(t) & (TYPE_MOD_MASK & ~TYPE_MOD_POINTER))\
))
/* Return TRUE if <e> and <t> are compatible basic xor pointer types.
*/
#define MASKED_TYPE(e,t) \
( BASIC_TYPE( (e) , (t) ) \
|| ( (e) == (TYPE_MOD_POINTER|TYPE_ANY) && (t) & TYPE_MOD_POINTER ) \
|| ( (t) == (TYPE_MOD_POINTER|TYPE_ANY) && (e) & TYPE_MOD_POINTER ) \
)
/* Return TRUE if <e> and <t> are compatible basic types, or if both
* are pointer types and one of them is a *ANY.
*/
#define REDEFINED_TYPE(e,t) \
( BASIC_TYPE( (e), (t) ) \
|| ( (t) == (TYPE_MOD_POINTER|TYPE_ANY) ) \
|| ( (e) == (TYPE_MOD_POINTER|TYPE_ANY) ) \
)
/* Return TRUE if type <t> is a proper redefinition of <e>.
* This is the case if <e> and <t> are compatible base types,
* or if one of them is *ANY.
*/
/*-------------------------------------------------------------------------*/
static char *
get_visibility (fulltype_t type)
/* Return (in a static buffer) a textual representation of the visibility
* portion of <type>.
*/
{
static char buff[100];
size_t len;
buff[0] = '\0';
if (type & TYPE_MOD_STATIC)
strcat(buff, "static ");
if (type & TYPE_MOD_NO_MASK)
strcat(buff, "nomask ");
if (type & TYPE_MOD_PRIVATE)
strcat(buff, "private ");
if (type & TYPE_MOD_PROTECTED)
strcat(buff, "protected ");
if (type & TYPE_MOD_PUBLIC)
strcat(buff, "public ");
if (type & TYPE_MOD_VARARGS)
strcat(buff, "varargs ");
len = strlen(buff);
if (len)
buff[len-1] = '\0';
return buff;
} /* get_visibility() */
/*-------------------------------------------------------------------------*/
static char *
get_type_name (fulltype_t type)
/* Return (in a static buffer) a textual representation of <type>.
*/
{
static char buff[100];
static char *type_name[] = { "unknown", "int", "string", "void", "object",
"mapping", "float", "mixed", "closure",
"symbol", "quoted_array", };
Bool pointer = MY_FALSE, reference = MY_FALSE;
buff[0] = '\0';
if (type & TYPE_MOD_STATIC)
strcat(buff, "static ");
if (type & TYPE_MOD_NO_MASK)
strcat(buff, "nomask ");
if (type & TYPE_MOD_PRIVATE)
strcat(buff, "private ");
if (type & TYPE_MOD_PROTECTED)
strcat(buff, "protected ");
if (type & TYPE_MOD_PUBLIC)
strcat(buff, "public ");
if (type & TYPE_MOD_VARARGS)
strcat(buff, "varargs ");
type &= TYPE_MOD_MASK;
if (type & TYPE_MOD_POINTER)
{
pointer = MY_TRUE;
type &= ~TYPE_MOD_POINTER;
}
if (type & TYPE_MOD_REFERENCE)
{
reference = MY_TRUE;
type &= ~TYPE_MOD_REFERENCE;
}
if (type >= sizeof type_name / sizeof type_name[0])
fatal("Bad type %ld\n", (long)type);
strcat(buff, type_name[type]);
strcat(buff," ");
if (pointer)
strcat(buff, "* ");
if (reference)
strcat(buff, "& ");
return buff;
} /* get_type_name() */
/*-------------------------------------------------------------------------*/
static char *
get_two_types (fulltype_t type1, fulltype_t type2)
/* Return (in a static buffer) the text "(<type1> vs. <type2>)".
*/
{
static char buff[100];
strcpy(buff, "( ");
strcat(buff, get_type_name(type1));
strcat(buff, "vs ");
strcat(buff, get_type_name(type2));
strcat(buff, ")");
return buff;
} /* get_two_types() */
/*-------------------------------------------------------------------------*/
static void
type_error (char *str, fulltype_t type)
/* Generate an yyerror with the message "<str>: <type>".
*/
{
char *p;
p = get_type_name(type);
yyerrorf("%s: \"%s\"", str, p);
} /* type_error() */
/*-------------------------------------------------------------------------*/
static void
argument_type_error (int instr, fulltype_t type)
/* Generate an yyerror with the message "Bad argument to <instr>: <type>".
*/
{
char *p;
p = get_type_name(type);
yyerrorf("Bad argument to %s: \"%s\"", instrs[instr].name, p);
} /* argument_type_error() */
/*-------------------------------------------------------------------------*/
static Bool
compatible_types (fulltype_t t1, fulltype_t t2)
/* Compare the two types <t1> and <t2> and return TRUE if they are compatible.
* Rules:
* - every type is compatible to itself
* - TYPE_UNKNOWN is incompatible to everything
* - TYPE_ANY is compatible to everything
* - two POINTER types are compatible if at least one is *TYPE_ANY.
*/
{
if (t1 == TYPE_UNKNOWN || t2 == TYPE_UNKNOWN)
return MY_FALSE;
if (t1 == t2)
return MY_TRUE;
if (t1 == TYPE_ANY || t2 == TYPE_ANY)
return MY_TRUE;
if ((t1 & TYPE_MOD_POINTER) && (t2 & TYPE_MOD_POINTER))
{
if ((t1 & TYPE_MOD_MASK) == (TYPE_ANY|TYPE_MOD_POINTER)
|| (t2 & TYPE_MOD_MASK) == (TYPE_ANY|TYPE_MOD_POINTER))
return MY_TRUE;
}
return MY_FALSE;
} /* compatible_types() */
/*-------------------------------------------------------------------------*/
static INLINE void
add_arg_type (vartype_t type)
/* Add another function argument type to the argument type stack.
*/
{
mem_block_t *mbp = &type_of_arguments;
if (mbp->current_size + sizeof type > mbp->max_size)
{
mbp->max_size *= 2;
mbp->block = rexalloc((char *)mbp->block, mbp->max_size);
}
*(vartype_t*)(mbp->block + mbp->current_size) = type;
mbp->current_size += sizeof type;
} /* add_arg_type() */
/*-------------------------------------------------------------------------*/
static INLINE void
pop_arg_stack (int n)
/* Pop (remove) the last <n> types from the argument stack.
*/
{
type_of_arguments.current_size -= sizeof (vartype_t) * n;
} /* pop_arg_stack() */
/*-------------------------------------------------------------------------*/
static INLINE vartype_t *
get_argument_types_start (int n)
/* Get the type of the <n>th last argument from the stack.
* <n> must be >= 1.
*/
{
return
&((vartype_t *)
(type_of_arguments.block + type_of_arguments.current_size))[ - n];
} /* get_arguments_type_start() */
/*-------------------------------------------------------------------------*/
static INLINE void
check_aggregate_types (int n)
/* The last <n> types on the argument stack are an aggregate type.
* Combine the single types and make sure that none is a reference type.
*/
{
vartype_t *argp, mask;
argp = (vartype_t *) (type_of_arguments.block +
(type_of_arguments.current_size -= sizeof (vartype_t) * n) );
/* We're just interested in TYPE_MOD_REFERENCE, so we preset all
* other bits with 1.
*/
for (mask = ~TYPE_MOD_REFERENCE; --n >= 0; )
{
mask |= *argp++;
}
if (!(~mask & 0xffff))
yyerror("Can't trace reference assignments.");
} /* check_aggregate_types() */
/* ============================= CODEGEN ============================= */
/*-------------------------------------------------------------------------*/
static INLINE char *
realloc_a_program (size_t size)
/* If necessary, increase the allocated size of the A_PROGRAM area so that at
* least <size> more bytes can be stored in it.
*
* Return NULL when out of memory, or a pointer to the (possibly newly
* allocated) memory area (ie. mem_block[A_PROGRAM].block).
*/
{
mem_block_t * mbp = &mem_block[A_PROGRAM];
mp_uint new_size = mbp->current_size + size;
if (new_size <= mbp->max_size)
return mbp->block;
return realloc_mem_block(mbp, new_size);
} /* realloc_a_program() */
/*-------------------------------------------------------------------------*/
#define ins_byte(b) byte_to_mem_block(A_PROGRAM, b)
#ifndef ins_byte
static INLINE void
ins_byte (unsigned char b)
/* Add the byte <b> to the A_PROGRAM area.
*/
{
if (mem_block[A_PROGRAM].current_size == mem_block[A_PROGRAM].max_size ) {
if (!realloc_a_program(1))
{
yyerrorf("Out of memory: program size %lu\n"
, mem_block[A_PROGRAM].current_size + 1);
return;
}
}
mem_block[A_PROGRAM].block[mem_block[A_PROGRAM].current_size++] = b;
} /* ins_byte() */
#endif
/*-------------------------------------------------------------------------*/
static void
ins_f_code (unsigned int b)
/* Add the instruction <b> to the A_PROGRAM area, taking care of encoding
* multi-byte instructions properly.
*/
{
if (b > 0x100)
ins_byte(b >> F_ESCAPE_BITS);
ins_byte(b);
} /* ins_f_code() */
/*-------------------------------------------------------------------------*/
static void
ins_short (short l)
/* Add the 2-byte number <l> to the A_PROGRAM area in a fixed byteorder.
*/
{
if (realloc_a_program(2))
{
mp_uint current_size;
char *dest;
current_size = CURRENT_PROGRAM_SIZE;
CURRENT_PROGRAM_SIZE = current_size + 2;
dest = mem_block[A_PROGRAM].block + current_size;
PUT_SHORT(dest, l);
}
else
{
yyerrorf("Out of memory: program size %lu\n"
, mem_block[A_PROGRAM].current_size + 2);
}
} /* ins_short() */
/*-------------------------------------------------------------------------*/
static void
upd_short (mp_uint offset, short l)
/* Store the 2-byte number <l> at <offset> in the A_PROGRAM are in
* a fixed byteorder.
*/
{
char *dest;
dest = mem_block[A_PROGRAM].block + offset;
PUT_SHORT(dest, l);
} /* upd_short() */
/*-------------------------------------------------------------------------*/
static short
read_short (mp_uint offset)
/* Return the 2-byte number stored at <offset> in the A_PROGRAM area.
*/
{
short l;
char *dest;
dest = mem_block[A_PROGRAM].block + offset;
GET_SHORT(l, dest);
return l;
} /* read_short() */
%ifdef INITIALIZATION_BY___INIT
/*-------------------------------------------------------------------------*/
static void
upd_offset (mp_uint offset, long l)
/* Store the 3-byte number <l> at <offset> in the A_PROGRAM are in
* a fixed byteorder.
*/
{
char *dest;
dest = mem_block[A_PROGRAM].block + offset;
STORE_UINT8(dest, l>>16);
PUT_SHORT(dest, l & 0xffff);
} /* upd_offset() */
%endif /* INITIALIZATION_BY___INIT */
/*-------------------------------------------------------------------------*/
static void
ins_long (int32 l)
/* Add the 4-byte number <l> to the A_PROGRAM area in a fixed byteorder.
*/
{
if (realloc_a_program(4))
{
mp_uint current_size;
char *dest;
current_size = CURRENT_PROGRAM_SIZE;
CURRENT_PROGRAM_SIZE = current_size + 4;
dest = mem_block[A_PROGRAM].block + current_size;
PUT_INT32(dest, l);
}
else
{
yyerrorf("Out of memory: program size %lu\n"
, mem_block[A_PROGRAM].current_size + 4);
}
} /* ins_long() */
/*-------------------------------------------------------------------------*/
/* The following macros are used for a speedy codegeneration within bigger
* functions.
*
* To insert at max <n> bytes, the function has to declare
*
* PREPARE_INSERT(n)
*
* among the variables and can the use the following macros to add bytes:
*
* add_byte(b): to add byte <b> to the program
* add_short(s): to add short <s> to the program
*/
#define PREPARE_INSERT(n) \
bytecode_p __PREPARE_INSERT__p = (\
realloc_a_program(n) ? (PROGRAM_BLOCK + CURRENT_PROGRAM_SIZE) : NULL);
#define add_byte(b) (void) STORE_INT8(__PREPARE_INSERT__p, (b))
#define add_short(s) STORE_SHORT(__PREPARE_INSERT__p, (s))
/*-------------------------------------------------------------------------*/
static void
push_address (void)
/* Push the current program size as address onto the compiler stack.
*/
{
if (comp_stackp >= COMPILER_STACK_SIZE)
{
yyerror("Compiler stack overflow");
/* Don't store the address, but keep proper track of the depth.
*/
comp_stackp++;
return;
}
comp_stack[comp_stackp++] = mem_block[A_PROGRAM].current_size;
} /* push_address() */
/*-------------------------------------------------------------------------*/
static void
push_explicit (p_int address)
/* Push the program <address> onto the compiler stack.
*/
{
if (comp_stackp >= COMPILER_STACK_SIZE)
{
yyerror("Compiler stack overflow");
/* Don't store the address, but keep proper track of the depth.
*/
comp_stackp++;
return;
}
comp_stack[comp_stackp++] = address;
} /* push_explicit() */
/*-------------------------------------------------------------------------*/
static p_int
pop_address (void)
/* Pop the most recent stored address from the compiler stack and return
* it.
*/
{
if (comp_stackp == 0)
fatal("Compiler stack underflow.\n");
if (comp_stackp > COMPILER_STACK_SIZE)
{
/* Nothing to retrieve, but keep track of the depth */
--comp_stackp;
return 0;
}
return comp_stack[--comp_stackp];
} /* pop_address() */
/*-------------------------------------------------------------------------*/
static Bool
fix_branch (int ltoken, p_int dest, p_int loc)
/* Backpatch a branch instruction at <loc> to jump to <dest>.
* If the offset exceeds the 255 range, the branch instruction is changed
* into its long-branch variant <ltoken>.
*
* Return TRUE if the long branch had to be used, FALSE otherwise.
* TODO: This really confuses the line number detection code, as suddenly
* TODO:: the recorded offset are no longer accurate.
*/
{
p_int offset; /* The branch offset */
offset = dest - (loc +1);
if (offset > 0xff)
{
/* We need a long branch. That also means that we have to
* move the following code and adapt remembered addresses.
*/
p_int i, j;
bytecode_p p;
mem_block[A_PROGRAM].block[loc] = 0; /* Init it */
/* Update the break address */
if ( current_break_address > loc
&& !(current_break_address & (BREAK_ON_STACK|BREAK_DELIMITER) ) )
{
for (i = current_break_address; (j = read_short(i)) > loc; )
{
upd_short(i, j+1);
i = j;
}
current_break_address++;
}
/* Update the continue address */
if ( (current_continue_address & CONTINUE_ADDRESS_MASK) > loc
&& !(current_continue_address & CONTINUE_DELIMITER ) )
{
for(i = current_continue_address & CONTINUE_ADDRESS_MASK;
(j=read_short(i)) > loc; )
{
upd_short(i, j+1);
i = j;
}
current_continue_address++;
}
ins_byte(0); /* Just to make sure the memory is there */
/* Move the code */
p = PROGRAM_BLOCK + mem_block[A_PROGRAM].current_size-1;
i = mem_block[A_PROGRAM].current_size - loc;
for( ; --i >= 0; --p )
{
PUT_CODE(p, GET_CODE(p-1));
}
/* Store the new branch instruction */
PUT_CODE(p, ltoken);
upd_short(loc, offset+2);
if (offset > 0x7ffd)
yyerror("offset overflow");
return MY_TRUE;
}
else
{
/* Just update the offset */
mem_block[A_PROGRAM].block[loc] = offset;
return MY_FALSE;
}
} /* fix_branch() */
/*-------------------------------------------------------------------------*/
static bytecode_p
yyget_space (p_int size)
/* Callback function for switch: return a pointer to <size> more bytes
* in the program area.
*/
{
if (realloc_a_program(size))
{
CURRENT_PROGRAM_SIZE += size;
return PROGRAM_BLOCK + CURRENT_PROGRAM_SIZE - size;
}
yyerrorf("Out of memory: program size %lu\n"
, mem_block[A_PROGRAM].current_size + size);
return NULL;
} /* yyget_space() */
/*-------------------------------------------------------------------------*/
static void
yymove_switch_instructions (int len, p_int blocklen)
/* Callback function for switch: move the <blocklen> bytecodes at <switch_pc>
* back by <len> bytes to <switch_pc>+<len>. A continue address in the
* affected area is corrected.
*/
{
mp_int i, j;
if (realloc_a_program(len))
{
CURRENT_PROGRAM_SIZE += len;
/* Adjust the continue address, if any */
if ( (current_continue_address & CONTINUE_ADDRESS_MASK) > switch_pc
&& !(current_continue_address & CONTINUE_DELIMITER ) )
{
for(i = current_continue_address & CONTINUE_ADDRESS_MASK;
(j=read_short(i)) > switch_pc; )
{
upd_short(i, j+len);
i = j;
}
current_continue_address += len;
}
move_memory(
mem_block[A_PROGRAM].block + switch_pc + len,
mem_block[A_PROGRAM].block + switch_pc,
blocklen
);
}
else
{
yyerrorf("Out of memory: program size %lu\n"
, mem_block[A_PROGRAM].current_size + len);
}
} /* yymove_switch_instructions() */
/*-------------------------------------------------------------------------*/
static void
yycerrorl (char *s1, char *s2, int line1, int line2)
/* Callback function for switch: Raise an error <s1> in file <s2> at
* lines <line1> and <line2>.
* <s1> may contain one '%s' to insert s2, <s2> may contain one or
* or two '%d' to insert line1 and line2.
*/
{
char buff[100];
sprintf(buff, s2, line1, line2);
yyerrorf(s1, buff);
} /* yycerrorl() */
/*-------------------------------------------------------------------------*/
static void
update_lop_branch ( p_uint address, int instruction )
/* <address> points to the branch offset value of an LAND/LOR operation,
* currently set to 0. Update that offset to branch to the current end
* of the program.
*
* If that branch is too long, the code is rewritten:
*
* Original: Rewritten:
*
* <expr1> <expr1>
* LOR/LAND l DUP
* <expr2> LBRANCH_<instruction>
* l: POP_VALUE
* <expr2>
* l:
*
* The extra DUP compensates the svalue the LBRANCH eats.
* The LBRANCH_<instruction> needs to be passed suiting the logical
* operator: LBRANCH_WHEN_ZERO for LAND, LBRANCH_WHEN_NON_ZERO for LOR.
*/
{
p_int offset;
last_expression = -1;
offset = mem_block[A_PROGRAM].current_size - ( address + 1);
if (offset > 0xff)
{
/* A long branch is needed */
int i;
bytecode_p p;
ins_short(0);
ins_byte(0);
p = PROGRAM_BLOCK + mem_block[A_PROGRAM].current_size-1;
for (i = offset; --i >= 0; --p )
*p = p[-3];
p[-4] = F_DUP;
p[-3] = instruction;
upd_short(address+1, offset+3);
if (offset > 0x7ffc)
yyerror("offset overflow");
p[0] = F_POP_VALUE;
}
else
{
mem_block[A_PROGRAM].block[address] = offset;
}
} /* update_lop_branch() */
/* ======================== LOCALS and SCOPES ======================== */
/*-------------------------------------------------------------------------*/
void
free_all_local_names (void)
/* Free all local names, and reset the counters.
*/
{
ident_t *p,*q;
for (q = all_locals; NULL != (p = q);)
{
q = p->next_all;
free_shared_identifier(p);
}
all_locals = NULL;
current_number_of_locals = 0;
max_number_of_locals = 0;
current_break_stack_need = 0;
max_break_stack_need = 0;
} /* free_all_local_names() */
/*-------------------------------------------------------------------------*/
static void
free_local_names (int depth)
/* Free all locals in the all_locals list which are of higher or
* the same <depth>, and adjust the counters.
* A <depth> of 0 is equivalent to calling free_all_local_names().
*/
{
ident_t *q;
if (!depth)
{
free_all_local_names();
return;
}
/* Are the locals of the given depth? */
if (!all_locals || all_locals->u.local.depth < depth)
return;
if (all_locals->u.local.depth > depth)
fatal("List of locals clobbered: depth %d, block_depth %d\n"
, all_locals->u.local.depth, depth);
while (all_locals != NULL && all_locals->u.local.depth >= depth)
{
q = all_locals;
all_locals = q->next_all;
free_shared_identifier(q);
current_number_of_locals--;
}
} /* free_local_names() */
/*-------------------------------------------------------------------------*/
static ident_t *
add_local_name (ident_t *ident, fulltype_t type, int depth)
/* Declare a new local variable <ident> with the type <type> on
* the scope depth <depth>.
* Return the (adjusted) ident for the new variable.
*/
{
if ((type & PRIMARY_TYPE_MASK) == TYPE_VOID)
{
yyerrorf( "Illegal to define variable '%s' as type 'void'"
, ident->name);
}
if (current_number_of_locals >= MAX_LOCAL
|| current_number_of_locals >= 256)
yyerror("Too many local variables");
else
{
if (ident->type != I_TYPE_UNKNOWN)
{
/* We're overlaying some other definition */
ident = make_shared_identifier(ident->name, I_TYPE_LOCAL, depth);
}
/* Initialize the ident */
ident->type = I_TYPE_LOCAL;
ident->u.local.num = current_number_of_locals;
ident->u.local.depth = depth;
/* Put the ident into the list of all locals */
if (all_locals && all_locals->u.local.depth > depth)
fatal("List of locals clobbered: depth %d, adding depth %d\n"
, all_locals->u.local.depth, depth);
ident->next_all = all_locals;
all_locals = ident;
/* Record the type */
type_of_locals[current_number_of_locals] = type;
full_type_of_locals[current_number_of_locals++] = type;
/* And update the scope information */
if (current_number_of_locals > max_number_of_locals)
max_number_of_locals = current_number_of_locals;
block_scope[depth-1].num_locals++;
}
return ident;
} /* add_local_name() */
/*-------------------------------------------------------------------------*/
static void
init_scope (int depth)
/* Initialize the block_scope entry for block_depth <depth>.
*/
{
block_scope[depth-1].num_locals = 0;
block_scope[depth-1].first_local = current_number_of_locals;
block_scope[depth-1].addr = 0;
} /* init_scope() */
/*-------------------------------------------------------------------------*/
static void
enter_block_scope (void)
/* Enter a new scope and initialize it (if use_local_scopes requires it).
*/
{
if (block_depth == COMPILER_STACK_SIZE)
yyerror("Too deep nesting of local blocks.\n");
if (use_local_scopes)
{
block_depth++;
init_scope(block_depth);
}
} /* enter_block_scope() */
/*-------------------------------------------------------------------------*/
static void
leave_block_scope (void)
/* Leave the current scope (if use_local_scopes requires it), freeing
* all local names defined in that scope.
*/
{
if (use_local_scopes)
{
free_local_names(block_depth);
block_depth--;
}
} /* leave_block_scope() */
/*-------------------------------------------------------------------------*/
static ident_t *
lookup_local (int num)
/* Lookup the ident_t structure for local variable <num>.
*/
{
ident_t *p, *q;
/* First, find the declaration of this local */
q = NULL;
for (p = all_locals; p != NULL; p = p->next_all)
{
if (p->u.local.num == num)
{
q = p;
break;
}
}
/* q should be set here and point to the previous declaration.
*/
if (!q)
fatal("Local identifier %ld not found in list.\n", (long)num);
return q;
} /* lookup_local() */
/*-------------------------------------------------------------------------*/
static ident_t *
redeclare_local (int num, fulltype_t type, int depth)
/* Redeclare a local name, identified by <num>, to <type> at <depth>.
* If this happens on a deeper level, it is legal: the new declaration
* is added and the new identifier is returned.
* If it is illegal, an yyerror() is risen and the ident of the older
* declaration is returned for error recovery.
*/
{
ident_t *p, *q;
if (all_locals && all_locals->u.local.depth > depth)
{
fatal("List of locals clobbered: list depth %d, "
"block depth %d\n"
, all_locals->u.local.depth, depth);
}
/* First, find the previous declaration of this local */
q = NULL;
for (p = all_locals; p != NULL; p = p->next_all)
{
if (p->u.local.num == num)
{
/* We found the identifier, and due to the list properties
* it is also the one with deepest depth.
*/
q = p;
break;
}
}
/* q should be set here and point to the previous declaration.
* If it is of lower depth, it may be shadowed. However, it
* is not possible to shadow an argument (depth 1) with
* a function-local variable (depth 2).
*/
if (!q)
fatal("Local identifier %ld not found in list.\n", (long)num);
if (q->u.local.depth >= depth
|| (q->u.local.depth == 1 && depth == 2)
)
{
yyerrorf("Illegal to redeclare local name '%s'", q->name);
}
else
{
/* TODO: Add a warning for shadowed variable */
q = add_local_name(q, type, depth);
}
return q;
} /* redeclare_local() */
/* ====================== GLOBALS and FUNCTIONS ====================== */
/*-------------------------------------------------------------------------*/
static unsigned short
store_argument_types ( int num_arg )
/* Store the <num_arg> argument types from global type_of_locals[] into
* the proper memblock and return the new argument start index.
* It is task of the caller to store this start index where it belongs.
*
* If exact_types are not required, the function just returns
* INDEX_START_NONE.
*/
{
unsigned short argument_start_index;
/* Store the function arguments, if required.
*/
if (!exact_types)
{
argument_start_index = INDEX_START_NONE;
}
else
{
int i;
/* Save the argument types.
*/
argument_start_index = ARGTYPE_COUNT;
for (i = 0; i < num_arg; i++)
{
add_to_mem_block(A_ARGUMENT_TYPES, &type_of_locals[i],
sizeof type_of_locals[i]);
}
}
return argument_start_index;
} /* store_argument_types() */
/*-------------------------------------------------------------------------*/
static int
define_new_function ( Bool complete, ident_t *p, int num_arg, int num_local
, p_int offset, funflag_t flags, fulltype_t type)
/* Define a new function <p> with the characteristics <num_arg>, <num_local>,
* program <offset>, <flags> and <type>.
* Result is the number (index) of the function.
*
* The function is called whenever a function header (return type, name
* and arguments) has been parsed - <complete> is FALSE then. Additionally,
* the function is called as well after a functionbody has been parsed,
* <complete> is TRUE then.
*
* This function is called at least twice for all function definitions:
* first as prototype (flags & NAME_PROTOTYPE) when the function def is
* encountered, then a second time for real when the function has been
* completed. Explicite prototypes can cause additional calls.
*/
{
int num;
function_t fun;
unsigned short argument_start_index;
flags |= type & ~TYPE_MOD_MASK; /* Move the visibility-info into flags */
do {
function_t *funp;
Bool args_differ, compare_args;
if (p->type != I_TYPE_GLOBAL) break;
if ((num = p->u.global.function) < 0) break;
funp = FUNCTION(num);
if ((funp->flags & (NAME_INHERITED|TYPE_MOD_PRIVATE))
== (NAME_INHERITED|TYPE_MOD_PRIVATE))
{
break;
}
/* The function was already defined. It may be one of several reasons:
*
* 1. There has been a prototype.
* 2. There was the same function defined by inheritance.
* 3. This function has been called, but not yet defined.
* 4. The function is defined twice.
* 5. A "late" prototype has been encountered.
*/
args_differ = MY_FALSE;
compare_args = MY_FALSE;
/* The following checks are useful only when done before
* a functionbody appears, otherwise the warning/error message
* line numbers will be misleading.
*/
if (!complete)
{
if ((funp->flags & TYPE_MOD_NO_MASK)
&& !(funp->flags & (NAME_PROTOTYPE|NAME_UNDEFINED))
&& ((flags & (NAME_PROTOTYPE|NAME_UNDEFINED)) == (NAME_PROTOTYPE|NAME_UNDEFINED))
)
yyerrorf("Illegal to redefine 'nomask' function \"%s\"", p->name);
if (!(funp->flags & (NAME_UNDEFINED|NAME_PROTOTYPE|NAME_INHERITED) ) )
{
yyerrorf("Redeclaration of function %s.", p->name);
if ( !(flags & NAME_PROTOTYPE) )
free_string(p->name);
return num;
}
/* It was either an undefined but used function, or an inherited
* function. In both cases, we now consider this to be THE new
* definition. It might also have been a prototype to an already
* defined function.
*
* Check arguments only when types are supposed to be tested,
* and if this function really has been defined already.
*
* 'nomask' functions may not be redefined.
*/
if (exact_types && funp->type != TYPE_UNKNOWN)
{
fulltype_t t1, t2;
if (funp->num_arg > num_arg && !(funp->flags & TYPE_MOD_VARARGS))
yyerrorf("Incorrect number of arguments in redefinition of '%s'.", p->name);
else if (funp->num_arg == num_arg
&& ((funp->flags ^ flags) & TYPE_MOD_XVARARGS)
&& !(funp->flags & TYPE_MOD_VARARGS))
yyerrorf("Incorrect number of arguments in redefinition of '%s'.", p->name);
else
{
unsigned short first_arg;
first_arg = ARGUMENT_INDEX(num);
if (first_arg == INDEX_START_NONE)
{
if (num_arg && !(funp->flags & NAME_TYPES_LOST) )
yyerrorf(
"Redefined function '%s' not compiled with type testing."
, p->name
);
}
else
{
/* We can compare the arguments */
compare_args = MY_TRUE;
}
} /* cases (number of arguments) */
/* If it's a prototype->function redefinition, check if the
* visibility is conserved.
*/
{
# define TYPE_MOD_VIS \
( TYPE_MOD_NO_MASK \
| TYPE_MOD_PRIVATE | TYPE_MOD_PUBLIC \
| TYPE_MOD_PROTECTED)
fulltype_t f1 = funp->flags;
fulltype_t f2 = flags;
/* Smooth out irrelevant differences */
if (f1 & TYPE_MOD_STATIC) f1 |= TYPE_MOD_PROTECTED;
if (f2 & TYPE_MOD_STATIC) f2 |= TYPE_MOD_PROTECTED;
if (!(f1 & (NAME_INHERITED|NAME_TYPES_LOST))
&& ((f1 ^ f2) & TYPE_MOD_VIS)
)
{
char buff[100];
strcpy(buff, get_visibility(funp->flags));
yywarnf("Inconsistent declaration of '%s': Visibility changed from '%s' to '%s'"
, p->name, buff, get_visibility(flags));
}
# undef TYPE_MOD_VIS
}
/* Check if the 'varargs' attribute is conserved */
t1 = type & TYPE_MOD_MASK;
t2 = funp->type & TYPE_MOD_MASK;
if (!MASKED_TYPE(t1, t2))
{
if (pragma_pedantic)
yyerrorf("Inconsistent declaration of '%s': Return type mismatch %s", p->name, get_two_types(t2, t1));
else
yywarnf("Inconsistent declaration of '%s': Return type mismatch %s", p->name, get_two_types(t2, t1));
}
if (pragma_pedantic
&& (funp->flags ^ flags) & TYPE_MOD_VARARGS
&& funp->flags & TYPE_MOD_VARARGS
)
{
yywarnf("Redefinition of '%s' loses 'varargs' modifier."
, p->name);
}
/* Check that the two argument lists are compatible */
if (compare_args)
{
int i;
unsigned short first_arg;
vartype_t *argp;
int num_args = num_arg;
/* Don't check newly added arguments */
if (num_args > funp->num_arg)
num_args = funp->num_arg;
first_arg = ARGUMENT_INDEX(num);
argp = (vartype_t *)mem_block[A_ARGUMENT_TYPES].block
+ first_arg;
if (funp->flags & TYPE_MOD_XVARARGS)
num_args--; /* last argument is ok */
for (i = 0; i < num_args; i++ )
{
t1 = type_of_locals[i] & TYPE_MOD_RMASK;
t2 = argp[i] & TYPE_MOD_MASK;
if (!MASKED_TYPE(t1, t2))
{
args_differ = MY_TRUE;
if (pragma_pedantic)
yyerrorf("Argument type mismatch in "
"redefinition of '%s': arg %d %s"
, p->name, i+1, get_two_types(t1, t2)
);
else
yywarnf("Argument type mismatch in "
"redefinition of '%s': arg %d %s"
, p->name, i+1, get_two_types(t1, t2)
);
}
} /* for (all args) */
} /* if (compare_args) */
} /* if (exact_types && already defined) */
} /* if (!complete) */
if (strcmp(p->name, "heart_beat") == 0)
heart_beat = num;
/* If it was yet another prototype, then simply return. */
if (flags & NAME_PROTOTYPE)
{
return num;
}
/* This is the completion of an earlier prototype: check
* and update the arguments if necessary, and flesh
* out the function structure.
*/
if (funp->num_arg != num_arg || args_differ)
{
/* Arguments changed. The only reasonable way this can happen
* is if this function redefined an inherited one.
* For that case, we re-create the arguments, for all other cases
* (to be on the safe side), we turn off type
* checking as we have no way of deciding which definition is the
* correct one.
*/
if (funp->flags & NAME_INHERITED)
{
funp->num_arg = num_arg;
ARGUMENT_INDEX(num) = store_argument_types(num_arg);
}
else
{
funp->num_arg = num_arg;
ARGUMENT_INDEX(num) = INDEX_START_NONE;
flags |= NAME_TYPES_LOST;
}
}
funp->num_local = num_local;
funp->flags = flags;
funp->offset.pc = offset;
funp->type = type;
/* That's it */
return num;
} while(0); /* Test and handle for already defined functions */
/* It's a new function! */
if (strcmp(p->name, "heart_beat") == 0)
heart_beat = FUNCTION_COUNT;
/* Fill in the function_t */
fun.name = p->name; /* adopt the ref */
fun.offset.pc = offset;
fun.flags = flags;
fun.num_arg = num_arg;
fun.num_local = num_local; /* will be updated later */
fun.type = type;
num = FUNCTION_COUNT;
if (p->type != I_TYPE_GLOBAL)
{
/* This is the first _GLOBAL use of this identifier:
* make an appropriate entry in the identifier table.
*/
if (p->type != I_TYPE_UNKNOWN)
{
/* The ident has been used before otherwise, so
* get a fresh structure.
*/
p = make_shared_identifier(p->name, I_TYPE_GLOBAL, 0);
}
/* should be I_TYPE_UNKNOWN now. */
p->type = I_TYPE_GLOBAL;
p->u.global.variable = I_GLOBAL_VARIABLE_OTHER;
p->u.global.efun = I_GLOBAL_EFUN_OTHER;
p->u.global.sim_efun = I_GLOBAL_SEFUN_OTHER;
p->next_all = all_globals;
all_globals = p;
}
else if (p->u.global.variable == I_GLOBAL_VARIABLE_FUN)
{
/* The previous _GLOBAL use is the permanent efun definition:
* mark the efun as shadowed.
*/
efun_shadow_t *q;
q = xalloc(sizeof(efun_shadow_t));
q->shadow = p;
q->next = all_efun_shadows;
all_efun_shadows = q;
}
/* else: Other cases don't need special treatment */
p->u.global.function = num;
/* Store the function_t in the functions area */
add_to_mem_block(A_FUNCTIONS, &fun, sizeof fun);
/* Store the function arguments, if required,
* and save the position of the argument types.
*/
argument_start_index = store_argument_types(num_arg);
add_to_mem_block( A_ARGUMENT_INDEX, &argument_start_index
, sizeof argument_start_index);
return num;
} /* define_new_function() */
/*-------------------------------------------------------------------------*/
%ifdef INITIALIZATION_BY___INIT
static void
define_variable (ident_t *name, fulltype_t flags)
%else /* then !INITIALIZATION_BY___INIT */
static void
define_variable (ident_t *name, fulltype_t flags, svalue_t *svp)
%endif /* INITIALIZATION_BY___INIT */
/* Define a new global variable <name> of type <flags>.
* If !INITIALIZATION_BY___INIT, then <svp> is the initializer for the
* variable.
*/
{
variable_t dummy;
int n;
if ((flags & PRIMARY_TYPE_MASK) == TYPE_VOID)
{
yyerrorf( "Illegal to define variable '%s' as type 'void'"
, name->name);
}
if (name->type != I_TYPE_GLOBAL)
{
/* This is the first _GLOBAL use of this identifier:
* make an appropriate entry in the identifier table.
*/
if (name->type != I_TYPE_UNKNOWN)
{
/* The ident has been used before otherwise, so
* get a fresh structure.
*/
name = make_shared_identifier(name->name, I_TYPE_GLOBAL, 0);
}
name->type = I_TYPE_GLOBAL;
name->u.global.function = I_GLOBAL_FUNCTION_VAR;
name->u.global.variable = I_GLOBAL_VARIABLE_OTHER; /* mark it as 'yet undef' for now */
name->u.global.efun = I_GLOBAL_EFUN_OTHER;
name->u.global.sim_efun = I_GLOBAL_SEFUN_OTHER;
name->next_all = all_globals;
all_globals = name;
}
else if (name->u.global.function == I_GLOBAL_FUNCTION_EFUN)
{
/* The previous _GLOBAL use is the permanent efun definition:
* mark the efun as shadowed.
*/
efun_shadow_t *q;
q = xalloc(sizeof(efun_shadow_t));
q->shadow = name;
q->next = all_efun_shadows;
all_efun_shadows = q;
}
/* If the variable already exists, make sure that we can redefine it */
if ( (n = name->u.global.variable) >= 0)
{
/* Visible nomask variables can't be redefined */
if ( VARIABLE(n)->flags & TYPE_MOD_NO_MASK && !(flags & NAME_HIDDEN))
yyerrorf( "Illegal to redefine 'nomask' variable '%s'"
, name->name);
/* We can redefine inherited variables if they are private or hidden,
* or if one of them is static.
*/
if ( ( !(VARIABLE(n)->flags & NAME_INHERITED)
|| ( !(VARIABLE(n)->flags & (TYPE_MOD_PRIVATE|NAME_HIDDEN))
&& !((flags ^ VARIABLE(n)->flags) & TYPE_MOD_STATIC)
)
)
&& !(flags & NAME_INHERITED)
)
{
if (VARIABLE(n)->flags & NAME_INHERITED)
yyerrorf("Illegal to redefine inherited variable '%s'", name->name);
else
yyerrorf("Illegal to redefine global variable '%s'", name->name);
}
if (((flags ^ VARIABLE(n)->flags) & (TYPE_MOD_STATIC|TYPE_MOD_PRIVATE))
== TYPE_MOD_STATIC
&& !(flags & NAME_INHERITED)
)
{
yywarnf("Redefining inherited %s variable '%s' with a %s variable"
, (VARIABLE(n)->flags & TYPE_MOD_STATIC)
? "nosave" : "non-nosave"
, name->name
, (flags & TYPE_MOD_STATIC) ? "nosave" : "non-nosave"
);
}
/* Make sure that at least one of the two definitions is 'static'.
* The variable which has not been inherited gets first pick.
*/
if (flags & NAME_INHERITED)
{
flags |= ~(VARIABLE(n)->flags) & TYPE_MOD_STATIC;
}
else
{
VARIABLE(n)->flags |= ~flags & TYPE_MOD_STATIC;
}
}
/* Prepare the new variable_t */
if (flags & TYPE_MOD_NOSAVE)
{
/* 'nosave' is internally saved as 'static' (historical reason) */
flags |= TYPE_MOD_STATIC;
flags ^= TYPE_MOD_NOSAVE;
}
dummy.name = ref_string(name->name);
dummy.flags = flags;
if (flags & TYPE_MOD_VIRTUAL)
{
if (!(flags & NAME_HIDDEN))
name->u.global.variable = VIRTUAL_VAR_TAG | V_VARIABLE_COUNT;
add_to_mem_block(A_VIRTUAL_VAR, &dummy, sizeof dummy);
%ifndef INITIALIZATION_BY___INIT
add_to_mem_block(A_VIRTUAL_VAR_VALUES, svp, sizeof *svp);
%endif /* INITIALIZATION_BY___INIT */
}
else
{
if (!(flags & NAME_HIDDEN))
name->u.global.variable = NV_VARIABLE_COUNT;
add_to_mem_block(A_VARIABLES, &dummy, sizeof dummy);
%ifndef INITIALIZATION_BY___INIT
add_to_mem_block(A_VARIABLE_VALUES, svp, sizeof *svp);
%endif /* INITIALIZATION_BY___INIT */
}
} /* define_variable() */
/*-------------------------------------------------------------------------*/
static void
redeclare_variable (ident_t *name, fulltype_t flags, int n)
/* The variable <name> is inherited virtually with number <n>.
* Redeclare it from its original type to <flags>.
*/
{
if (name->type != I_TYPE_GLOBAL)
{
/* This is the first _GLOBAL use of this identifier:
* make an appropriate entry in the identifier table.
*/
/* I_TYPE_UNKNOWN */
name->type = I_TYPE_GLOBAL;
name->u.global.function = I_GLOBAL_FUNCTION_VAR;
name->u.global.variable = I_GLOBAL_VARIABLE_OTHER; /* default: it's hidden */
name->u.global.efun = I_GLOBAL_EFUN_OTHER;
name->u.global.sim_efun = I_GLOBAL_SEFUN_OTHER;
name->next_all = all_globals;
all_globals = name;
}
else if (name->u.global.function == I_GLOBAL_FUNCTION_EFUN)
{
/* The previous _GLOBAL use is the permanent efun definition:
* mark the efun as shadowed.
*/
efun_shadow_t *q;
q = xalloc(sizeof(efun_shadow_t));
q->shadow = name;
q->next = all_efun_shadows;
all_efun_shadows = q;
}
/* else: the variable is inherited after it has been defined
* in the child program.
*/
/* The variable is hidden, do nothing else */
if (flags & NAME_HIDDEN)
return;
if (name->u.global.variable >= 0 && name->u.global.variable != n)
{
if (VARIABLE(name->u.global.variable)->flags & TYPE_MOD_NO_MASK )
yyerrorf( "Illegal to redefine 'nomask' variable '%s'"
, name->name);
}
else if (V_VARIABLE(n)->flags & TYPE_MOD_NO_MASK
&& !(V_VARIABLE(n)->flags & NAME_HIDDEN)
&& (V_VARIABLE(n)->flags ^ flags) & TYPE_MOD_STATIC )
{
yyerrorf("Illegal to redefine 'nomask' variable \"%s\"", name->name);
}
if (flags & TYPE_MOD_NOSAVE)
{
/* 'nosave' is internally saved as 'static' (historical reason) */
flags |= TYPE_MOD_STATIC;
flags ^= TYPE_MOD_NOSAVE;
}
name->u.global.variable = n;
V_VARIABLE(n)->flags = flags;
} /* redeclare_variable() */
/*-------------------------------------------------------------------------*/
static int
verify_declared (ident_t *p)
/* Check that <p> is a global variable.
* If yes, return the index of that variable, -1 otherwise.
*/
{
int r;
if (p->type != I_TYPE_GLOBAL
|| (r = p->u.global.variable) < 0)
{
yyerrorf("Variable %s not declared !", p->name);
return -1;
}
return r;
} /* verify_declared() */
/* ========================= PROGRAM STRINGS ========================= */
/*-------------------------------------------------------------------------*/
static short
store_prog_string (char *str)
/* Add the shared string <str> to the strings used by the program.
* The function takes care that the same string is not stored twice.
* Result is the index of the string in the table, the function
* adopts the reference of <str>.
*/
{
mp_uint str_size, next_size;
long hash;
char mask, *tagp;
int i, *indexp;
/* Compute the hash and the tagmask for the hash table */
/* TODO: This assumes 32-Bit pointers */
hash = (long)str ^ (long)str >> 16;
hash = (hash ^ hash >> 8);
mask = 1 << (hash & 7);
hash = hash & 0xff;
indexp = &prog_string_indizes[hash];
tagp = &prog_string_tags[hash >> 3];
if (*tagp & mask)
{
/* There is a hash chain for this hash: search the
* string in there.
*/
i = *indexp;
for(;;)
{
if ( PROG_STRING(i) == str )
{
free_string(str); /* Drop the extra ref. */
last_string_is_new = MY_FALSE;
return i;
}
if ((i = PROG_STRING_NEXT(i)) < 0)
break;
}
/* Not found: re-get the initial 'next'-index */
i = *indexp;
}
else
{
/* The first time this hash shows up (which also implies
* that <str> is a new string.
*/
*tagp |= mask;
i = -1;
}
/* Add a totally new string */
str_size = mem_block[A_STRINGS].current_size;
next_size = mem_block[A_STRING_NEXT].current_size;
/* Make sure we have enough memory */
if (str_size + sizeof(char *) > mem_block[A_STRINGS].max_size
|| next_size + sizeof(int) > mem_block[A_STRING_NEXT].max_size
)
{
if (!realloc_mem_block(&mem_block[A_STRINGS], 0)
|| !realloc_mem_block(&mem_block[A_STRING_NEXT], 0))
{
if (i < 0)
*tagp &= ~mask;
last_string_is_new = MY_FALSE;
return 0;
}
}
/* Add the string pointer */
mem_block[A_STRINGS].current_size = str_size + sizeof(char *);
*((char **)(mem_block[A_STRINGS].block+str_size)) = str;
/* Add the old prog_string_index[] */
mem_block[A_STRING_NEXT].current_size = next_size + sizeof(int);
*((int *)(mem_block[A_STRING_NEXT].block+next_size)) = i;
/* Store the string index as new prog_string_index[] */
*indexp = str_size / sizeof str;
last_string_is_new = MY_TRUE;
return *indexp;
} /* store_prog_string() */
/*-------------------------------------------------------------------------*/
static void
delete_prog_string (void)
/* Remove the program string last added with store_prog_string().
*/
{
char *str;
int size;
long hash;
char mask, *tagp;
int *indexp;
/* Remove the string from the A_STRINGS area and free it */
size = mem_block[A_STRINGS].current_size - sizeof(char *);
free_string(
str = *(char**)(mem_block[A_STRINGS].block+size)
);
mem_block[A_STRINGS].current_size = size;
/* Remove the string from the hash table */
size = (mem_block[A_STRING_NEXT].current_size -= sizeof(int));
/* TODO: Assumes 32-Bit pointers */
hash = (long)str ^ (long)str >> 16;
hash = (hash ^ hash >> 8);
mask = 1 << (hash & 7);
hash = hash & 0xff;
indexp = &prog_string_indizes[hash];
tagp = &prog_string_tags[hash >> 3];
if ( ( *indexp = *((int *)(mem_block[A_STRING_NEXT].block+size)) ) < 0)
/* Hash chain empty */
*tagp &= ~mask;
} /* delete_prog_string() */
/* ========================== INITIALIZATION ========================== */
%ifndef INITIALIZATION_BY___INIT
/*-------------------------------------------------------------------------*/
static INLINE fulltype_t
type_rtoc (svalue_t *svp)
/* Return the proper TYPE_ value for the type given by svalue <svp>.
*/
{
switch (svp->type)
{
case T_NUMBER: return !svp->u.number ? TYPE_ANY : TYPE_NUMBER;
case T_STRING: return TYPE_STRING;
case T_POINTER: return TYPE_MOD_POINTER | TYPE_ANY;
case T_FLOAT: return TYPE_FLOAT;
case T_CLOSURE: return TYPE_CLOSURE;
case T_SYMBOL: return TYPE_SYMBOL;
case T_QUOTED_ARRAY: return TYPE_QUOTED_ARRAY;
case T_MAPPING: return TYPE_MAPPING;
default:
fatal("Bad svalue type at compile time.\n");
}
/* NOTREACHED */
return TYPE_ANY;
} /* type_rtoc() */
/*-------------------------------------------------------------------------*/
static INLINE svalue_t *
copy_svalue (svalue_t *svp)
/* Create another reference to the value <svp> and return it.
* Of course this only works for numbers, floats and shareable svalues
* like shared strings or arrays.
* If the <svp> is not shareable, the function will return a reference
* to the svalue-0.
*
* The function is used to store svalues in the initializer table for
* a program.
*/
{
switch (svp->type)
{
case T_NUMBER:
case T_FLOAT:
break;
case T_STRING:
if (svp->x.string_type != STRING_SHARED)
return &const0;
/* FALLTHROUGH */
case T_SYMBOL:
ref_string(svp->u.string);
break;
case T_POINTER:
case T_QUOTED_ARRAY:
svp->u.vec->ref++;
break;
case T_MAPPING:
svp->u.map->ref++;
break;
case T_CLOSURE:
addref_closure(svp, "ass to var");
break;
default:
return &const0;
}
return svp;
} /* copy_svalue() */
/*-------------------------------------------------------------------------*/
static vector_t *
list_to_vector (size_t length, svalue_t *initialized)
/* <initialized>.u.lvalue points to a const_list of <length> elements: create
* a vector from this list, store it in <initialized> and also return it.
*/
{
const_list_t *list;
vector_t *vec;
svalue_t *svp;
void *block;
const_list_svalue_t *clsv;
%line
vec = allocate_array(length);
if (length)
{
/* Unravel and copy the constants from the list into the vector
*/
clsv = initialized->u.const_list;
list = &clsv->list;
block = clsv;
svp = vec->item;
do {
*svp++ = list->val;
list = list->next;
xfree(block);
} while ( NULL != (block = list) );
}
/* Return the array */
put_array(initialized, vec);
return vec;
} /* list_to_vector() */
/*-------------------------------------------------------------------------*/
static void
free_const_list_svalue (svalue_t *svp)
/* Function used as error-handler for const lists: <svp> is in fact
* a const_list_svalue_t* and this function deallocates all memory
* associated with the list.
*/
{
const_list_t *list;
void *block;
%line
list = &((const_list_svalue_t *)svp)->list;
block = svp;
do {
free_svalue(&list->val);
list = list->next;
xfree(block);
} while ( NULL != (block = list) );
} /* free_const_list_svalue() */
%endif /* !INITIALIZATION_BY___INIT */
#if defined(__MWERKS__) && !defined(WARN_ALL)
# pragma warn_possunwant off
# pragma warn_implicitconv off
#endif
%}
/*=========================================================================*/
/* P A R S E R */
/*-------------------------------------------------------------------------*/
%token L_ASSIGN
%token L_ARROW
%token L_BREAK
%token L_CASE
%token L_CATCH
%token L_CLOSURE
%token L_CLOSURE_DECL
%token L_COLON_COLON
%token L_CONTINUE
%token L_DEC
%token L_DEFAULT
%token L_DO
%token L_ELSE
%token L_EQ
%token L_FLOAT
%token L_FLOAT_DECL
%token L_FOR
%token L_FOREACH
%token L_GE
%token L_IDENTIFIER
%token L_IF
%token L_INC
%token L_INHERIT
%token L_INLINE_FUN
%token L_INT
%token L_LAND
%token L_LE
%token L_LOCAL
%token L_LOR
%token L_LSH
%token L_MAPPING
%token L_MIXED
%token L_NE
%token L_NO_MASK
%token L_NOSAVE
%token L_NOT
%token L_NUMBER
%token L_OBJECT
%ifdef SUPPLY_PARSE_COMMAND
%token L_PARSE_COMMAND
%endif
%token L_PRIVATE
%token L_PROTECTED
%token L_PUBLIC
%token L_QUOTED_AGGREGATE
%token L_RANGE
%token L_RETURN
%token L_RSH
%token L_RSHL
%token L_SSCANF
%token L_STATIC
%token L_STATUS
%token L_STRING
%token L_STRING_DECL
%token L_SWITCH
%token L_SYMBOL
%token L_SYMBOL_DECL
%token L_VARARGS
%token L_VIRTUAL
%token L_VOID
%token L_WHILE
/* Textbook solution to the 'dangling else' shift/reduce conflict.
*/
%nonassoc LOWER_THAN_ELSE
%nonassoc L_ELSE
/*-------------------------------------------------------------------------*/
/* The yacc stack type */
%union
{
%line
p_int number;
/* Literal numbers, or whereever a number is required.
*/
double float_number;
/* Literal floats */
struct {
p_int number;
} closure;
/* A closure (#'xxx). The .number determines the exact
* nature of the closure.
*/
struct {
char *name; /* The shared string with the name */
int quotes; /* Number of quotes */
} symbol;
/* A literal symbol.
*/
ident_t *ident;
/* L_IDENTIFIER, L_INLINE_FUN: The recognized identifier
*/
vartype_t type;
/* The datatype.
*/
fulltype_t fulltype;
/* The fulltype (datatype plus visibility) of entities.
*/
fulltype_t fulltypes[2];
/* Inheritance: [0]: code inheritance qualifiers
* [1]: variable inheritance qualifiers
*/
svalue_t *initialized;
/* Position where to store the variable initializer.
*/
p_int numbers[2];
/* Often used to save the current break/continue address.
*/
p_uint address;
/* Address of an instruction. */
struct {
bytecode_p p; /* The condition code */
unsigned short length; /* Length of the condition code */
unsigned short line; /* Last source line of the condition code */
} expression;
/* Expressions are used to save the code for a loop-condition
* while the body is compiled.
*/
struct s_lrvalue
{
vartype_t type; /* Type of the expression */
uint32 start; /* Startaddress of the instruction */
short code; /* Alternative instruction */
uint32 end; /* Endaddress+1 of the instruction */
}
lrvalue;
/* Used for expressions which may return a rvalue or lvalues.
* It is also used by the index range generation to move around
* the index expressions.
* Lvalue generation in places where either a r- or an lvalue
* is acceptible first generates the rvalue code, but stores
* the necessary information to patch the code to produce
* lvalues in this structure.
* For more information, see arrange_protected_lvalue().
*/
struct s_index
{
int inst; /* Type of the index */
uint32 start; /* Startaddress of the index */
uint32 end; /* Endaddress+1 of the index */
vartype_t type1; /* Type of index, resp. lower bound */
vartype_t type2; /* Type of other index, resp. upper bound */
}
index;
/* This is used to parse and return the indexing operation
* of an array or mapping.
* .inst gives the type of the operation:
* F_INDEX: [x]
* F_RINDEX: [<x]
* F_RANGE: [ x.. y]
* F_RN_RANGE: [<x.. y]
* F_NR_RANGE: [ x..<y]
* F_RR_RANGE: [<x..<y]
* F_NX_RANGE: [ x.. ]
* F_RX_RANGE: [<x.. ]
* .start and .end are the bytecode limits of the whole
* operation.
* .type1 and optionally .type2 are the types of the
* index values.
*/
struct lvalue_s {
union {
bytecode_p p;
bytecode_t simple[2];
} u;
unsigned short length;
vartype_t type;
} lvalue;
/* Used in assigns to communicate how an lvalue has to be accessed
* (by passing on the bytecode to create) and what type it is.
* .length = 0: u.simple contains the bytecode to create
* .length != 0: u.p points to the bytecode of .length bytes.
*/
struct {
p_int key; /* shared string ptr, or a number */
Bool numeric; /* TRUE: .key is a number */
} case_label;
/* Used to return the value of a 'case' label.
*/
char *string;
/* An allocated string */
char *sh_string;
/* A shared string */
struct {
char *super; /* NULL, or the allocated qualifier */
ident_t *real; /* The function identifier */
} function_name;
/* A qualified function name: "<super>::<func>" */
struct {
int simul_efun; /* -1, or index of the simul_efun */
p_int start; /* Address of the function call */
} function_call_head;
/* Used to save address and possible sefun-index over
* the argument parsing in a function call.
*/
%ifndef INITIALIZATION_BY___INIT
struct {
p_int length; /* Length of the list */
struct const_list_s * l; /* The list of constants */
} const_list;
/* Used to hold the constant elements of an array
* initializer.
*/
struct {
int function; /* efun index */
svalue_t *initialized; /* svalue to initialize */
} const_call_head;
/* Used to hold the information of a constant efun call
* over the parsing of the arguments.
*/
svalue_t svalue;
/* Used for constant float initializers: the float value */
%endif
} /* YYSTYPE */
/*-------------------------------------------------------------------------*/
%type <number> L_NUMBER constant
%type <float_number> L_FLOAT
%type <closure> L_CLOSURE
%type <symbol> L_SYMBOL
%type <number> L_QUOTED_AGGREGATE
%type <ident> L_IDENTIFIER L_INLINE_FUN
%type <fulltype> optional_star type type_modifier_list type_modifier
%type <fulltype> opt_basic_type basic_type
%type <fulltype> non_void_type opt_basic_non_void_type basic_non_void_type
%type <fulltypes> inheritance_qualifier inheritance_qualifiers
%type <fulltype> inheritance_modifier_list inheritance_modifier
%type <type> decl_cast cast
%type <lrvalue> note_start comma_expr expr0 expr4
%type <lrvalue> function_call inline_fun
%type <lrvalue> catch sscanf
%type <lrvalue> for_init_expr for_expr
%type <lrvalue> comma_expr_decl expr_decl
%ifdef SUPPLY_PARSE_COMMAND
%type <lrvalue> parse_command
%endif
%type <lvalue> lvalue name_lvalue local_name_lvalue foreach_var_lvalue
%type <lvalue> local_name_list new_local new_local_name
%type <index> index_range index_expr
%type <case_label> case_label
%type <address> optional_else
%type <string> anchestor
%type <sh_string> call_other_name
%type <function_name> function_name
%ifndef INITIALIZATION_BY___INIT
%type <svalue> float_constant
%type <const_list> const_expr_list const_expr_list2 const_expr_list3
%endif
/* Special uses of <number> */
%type <number> function_body
/* program address or -1 */
%type <number> argument argument_list lvalue_list
/* number of arguments */
%type <number> expr_list expr_list3 expr_list2
/* Number of expressions in an expression list */
%type <number> m_expr_values
/* Number of values for a mapping entry (ie the 'width') */
%type <number> L_ASSIGN
/* Instruction code of the assignment, e.g. F_ADD_EQ */
%type <number> L_LOCAL
/* Index number of the local variable */
%type <number> foreach_vars
/* Number of variables given to foreach
*/
%type <number> opt_catch_mods
/* Bitflags for catch() modes: 1: nolog
*/
/* Special uses of <numbers> */
%type <numbers> condStart
/* [0]: current_break_address
* [1]: address of the branch-offset of the if
*/
%type <numbers> m_expr_list m_expr_list2
/* [0]: number of entries in a mapping literal
* [1]: width of the mapping literal
*/
/* Special uses of <lrvalue> */
%type <lrvalue> pre_inc_dec
/* .code: The instruction F_PRE_INC or F_PRE_DEC.
* .start: The CURRENT_PROGRAM_SIZE where this inst was encountered.
*/
/*-------------------------------------------------------------------------*/
%right L_ASSIGN
%right '?'
%left L_LOR
%left L_LAND
%left '|'
%left '^'
%left '&'
%left L_EQ L_NE
%left '<' L_LE '>' L_GE
%left L_LSH L_RSH L_RSHL
%left '+' '-'
%left '*' '/' '%'
%right '~' L_NOT
%nonassoc L_INC L_DEC
%left L_ARROW '['
%%
/*-------------------------------------------------------------------------*/
all: program ;
program:
program def possible_semi_colon
| /* empty */ ;
possible_semi_colon:
/* empty */
| ';' { yywarn("Extra ';'. Ignored."); }
;
note_start: { $$.start = CURRENT_PROGRAM_SIZE; } ;
/*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/
/* Function prototypes
* Function definitions
* Variable definitions
* Inheritance
* Default visibility
*/
def: type optional_star L_IDENTIFIER /* Function definition or prototype */
{
use_local_scopes = pragma_use_local_scopes;
block_depth = 1;
init_scope(block_depth);
if (!($1 & (TYPE_MOD_PRIVATE | TYPE_MOD_PUBLIC
| TYPE_MOD_PROTECTED | TYPE_MOD_STATIC)))
{
$1 |= default_funmod;
}
$2 |= $1; /* $2 is now the complete type */
/* Require exact types? */
if ($1 & TYPE_MOD_MASK)
{
exact_types = $2;
}
else
{
if (pragma_strict_types != PRAGMA_WEAK_TYPES)
yyerror("\"#pragma strict_types\" requires type of function");
exact_types = 0;
}
if ($1 & TYPE_MOD_NOSAVE)
{
yyerror("can't declare a function as nosave");
$1 &= ~TYPE_MOD_NOSAVE;
}
if ($3->type == I_TYPE_UNKNOWN)
{
/* prevent freeing by exotic name clashes */
ident_t *p = $3;
p->type = I_TYPE_GLOBAL;
p->u.global.variable = I_GLOBAL_VARIABLE_OTHER;
p->u.global.efun = I_GLOBAL_EFUN_OTHER;
p->u.global.sim_efun = I_GLOBAL_SEFUN_OTHER;
p->u.global.function = I_GLOBAL_FUNCTION_VAR;
p->next_all = all_globals;
all_globals = p;
}
}
'(' argument ')'
{
/* We got the complete prototype: define it */
if ( current_number_of_locals
&& (full_type_of_locals[current_number_of_locals-1]
& TYPE_MOD_VARARGS)
)
{
%line
/* The last argument has to allow an array. */
vartype_t *t;
$2 |= TYPE_MOD_XVARARGS;
t = type_of_locals + (current_number_of_locals-1);
if (!(*t & TYPE_MOD_POINTER)
&& (*t & TYPE_MOD_RMASK) != TYPE_ANY
)
{
if ((*t & TYPE_MOD_RMASK) != TYPE_UNKNOWN)
yyerror(
"varargs parameter must be declared array or mixed");
/* Keep the visibility, but change the type to
* '&any'
*/
*t &= ~TYPE_MOD_RMASK;
*t |= TYPE_ANY;
}
}
/* Define a prototype. If it is a real function, then the
* prototype will be updated below.
*/
define_new_function(MY_FALSE, $3, $6, 0, 0,
NAME_UNDEFINED|NAME_PROTOTYPE, $2);
}
function_body
{
/* The function is complete */
p_int start;
bytecode_p p;
%line
if ( (start = $9) < 0)
{
/* function_body was a ';' -> prototype
* Just norm the visibility flags unless it is a prototype
* for an already inherited function.
*/
funflag_t *flagp;
flagp = (funflag_t *)(&FUNCTION($3->u.global.function)->flags);
if (!(*flagp & NAME_INHERITED))
{
*flagp |= $1 & (*flagp & TYPE_MOD_PUBLIC
? (TYPE_MOD_NO_MASK)
: (TYPE_MOD_NO_MASK|TYPE_MOD_PRIVATE
|TYPE_MOD_STATIC|TYPE_MOD_PROTECTED
|TYPE_MOD_PUBLIC)
);
}
}
else
{
/* function_body was a block: generate the
* function header and update the ident-table entry.
*/
p = &(PROGRAM_BLOCK[start]);
/* FUNCTION_NAME */
memcpy(p, &$3->name, sizeof $3->name);
p += sizeof $3->name;
/* FUNCTION_TYPE */
*p++ = $2;
/* FUNCTION_NUM_ARGS */
if ($2 & TYPE_MOD_XVARARGS)
*p++ = $6 | ~0x7f;
else
*p++ = $6;
/* FUNCTION_NUM_VARS */
*p = max_number_of_locals - $6+ max_break_stack_need;
define_new_function(MY_TRUE, $3, $6, max_number_of_locals - $6+
max_break_stack_need,
start + sizeof $3->name + 1, 0, $2);
ref_string($3->name);
ins_byte(F_RETURN0); /* catch a missing return */
}
/* Clean up */
free_all_local_names();
if (first_inline_fun)
insert_inline_fun_now = MY_TRUE;
block_depth = 0;
}
| type name_list ';' /* Variable definition */
{
if ($1 == 0)
yyerror("Missing type");
if (first_inline_fun)
insert_inline_fun_now = MY_TRUE;
}
| inheritance
| default_visibility
; /* def */
function_body:
/* A function with code: align the function and
* make space for the function header.
* Result is the address of the FUNCTION_NAME space.
*/
{
%line
#ifdef ALIGN_FUNCTIONS
CURRENT_PROGRAM_SIZE = align(CURRENT_PROGRAM_SIZE);
#endif
$<number>$ = CURRENT_PROGRAM_SIZE;
if (realloc_a_program(FUNCTION_HDR_SIZE))
{
CURRENT_PROGRAM_SIZE += FUNCTION_HDR_SIZE;
}
else
{
yyerrorf("Out of memory: program size %lu\n"
, mem_block[A_PROGRAM].current_size + FUNCTION_HDR_SIZE);
YYACCEPT;
}
}
block
%ifdef YACC_CANNOT_MIX_ANONYMOUS_WITH_DEFAULT
{ $$ = $<number>1; }
%endif
| ';' { $$ = -1; }
; /* function_body */
/*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/
/* Inheritance specification
*/
inheritance:
inheritance_qualifiers L_INHERIT string_constant ';'
{
%line
/* We got an inheritance: look up the name object and copy
* the functions and variables into this program.
*
* If the inherited object hasn't been loaded yet, store the
* name in inherit_file and abort the compile.
*
* copy_variables() might add extra inherits for virtual inheritance.
* For this reason, copy_functions() can't know the actual index
* of the new inherit, so it sets it to NEW_INHERITED_INDEX instead.
* This is changed later to the actual value by
* fix_function_inherit_indices() .
*/
object_t *ob;
inherit_t inherit;
%ifdef INITIALIZATION_BY___INIT
int initializer;
%endif /* INITIALIZATION_BY___INIT */
if (CURRENT_PROGRAM_SIZE
%ifdef INITIALIZATION_BY___INIT
&& !(((function_t *)(mem_block[A_FUNCTIONS].block+
mem_block[A_FUNCTIONS].current_size))[-1].flags &
NAME_INHERITED)
%endif /* INITIALIZATION_BY___INIT */
)
{
yyerror("illegal to inherit after defining functions");
}
/* Check the inheritance qualifiers.
* A variable 'nosave' inherit is internally stored as 'static',
* a functions 'nosave' inherit is not allowed.
*/
if ($1[1] & TYPE_MOD_NOSAVE)
{
$1[1] Showing the first 100 KB of 379.5 KB. Download the archive for the full file.