prolang.y
ldmud-3.4.1/src/prolang.y · 512.1 KB
From the archive ldmud-3.4.1.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 so that parsing rules can be
* activated/deactivated from config.h defines.
*---------------------------------------------------------------------------
* To compile a file, open the file to yield a filedescriptor 'fd', then call
*
* compile_file(fd, <filename>, <isMasterObj>);
*
* 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 that the compiler is not called
* recursively.
*
* 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.
*---------------------------------------------------------------------------
* 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...
*
#ifdef USE_NEW_INLINES
* Another challenge is the compilation of inline closures, as they
* are implemented as separate lfuns (with synthetic names), but encountered
* in the middle of a regular lfun or even another inline closure. The
* compiler therefore stores his state when it recognizes another
* inline closures, and then resets its state as if a normal lfun is
* compiled. When the inline closure is complete, its data is moved into
* a backup storage area, and the compiler restores its previous state.
#endif
*---------------------------------------------------------------------------
*/
#undef lint /* undef so that precompiled headers can be used */
#include "driver.h"
#include "typedefs.h"
#include "my-alloca.h"
#include <ctype.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 "mstrings.h"
#include "object.h"
#include "simulate.h"
#include "simul_efun.h"
#include "stdstrings.h"
#ifdef USE_STRUCTS
#include "structs.h"
#endif
#include "svalue.h"
#include "swap.h"
#include "switch.h"
#include "wiz_list.h"
#include "xalloc.h"
#include "../mudlib/sys/driver_hook.h"
#ifdef USE_NEW_INLINES
# undef DEBUG_INLINES
/* Define this to activate lots of debugging output during the compilation
* of inline closures.
*/
#endif /* USE_NEW_INLINES */
#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;
#ifdef USE_STRUCTS
typedef struct struct_init_s struct_init_t;
#endif /* USE_STRUCTS */
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.
*/
string_t *inherit_file;
/* Used as a flag: if it is set to a tabled 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.
*/
Bool variables_defined;
/* TRUE: Variable definitions have been encountered.
*/
/*-------------------------------------------------------------------------*/
/* 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), \
H_DEFAULT_METHOD: SH(T_CLOSURE) SH(T_STRING), \
H_DEFAULT_PROMPT: SH(T_CLOSURE) SH(T_STRING), \
H_PRINT_PROMPT: SH(T_CLOSURE) SH(T_STRING), \
H_REGEXP_PACKAGE: SH(T_NUMBER), \
#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;
#ifdef USE_STRUCTS
string_t * member; /* NULL, or the member name to initialize */
#endif
};
/* --- 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 */
#ifdef USE_STRUCTS
const_list_t *last_member; /* For nested struct initialisations */
#endif /* USE_STRUCTS */
};
#ifdef USE_STRUCTS
/* --- struct struct_init_s: Descriptor for one struct literal member
*
* When createing struct literals at runtime, a list of these structures
* keeps the information about the order and type of members encountered.
*/
struct struct_init_s
{
struct_init_t * next; /* Next member entry */
vartype_t type; /* Type of expression */
string_t * name; /* Member name, or NULL if unnamed */
};
#endif /* USE_STRUCTS */
/* --- 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.
*/
#ifdef USE_STRUCTS
#define set_vartype(t, id, ptr) \
( t.type = (id), t.t_struct = (ptr) )
#define set_fulltype(t, id, ptr) \
( t.typeflags = (id), t.t_struct = (ptr) )
#else
#define set_vartype(t, id, ptr) \
( t.type = (id) )
#define set_fulltype(t, id, ptr) \
( t.typeflags = (id) )
#endif
/* Set the full/vartype <t> to type(flags) <id> and the struct
* typeobject pointer to <ptr>.
*/
#define NEW_INHERITED_INDEX (0xfffff)
/* While inserting a new inherit, this marks the newly inherited
* things.
*/
/* Values for %type <number> foreach_expr
*/
#define FOREACH_LOOP 0 /* Normal foreach loop value */
#define FOREACH_REF 1 /* Referenced foreach loop value */
#define FOREACH_RANGE 2 /* Integer range as loop value */
/*-------------------------------------------------------------------------*/
/* 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.
*/
enum e_saved_areas {
A_PROGRAM = 0
/* (bytecode_t): Program code.
*/
, A_STRINGS
/* (string_t*) Strings used by the program, all tabled.
*/
, A_VARIABLES
/* (variable_t) The information for all non-virtual variables.
*/
, A_VIRTUAL_VAR
/* (variable_t) The information for all virtual variables.
*/
, A_LINENUMBERS
/* (char) The linenumber information.
*/
, A_INHERITS
/* (inherit_t) The information for the inherited programs.
*/
, A_ARGUMENT_TYPES
/* (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
*/
, A_ARGUMENT_INDEX
/* (unsigned short) Index of the first argument type of function <n>.
* INDEX_START_NONE is used for functions with no type information.
*/
, A_INCLUDES
/* (include_t) Tabled descriptors of all included files, in the order
* of appearance.
*/
#ifdef USE_STRUCTS
, A_STRUCT_DEFS
/* (struct_def_t) Tabled descriptors of all struct definitions.
*/
#endif /* USE_STRUCTS */
, NUMPAREAS /* Number of saved areas */
};
enum e_internal_areas {
A_FUNCTIONS = NUMPAREAS
/* (function_t): Function definitions
*/
, A_STRING_NEXT
/* (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.
*/
, A_LOCAL_TYPES
/* (fulltype_t) The full types of local and context variables.
#ifdef USE_NEW_INLINES
* For normal functions, only the beginning of the area is used.
* The rest is used stack-wise for nested inline closures.
#endif
*/
%ifdef USE_NEW_INLINES
, A_INLINE_PROGRAM
/* (bytecode_t, char): Program and linenumbers saved from the compiled
* but not yet inserted inline closures.
*/
, A_INLINE_CLOSURE
/* (inline_closure_t): The currently pending inline closures. The lexical
* nesting is achieved with the .prev/.next pointers in the
* inline_closure_t structures.
*/
%endif /* USE_NEW_INLINES */
#ifdef USE_STRUCTS
, A_STRUCT_MEMBERS
/* (struct_member_t) While a struct definition is parsed, the member
* descriptors are collected here.
*/
#endif /* USE_STRUCTS */
, NUMAREAS /* 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 LINENUMBER_BLOCK ((char *)(mem_block[A_LINENUMBERS].block))
/* The current linenumber block, properly typed.
*/
#define LINENUMBER_SIZE (mem_block[A_LINENUMBERS].current_size)
/* The current linenumber data 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 ARGUMENT_TYPE(n) ((vartype_t *)mem_block[A_ARGUMENT_TYPES].block)[n]
/* Index the vartype_t <n>.
*/
#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.
*/
#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.
*/
#ifdef USE_STRUCTS
#define STRUCT_DEF(n) ((struct_def_t *)mem_block[A_STRUCT_DEFS].block)[n]
/* Index the struct_def_t <n>.
*/
#define STRUCT_COUNT (mem_block[A_STRUCT_DEFS].current_size / sizeof(struct_def_t))
/* Return the number of structs encountered so far.
*/
#define STRUCT_MEMBER(n) ((struct_member_t *)mem_block[A_STRUCT_MEMBERS].block)[n]
/* Index the struct_member_t <n>.
*/
#define STRUCT_MEMBER_COUNT (mem_block[A_STRUCT_MEMBERS].current_size / sizeof(struct_member_t))
/* Return the number of struct members stored.
*/
#endif /* USE_STRUCTS */
#define PROG_STRING(n) ((string_t **)mem_block[A_STRINGS].block)[n]
/* Index the pointer for program string <n>.
*/
#define STRING_COUNT (mem_block[A_STRINGS].current_size / sizeof(string_t *))
/* 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.
*/
#define LOCAL_TYPE_COUNT (mem_block[A_LOCAL_TYPES].current_size / sizeof(fulltype_t))
/* Return the total number of types.
*/
#define LOCAL_TYPE(n) ((fulltype_t *)mem_block[A_LOCAL_TYPES].block)[n]
/* Return the local/context var type at index <n>.
*/
%ifdef USE_NEW_INLINES
#define INLINE_PROGRAM_BLOCK(n) ((bytecode_p)(mem_block[A_INLINE_PROGRAM].block + (n)))
/* Return the inline-closure program block at address <n>, properly typed.
*/
#define INLINE_PROGRAM_SIZE (mem_block[A_INLINE_PROGRAM].current_size)
/* The current program size.
*/
#define INLINE_CLOSURE(n) ((inline_closure_t *)mem_block[A_INLINE_CLOSURE].block)[n]
/* Return the inline-closure program block at address <n>, properly typed.
*/
#define INLINE_CLOSURE_COUNT (mem_block[A_INLINE_CLOSURE].current_size/sizeof(inline_closure_t))
/* Return the number of saved inline-closures.
*/
%endif /* USE_NEW_INLINES */
/*-------------------------------------------------------------------------*/
/* 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.
*/
/*-------------------------------------------------------------------------*/
#ifdef USE_NEW_INLINES
/* Information describing inline closures.
*/
typedef struct inline_closure_s inline_closure_t;
struct inline_closure_s
{
mp_int prev;
/* Index of the enclosing inline closure, or -1 if none.
*/
/* --- Compilation information --- */
mp_uint end;
/* While compiling the closure: end of the program code before
* the closure. It is not identical to .start because of alignment.
*/
mp_uint start;
/* While compiling the closure: start address of the code in A_PROGRAM.
* For pending closures: start address of the code in A_INLINE_PROGRAM.
*/
mp_uint length;
/* Length of the compiled code.
*/
mp_uint li_start;
/* While compiling the closure: start address of the data in
* A_LINENUMBERS.
* For pending closures: start address of the data in A_INLINE_PROGRAM.
*/
mp_uint li_length;
/* Length of the linenumber data.
*/
int function;
/* Function index
*/
fulltype_t returntype;
/* The return type (uncounted reference).
*/
ident_t * ident;
/* The ident entry with the function name.
*/
int num_args;
/* Number of arguments.
*/
Bool parse_context;
/* TRUE if the context variable definitions are parsed.
*/
int current_line;
/* Current line number, used to adjust the generated linenumbers.
*/
/* --- Saved Globals --- */
void * include_handle;
/* Current include state.
*/
fulltype_t exact_types;
/* The enclosing return type setting (reference not counted).
*/
int block_depth;
/* Block depth at definition point.
* +1: Context depth
* +2: Argument depth
*/
int num_locals;
int max_num_locals;
/* Current and max number of locals at definition point.
*/
int break_stack_size;
int max_break_stack_size;
/* Current and max break stack size at definition point.
*/
mp_uint full_local_type_start;
mp_uint full_context_type_start;
/* Start indices of the local/context variable type information
* in A_LOCAL_TYPES.
*/
mp_uint full_local_type_size;
/* Current size of the A_LOCAL_TYPES memblocks.
*/
};
static inline_closure_t * current_inline;
/* NULL, or pointer to the current inline_closure_t structure while
* compiling an inline closure.
* This variable is also used as flag that we're currently compiling
* an inline_closure.
*/
static unsigned int inline_closure_id;
/* ID Number for the inline closure name.
*/
#endif /* USE_NEW_INLINES */
/*-------------------------------------------------------------------------*/
/* Other Variables */
static Bool disable_sefuns;
/* TRUE: Sefuns will be ignored.
*/
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>.
*/
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.
*/
static fulltype_t def_function_returntype;
static ident_t * def_function_ident;
static int def_function_num_args;
/* Globals to keep the state while a function is parsed:
* _returntype: the returntype (uncounted reference)
* _ident: the function's identifier.
* _num_args: number of formal arguments.
*/
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 fulltype_t * type_of_locals = NULL;
/* The full types of the local variables.
* Points to a location in mem_block A_LOCAL_TYPES, it is NULL between
* compilations.
*/
#ifdef USE_NEW_INLINES
static fulltype_t * type_of_context = NULL;
/* The full types of the context variables.
* Points to a location in mem_block A_LOCAL_TYPES, it is NULL between
* compilations.
*/
#endif /* USE_NEW_INLINES */
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.
*/
static fulltype_t exact_types;
/* If .typeflags is 0, don't check nor require argument and function types.
* Otherwise it's the full return type of the function, including
* visibility (reference not counted).
*/
static funflag_t default_varmod;
static funflag_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 FBRANCH is marked by having a negative offset value.
*
* There are a few special values/flags for this variable:
*/
#define BREAK_ADDRESS_MASK 0x0003ffff
/* Mask for the offset-address part of the 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 FBRANCHes
* which implement the continue statement. Stored in every offset-part
* is the address of the offset of the next FBRANCH in the series. The
* last FBRANCH 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).
*/
#ifdef USE_STRUCTS
static int current_struct;
/* Index of the current structure to be defined.
*/
#endif /* USE_STRUCTS */
static fulltype_t current_type;
/* The current basic type (reference not counted).
*/
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 (unsigned)-1.
*/
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 string_t *last_string_constant = NULL;
/* The current (last) string constant, a tabled 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').
*/
static int argument_level;
/* Nesting level of function call arguments.
* Used to detect nested function calls, like foo( bar () ).
*/
static Bool got_ellipsis[COMPILER_STACK_SIZE];
/* Flags indexed by <argument_level>, telling if the current function
* arguments used the L_ELLIPSIS operator.
* TODO: This should be dynamic.
*/
#ifdef USE_STRUCTS
static const char * compiled_file;
/* The name of the program to be compiled. While current_loc.file reflects
* the name of the source file currently being read, this name is always
* the program's name. Set by prolog().
*/
static const fulltype_t Type_Any = { TYPE_ANY, NULL };
static const fulltype_t Type_Unknown = { TYPE_UNKNOWN, NULL };
static const vartype_t VType_Unknown = { TYPE_UNKNOWN, NULL };
static const fulltype_t Type_Number = { TYPE_NUMBER, NULL };
static const fulltype_t Type_Float = { TYPE_FLOAT, NULL };
static const fulltype_t Type_String = { TYPE_STRING, NULL };
static const fulltype_t Type_Object = { TYPE_OBJECT, NULL };
static const fulltype_t Type_Closure = { TYPE_CLOSURE, NULL };
static const fulltype_t Type_Mapping = { TYPE_MAPPING, NULL };
static const fulltype_t Type_Symbol = { TYPE_SYMBOL, NULL };
static const fulltype_t Type_Void = { TYPE_VOID, NULL };
static const fulltype_t Type_Quoted_Array = { TYPE_QUOTED_ARRAY, NULL };
static const fulltype_t Type_Ptr_Any = { TYPE_ANY|TYPE_MOD_POINTER, NULL };
static const fulltype_t Type_Ref_Any = { TYPE_ANY|TYPE_MOD_REFERENCE, NULL };
static const fulltype_t Type_Ref_Number = { TYPE_NUMBER|TYPE_MOD_REFERENCE, NULL };
#else
static const fulltype_t Type_Any = { TYPE_ANY };
static const fulltype_t Type_Unknown = { TYPE_UNKNOWN };
static const vartype_t VType_Unknown = { TYPE_UNKNOWN };
static const fulltype_t Type_Number = { TYPE_NUMBER };
static const fulltype_t Type_Float = { TYPE_FLOAT };
static const fulltype_t Type_String = { TYPE_STRING };
static const fulltype_t Type_Object = { TYPE_OBJECT };
static const fulltype_t Type_Closure = { TYPE_CLOSURE };
static const fulltype_t Type_Mapping = { TYPE_MAPPING };
static const fulltype_t Type_Symbol = { TYPE_SYMBOL };
static const fulltype_t Type_Void = { TYPE_VOID };
static const fulltype_t Type_Quoted_Array = { TYPE_QUOTED_ARRAY };
static const fulltype_t Type_Ptr_Any = { TYPE_ANY|TYPE_MOD_POINTER };
static const fulltype_t Type_Ref_Any = { TYPE_ANY|TYPE_MOD_REFERENCE };
static const fulltype_t Type_Ref_Number = { TYPE_NUMBER|TYPE_MOD_REFERENCE };
#endif /* USE_STRUCTS */
/* Constants for the known simple types.
*/
/*-------------------------------------------------------------------------*/
/* 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 *, string_t *, 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);
static void add_new_init_jump(void);
static void transfer_init_control(void);
static void copy_variables(program_t *, funflag_t);
static int copy_functions(program_t *, funflag_t type);
#ifdef USE_STRUCTS
static void copy_structs(program_t *, funflag_t);
#endif /* USE_STRUCTS */
#ifdef USE_NEW_INLINES
static void new_inline_closure (void);
#endif /* USE_NEW_INLINES */
static void fix_function_inherit_indices(program_t *);
static void fix_variable_index_offsets(program_t *);
static short store_prog_string (string_t *str);
/*-------------------------------------------------------------------------*/
void
yyerror (const 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_loc.file->name, current_loc.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_loc.file->name, current_loc.line
, str, context);
if (num_parse_error == 0)
save_error(str, current_loc.file->name, current_loc.line);
num_parse_error++;
} /* yyerror() */
/*-------------------------------------------------------------------------*/
void
yyerrorf (const 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 (const 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_loc.file->name, current_loc.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_loc.file->name, current_loc.line
, str, context);
if (master_ob && num_parse_error == 0)
save_error(str, current_loc.file->name, current_loc.line);
/* TODO: Introduce a 'master_is_loading' flag to prevent this call while
* TODO:: the master is inactive.
*/
} /* yywarn() */
/*-------------------------------------------------------------------------*/
void
yywarnf (const 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.
*/
{
string_t *tmp;
tmp = mstr_add(last_string_constant, last_lex_string);
if (!tmp)
{
yyerrorf("Out of memory for string literal (%ld bytes)"
, (long)(mstrsize(last_string_constant)
+mstrsize(last_lex_string))
);
return;
}
free_mstring(last_string_constant);
free_mstring(last_lex_string); last_lex_string = NULL;
last_string_constant = make_tabled(tmp);
if (!last_string_constant)
{
yyerror("Out of memory for string literal (%ld bytes)");
}
} /* 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 ((mp_uint)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
extend_mem_block (int n, size_t size)
/* Reserve <size> bytes at the current position in memory area <n>.
* This does increase the .current_size .
*/
{
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;
}
mbp->current_size += size;
}
} /* extend_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 ============================== */
/*-------------------------------------------------------------------------*/
static INLINE void
assign_full_to_vartype(vartype_t * dest, fulltype_t src)
/* Assign a fulltype_t variable to a vartype_t variable.
*/
{
dest->type = src.typeflags;
#ifdef USE_STRUCTS
dest->t_struct = src.t_struct;
#endif
} /* assign_full_to_vartype() */
/*-------------------------------------------------------------------------*/
static INLINE void
assign_var_to_fulltype(fulltype_t * dest, vartype_t src)
/* Assign a vartype_t variable to a fulltype_t variable.
*/
{
dest->typeflags = src.type;
#ifdef USE_STRUCTS
dest->t_struct = src.t_struct;
#endif
} /* assign_var_to_fulltype() */
/*-------------------------------------------------------------------------*/
static INLINE Bool
equal_types (fulltype_t e, fulltype_t t)
/* Return TRUE if <e> and <t> are compatible basic types.
*/
{
return (e.typeflags & TYPEID_MASK) == (t.typeflags & TYPEID_MASK)
#ifdef USE_STRUCTS
&& e.t_struct == t.t_struct
#endif
;
} /* equal_types() */
static INLINE Bool
basic_type (typeflags_t e, typeflags_t t)
/* Return TRUE if <e> and <t> are compatible basic types.
*/
{
e &= TYPEID_MASK;
t &= TYPEID_MASK;
return e == TYPE_ANY
|| e == t
|| t == TYPE_ANY
;
} /* basic_type() */
static INLINE Bool
BASIC_TYPE (fulltype_t e, fulltype_t t)
/* Return TRUE if <e> and <t> are compatible basic types.
*/
{
return basic_type(e.typeflags, t.typeflags);
} /* BASIC_TYPE() */
static INLINE Bool
TYPE (fulltype_t e, fulltype_t t)
/* Return TRUE if <e> and <t> are compatible basic xor pointer types.
*/
{
typeflags_t ef = e.typeflags & TYPEID_MASK;
typeflags_t tf = t.typeflags & TYPEID_MASK;
return basic_type(ef & TYPE_MOD_MASK, tf & TYPE_MOD_MASK)
|| ( (ef & TYPE_MOD_POINTER) && (tf & TYPE_MOD_POINTER)
&& basic_type( ef & (TYPE_MOD_MASK & ~TYPE_MOD_POINTER)
, tf & (TYPE_MOD_MASK & ~TYPE_MOD_POINTER))
)
;
} /* TYPE() */
static INLINE Bool
vtype (vartype_t e, vartype_t t)
/* Return TRUE if <e> and <t> are compatible basic xor pointer types.
*/
{
fulltype_t et, tt;
assign_var_to_fulltype(&et, e);
assign_var_to_fulltype(&tt, t);
return TYPE(et, tt);
} /* vtype() */
static INLINE Bool
MASKED_TYPE (fulltype_t e, fulltype_t t)
/* Return TRUE if <e> and <t> are compatible basic types, or if both
* are pointer types and one of them is a *ANY.
*/
{
typeflags_t ef = e.typeflags & TYPEID_MASK;
typeflags_t tf = t.typeflags & TYPEID_MASK;
return basic_type(ef, tf)
|| ( ef == (TYPE_MOD_POINTER|TYPE_ANY) && ef & TYPE_MOD_POINTER )
|| ( tf == (TYPE_MOD_POINTER|TYPE_ANY) && ef & TYPE_MOD_POINTER )
;
} /* MASKED_TYPE() */
static INLINE Bool
REDEFINED_TYPE (fulltype_t e, fulltype_t t)
/* 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.
*/
{
typeflags_t ef = e.typeflags & TYPEID_MASK;
typeflags_t tf = t.typeflags & TYPEID_MASK;
return basic_type(ef, tf )
|| (tf == (TYPE_MOD_POINTER|TYPE_ANY) )
|| (ef == (TYPE_MOD_POINTER|TYPE_ANY) )
;
} /* REDEFINED_TYPE() */
/*-------------------------------------------------------------------------*/
static char *
get_f_visibility (funflag_t flags)
/* Return (in a static buffer) a textual representation of the visibility
* flags in <flags>.
*/
{
static char buff[100];
size_t len;
buff[0] = '\0';
if (flags & TYPE_MOD_STATIC)
strcat(buff, "static ");
if (flags & TYPE_MOD_NO_MASK)
strcat(buff, "nomask ");
if (flags & TYPE_MOD_PRIVATE)
strcat(buff, "private ");
if (flags & TYPE_MOD_PROTECTED)
strcat(buff, "protected ");
if (flags & TYPE_MOD_PUBLIC)
strcat(buff, "public ");
if (flags & TYPE_MOD_VARARGS)
strcat(buff, "varargs ");
len = strlen(buff);
if (len)
buff[len-1] = '\0';
return buff;
} /* get_f_visibility() */
/*-------------------------------------------------------------------------*/
static char *
get_visibility (fulltype_t type)
/* Return (in a static buffer) a textual representation of the visibility
* portion of <type>.
*/
{
return get_f_visibility(type.typeflags);
} /* 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", "struct" };
Bool pointer = MY_FALSE, reference = MY_FALSE;
buff[0] = '\0';
if (type.typeflags & TYPE_MOD_STATIC)
strcat(buff, "static ");
if (type.typeflags & TYPE_MOD_NO_MASK)
strcat(buff, "nomask ");
if (type.typeflags & TYPE_MOD_PRIVATE)
strcat(buff, "private ");
if (type.typeflags & TYPE_MOD_PROTECTED)
strcat(buff, "protected ");
if (type.typeflags & TYPE_MOD_PUBLIC)
strcat(buff, "public ");
if (type.typeflags & TYPE_MOD_VARARGS)
strcat(buff, "varargs ");
type.typeflags &= TYPE_MOD_MASK;
if (type.typeflags & TYPE_MOD_POINTER)
{
pointer = MY_TRUE;
type.typeflags &= ~TYPE_MOD_POINTER;
}
if (type.typeflags & TYPE_MOD_REFERENCE)
{
reference = MY_TRUE;
type.typeflags &= ~TYPE_MOD_REFERENCE;
}
if (type.typeflags >= sizeof type_name / sizeof type_name[0])
fatal("Bad type %ld: %s line %d\n"
, (long)type.typeflags, current_loc.file->name, current_loc.line);
strcat(buff, type_name[type.typeflags]);
#ifdef USE_STRUCTS
if (type.typeflags == TYPE_STRUCT)
{
strcat(buff, " ");
if (type.t_struct)
{
char buff2[100];
strcat(buff, get_txt(type.t_struct->name));
sprintf(buff2, " %p", type.t_struct);
strcat(buff, buff2);
}
}
#endif /* USE_STRUCTS */
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() */
#ifdef USE_STRUCTS
/*-------------------------------------------------------------------------*/
static char *
get_two_vtypes (vartype_t type1, vartype_t type2)
/* Return (in a static buffer) the text "(<type1> vs. <type2>)".
*/
{
fulltype_t ftype1, ftype2;
assign_var_to_fulltype(&ftype1, type1);
assign_var_to_fulltype(&ftype2, type2);
return get_two_types(ftype1, ftype2);
} /* get_two_vtypes() */
#endif /* USE_STRUCTS */
/*-------------------------------------------------------------------------*/
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 void
efun_argument_error(int arg, int instr
, fulltype_t * expected, fulltype_t got
)
{
char msg[1024];
msg[0] = '\0';
for (; expected->typeflags; expected++)
{
if (msg[0] != '\0')
strcat(msg, "/");
strcat(msg, get_type_name(*expected));
}
yyerrorf("Bad arg %d type to %s(): got %s, expected %s"
, arg, instrs[instr].name, get_type_name(got), msg);
} /* efun_argument_error() */
/*-------------------------------------------------------------------------*/
static Bool
compatible_types (fulltype_t t1, fulltype_t t2, Bool is_assign)
/* 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 <is_assign> is true, it is assumed that <t2> will be assigned
* to a var of <t1>, and the following rules have to match as well:
* - a struct <t1> is compatible to a derived struct <t2>.
* - if <t1> is a struct, <t2> must be a struct or TYPE_ANY.
*/
{
t1.typeflags &= TYPEID_MASK;
t2.typeflags &= TYPEID_MASK;
if (t1.typeflags == TYPE_UNKNOWN || t2.typeflags == TYPE_UNKNOWN)
return MY_FALSE;
if (t1.typeflags == TYPE_ANY || t2.typeflags == TYPE_ANY)
return MY_TRUE;
#ifdef USE_STRUCTS
if (is_assign
&& (t1.typeflags & PRIMARY_TYPE_MASK) == T_STRUCT
&& (t2.typeflags & PRIMARY_TYPE_MASK) == T_STRUCT
)
{
struct_type_t * id1, * id2;
/* Check if t1 is a base-struct of t2 */
id1 = t1.t_struct;
id2 = t2.t_struct;
while (id2 != NULL && id1 != id2)
{
id2 = id2->base;
}
/* If the base structs match, just pretend that t2 is the
* same struct as t1. This will make the following tests
* work as normal.
*/
if (id2 != NULL)
t2.t_struct = id1;
}
#endif
if (t1.typeflags == t2.typeflags)
{
#ifdef USE_STRUCTS
if (t1.t_struct == t2.t_struct)
return MY_TRUE;
#else
return MY_TRUE;
#endif
}
if ((t1.typeflags & TYPE_MOD_POINTER) && (t2.typeflags & TYPE_MOD_POINTER))
{
if ((t1.typeflags & TYPE_MOD_MASK) == (TYPE_ANY|TYPE_MOD_POINTER)
|| (t2.typeflags & TYPE_MOD_MASK) == (TYPE_ANY|TYPE_MOD_POINTER))
return MY_TRUE;
}
#ifdef USE_STRUCTS
if (is_assign && (t1.typeflags & PRIMARY_TYPE_MASK) == T_STRUCT)
{
/* Check if t2 is a struct. If it is, the above
* check already made sure that the type matches.
*/
if ((t2.typeflags & PRIMARY_TYPE_MASK) != T_STRUCT)
return MY_FALSE;
}
#endif
return MY_FALSE;
} /* compatible_types() */
/*-------------------------------------------------------------------------*/
static INLINE void
i_add_arg_type (fulltype_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);
}
assign_full_to_vartype((vartype_t*)(mbp->block + mbp->current_size), type);
mbp->current_size += sizeof(vartype_t);
} /* i_add_arg_type() */
#define add_arg_type(t) i_add_arg_type(t)
/*-------------------------------------------------------------------------*/
static INLINE void
pop_arg_stack (int n)
/* Pop (remove) the last <n> types from the argument stack.
*/
{
vartype_t * vp;
vp = (vartype_t*)(type_of_arguments.block + type_of_arguments.current_size);
while (n > 0)
{
type_of_arguments.current_size -= sizeof (vartype_t);
n--;
vp--;
}
} /* 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;
typeid_t 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->type;
argp++;
}
if (!(~mask & 0xffff))
yyerror("Can't trace reference assignments.");
} /* check_aggregate_types() */
/*-------------------------------------------------------------------------*/
static INLINE void
warn_function_shadow ( const string_t *pubProg, string_t * pubFun
, const string_t *privProg, string_t * privFun
)
/* Issue a warning that the public function <pubProg>::<pubFun>() shadows the
* private function <privProg>::<privFun>().
* Both <pubProg> and <privProg> can be NULL.
* If the function is __INIT(), no warning is printed.
*/
{
string_t *pubCProg = NULL;
string_t *privCProg = NULL;
if (mstreq(pubFun, STR_VARINIT)
&& mstreq(privFun, STR_VARINIT))
return;
if (pubProg != NULL) pubCProg = cvt_progname(pubProg);
if (privProg != NULL) privCProg = cvt_progname(privProg);
if (pubCProg != NULL)
{
if (privCProg != NULL)
yywarnf("public %s::%s() shadows private %s::%s()"
, get_txt(pubCProg), get_txt(pubFun)
, get_txt(privCProg), get_txt(privFun)
);
else
yywarnf("public %s::%s() shadows private %s()"
, get_txt(pubCProg), get_txt(pubFun)
, get_txt(privFun)
);
}
else if (privCProg != NULL)
yywarnf("public %s() shadows private %s::%s()"
, get_txt(pubFun)
, get_txt(privCProg), get_txt(privFun)
);
else
yywarnf("public %s() shadows private %s()"
, get_txt(pubFun)
, get_txt(privFun)
);
if (pubCProg != NULL) free_mstring(pubCProg);
if (privCProg != NULL) free_mstring(privCProg);
} /* warn_function_shadow() */
/* ============================= 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 (instrs[b].prefix)
ins_byte(instrs[b].prefix);
ins_byte(instrs[b].opcode);
} /* ins_f_code() */
/*-------------------------------------------------------------------------*/
static void
ins_short (long l)
/* Add the 2-byte number <l> to the A_PROGRAM area in a fixed byteorder.
*/
{
short s = (short)l;
if (l > (long)USHRT_MAX || l < SHRT_MIN)
yyerrorf("Compiler error: too large number %lx passed to ins_short()"
, l);
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, s);
}
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, long l)
/* Store the 2-byte number <l> at <offset> in the A_PROGRAM are in
* a fixed byteorder.
*/
{
char *dest;
short s = (short)l;
if (l > (long)USHRT_MAX || l < SHRT_MIN)
yyerrorf("Compiler error: too large number %ld passed to upd_short()"
, l);
dest = mem_block[A_PROGRAM].block + offset;
PUT_SHORT(dest, s);
} /* 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() */
/*-------------------------------------------------------------------------*/
static void
upd_jump_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;
PUT_3BYTE(dest, l);
} /* upd_jump_offset() */
/*-------------------------------------------------------------------------*/
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() */
/*-------------------------------------------------------------------------*/
static void
upd_long (mp_uint offset, long l)
/* Store the 4-byte number <l> at <offset> in the A_PROGRAM are in
* a fixed byteorder.
*/
{
char *dest;
dest = mem_block[A_PROGRAM].block + offset;
PUT_LONG(dest, l);
} /* upd_long() */
/*-------------------------------------------------------------------------*/
static long
read_long (mp_uint offset)
/* Return the 4-byte number stored at <offset> in the A_PROGRAM area.
*/
{
long l;
char *dest;
dest = mem_block[A_PROGRAM].block + offset;
GET_LONG(l, dest);
return l;
} /* read_long() */
/*-------------------------------------------------------------------------*/
static void
ins_number (long num)
/* Insert code to push number <num> onto the stack.
* The function tries to find the shortest sequence to do so.
*/
{
if (num == 0)
ins_f_code(F_CONST0);
else if (num == 1)
{
ins_f_code(F_CONST1);
}
else if (num == -1)
ins_f_code(F_NCONST1);
else if (num >= 0 && num <= 0x0FF)
{
ins_f_code(F_CLIT);
ins_byte((num & 0xFF));
}
else if (num < 0 && num >= -0x0FF)
{
ins_f_code(F_NCLIT);
ins_byte(((-num) & 0xFF));
}
else
{
ins_f_code(F_NUMBER);
ins_long(num);
}
} /* ins_number() */
/*-------------------------------------------------------------------------*/
/* 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_f_code(i): to add instruction <i> to the program
* add_byte(b): to add byte <b> to the program
* add_short(s): to add short <s> to the program
*
* Except for add_f_code(), none of the macros adapts CURRENT_PROGRAM_SIZE,
* and add_f_code() increments the _SIZE only for the prefix byte if any.
*/
#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))
#define add_f_code(i) \
do{ if (instrs[i].prefix) { \
add_byte(instrs[i].prefix); \
CURRENT_PROGRAM_SIZE++; \
}\
add_byte(instrs[i].opcode); \
}while(0)
/*-------------------------------------------------------------------------*/
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 & BREAK_ADDRESS_MASK
; (j = read_long(i)) > loc; )
{
upd_long(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_long(i)) > loc; )
{
upd_long(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)
yyerrorf("Compiler limit: Too much code to branch over: %ld bytes"
, offset);
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_long(i)) > switch_pc; )
{
upd_long(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 (const char *s1, const 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)
yyerrorf("Compiler limit: Too much code to skip for ||/&&:"
" %ld bytes" , offset);
p[0] = F_POP_VALUE;
}
else
{
mem_block[A_PROGRAM].block[address] = offset;
}
} /* update_lop_branch() */
/*-------------------------------------------------------------------------*/
static void
shuffle_code (p_uint start1, p_uint start2, p_uint end)
/* Reverse the order of the program blocks [start1..start2[ and [start2..end[
*/
{
p_uint len1 = start2 - start1;
p_uint len2 = end - start2;
bytecode_p pStart1 = PROGRAM_BLOCK + start1;
bytecode_p pStart2 = PROGRAM_BLOCK + start2;
bytecode_p * pTmp;
if (!len1 || !len2)
return;
pTmp = xalloc(len1);
if (!pTmp)
{
yyerror("(shuffle_code) Out of memory");
return;
}
memmove(pTmp, pStart1, len1);
memmove(pStart1, pStart2, len2);
memmove(pStart1+len2, pTmp, len1);
xfree(pTmp);
} /* shuffle_code() */
/* ======================== 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);
}
while (current_number_of_locals > 0 && type_of_locals)
{
current_number_of_locals--;
free_fulltype_data(&type_of_locals[current_number_of_locals]);
}
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_fulltype_data(&type_of_locals[current_number_of_locals]);
}
} /* free_local_names() */
/*-------------------------------------------------------------------------*/
static ident_t *
add_local_name (ident_t *ident, fulltype_t type, int depth
#ifndef USE_NEW_INLINES
, Bool may_shadow
#endif /* USE_NEW_INLINES */
)
/* Declare a new local variable <ident> with the type <type> on
* the scope depth <depth>. The references of <type> are NOT adopted.
#ifndef USE_NEW_INLINES
* If <may_shadow> is TRUE, the declaration is
* allowed to shadow a previous one without generating a warning (this is
* used to declare inline functions on the fly).
#endif
* Return the (adjusted) ident for the new variable.
*/
{
if ((type.typeflags & PRIMARY_TYPE_MASK) == TYPE_VOID)
{
yyerrorf( "Illegal to define variable '%s' as type 'void'"
, get_txt(ident->name));
}
if (current_number_of_locals >= MAX_LOCAL /* size of type recording array */
|| current_number_of_locals >= 256)
yyerror("Too many local variables");
else
{
ref_fulltype_data(&type);
if (ident->type != I_TYPE_UNKNOWN)
{
/* We're overlaying some other definition.
* If it's a global, or if we are in an inline-closure arg list,
* it's ok.
*/
#ifdef USE_NEW_INLINES
#ifdef DEBUG_INLINES
if (current_inline && current_inline->block_depth+2 == block_depth && ident->type != I_TYPE_GLOBAL) printf("DEBUG: redeclare local '%s' as inline arg, depth %d\n", get_txt(ident->name), block_depth);
#endif /* DEBUG_INLINES */
if (ident->type != I_TYPE_GLOBAL
&& !(current_inline && current_inline->block_depth+2 == block_depth)
)
{
yywarnf( "Variable '%s' shadows previous declaration"
, get_txt(ident->name));
}
#else /* USE_NEW_INLINES */
if (!may_shadow && ident->type != I_TYPE_GLOBAL)
{
yywarnf( "Variable '%s' shadows previous declaration"
, get_txt(ident->name));
}
#endif /* USE_NEW_INLINES */
ident = make_shared_identifier(get_txt(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;
#ifdef USE_NEW_INLINES
ident->u.local.context = -1;
#endif /* USE_NEW_INLINES */
/* 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;
/* 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 ident_t *
redeclare_local (ident_t *ident, fulltype_t type, int depth)
/* Redeclare a local name <ident>, to <type> at <depth>; the references
* of <type> are NOT adopted (nor freed on error).
* 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.
*/
{
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);
}
if (ident->u.local.depth >= depth
|| (ident->u.local.depth == 1 && depth == 2)
#ifdef USE_NEW_INLINES
|| (current_inline && ident->u.local.depth == current_inline->block_depth+2
&& depth == current_inline->block_depth+3
)
#endif /* USE_NEW_INLINES */
)
{
yyerrorf("Illegal to redeclare local name '%s'", get_txt(ident->name));
}
else
{
#ifdef USE_NEW_INLINES
ident = add_local_name(ident, type, depth);
#else /* USE_NEW_INLINES */
ident = add_local_name(ident, type, depth, MY_FALSE);
#endif /* USE_NEW_INLINES */
}
return ident;
} /* redeclare_local() */
#ifdef USE_NEW_INLINES
/*-------------------------------------------------------------------------*/
static ident_t *
add_context_name (ident_t *ident, fulltype_t type, int num)
/* Declare a new context variable <ident> with the type <type> for the
* currently compiled inline closure. The references of <type> are NOT adopted.
* <num> is -1 for independent context
* variables, or the index of the inherited local variable.
* Return the (adjusted) ident for the new variable.
*/
{
int depth;
block_scope_t * block;
depth = current_inline->block_depth+1;
block = & block_scope[depth-1];
#ifdef DEBUG_INLINES
printf("DEBUG: add_context_name('%s', num %d) depth %d, context %d\n", get_txt(ident->name), num, depth, block->num_locals);
#endif /* DEBUG_INLINES */
if (block->num_locals >= 256
|| block->num_locals >= MAX_LOCAL /* size of type recording array */
)
{
yyerror("Too many context variables");
}
else
{
ref_fulltype_data(&type);
if (ident->type != I_TYPE_UNKNOWN)
{
/* We're overlaying some other definition, but that's ok.
*/
ident = make_shared_identifier(get_txt(ident->name), I_TYPE_LOCAL, depth);
}
/* Initialize the ident */
ident->type = I_TYPE_LOCAL;
ident->u.local.num = num;
ident->u.local.depth = depth;
ident->u.local.context = block->num_locals;
/* Put the ident into the list of all locals.
*/
if (all_locals && all_locals->u.local.depth > depth)
{
/* This context variable was detected after we already
* added locals - find the proper insertion point.
*/
ident_t * prev, *this;
for ( prev = all_locals, this = all_locals->next_all
; this && this->u.local.depth > depth
; prev = this, this = this->next_all) NOOP;
ident->next_all = this;
prev->next_all = ident;
}
else
{
ident->next_all = all_locals;
all_locals = ident;
}
/* Record the type */
type_of_context[block->num_locals] = type;
block->num_locals++;
}
return ident;
} /* add_context_name() */
/*-------------------------------------------------------------------------*/
static ident_t *
check_for_context_local (ident_t *ident, fulltype_t * pType)
/* The LPC code uses local variable <ident>. If we're compiling
* an inline closure, check if it is an inherited local for which
* no context variable has been created yet. If yes, create the context
* variable.
* Return the (possibly updated) ident, and store the variables type
* in *<pType>.
*/
{
int depth = ident->u.local.depth;
if (current_inline
&& depth <= current_inline->block_depth
)
{
/* This local has been inherited - create the
* proper context variable.
*/
if (ident->u.local.context >= 0)
{
if (!current_inline->parse_context
&& current_inline->prev != -1
&& depth <= INLINE_CLOSURE(current_inline->prev).block_depth
)
{
/* Can't use outer context variables when compiling
* an inline closure body.
*/
yyerrorf("Can't use context variable '%s' "
"across closure boundaries", get_txt(ident->name));
ident = redeclare_local(ident, Type_Any, block_depth);
*pType = Type_Any;
}
else
{
/* We can use outer context variables when compiling
* an inline closure context.
*/
*pType = LOCAL_TYPE(current_inline->full_context_type_start
+ ident->u.local.context
);
}
}
else /* it's a local */
{
fulltype_t type;
type = LOCAL_TYPE(current_inline->full_local_type_start
+ ident->u.local.num
);
if (!current_inline->parse_context)
{
ref_fulltype_data(&type);
ident = add_context_name( ident, type, ident->u.local.num);
}
*pType = type;
}
}
else if (ident->u.local.context >= 0)
*pType = type_of_context[ident->u.local.context];
else
*pType = type_of_locals[ident->u.local.num];
return ident;
} /* check_for_context_local() */
#endif /* USE_NEW_INLINES */
/*-------------------------------------------------------------------------*/
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() */
/* ====================== 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.typeflags)
{
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++)
{
vartype_t vt;
assign_full_to_vartype(&vt, type_of_locals[i]);
ref_vartype_data(&vt);
add_to_mem_block(A_ARGUMENT_TYPES, &vt, sizeof vt);
}
}
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>.
* The references of <type> are NOT adopted.
* 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;
/* Move the visibility-info into flags */
flags |= type.typeflags & ~TYPE_MOD_MASK;
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\""
, get_txt(p->name));
if (!(funp->flags & (NAME_UNDEFINED|NAME_PROTOTYPE|NAME_INHERITED) ) )
{
yyerrorf("Redeclaration of function %s.", get_txt(p->name));
if ( !(flags & NAME_PROTOTYPE) )
free_mstring(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.typeflags && funp->type.typeflags != 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'.", get_txt(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'.", get_txt(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."
, get_txt(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)
funflag_t f1 = funp->flags;
funflag_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];
t2 = funp->type;
strcpy(buff, get_visibility(t2));
yywarnf("Inconsistent declaration of '%s': Visibility changed from '%s' to '%s'"
, get_txt(p->name), buff, get_visibility(type));
}
# undef TYPE_MOD_VIS
}
/* Check if the 'varargs' attribute is conserved */
t1 = type; t1.typeflags &= TYPE_MOD_MASK;
t2 = funp->type; t2.typeflags &= TYPE_MOD_MASK;
if (!MASKED_TYPE(t1, t2))
{
if (pragma_pedantic)
yyerrorf("Inconsistent declaration of '%s': Return type mismatch %s", get_txt(p->name), get_two_types(t2, t1));
else if (pragma_check_overloads)
yywarnf("Inconsistent declaration of '%s': Return type mismatch %s", get_txt(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."
, get_txt(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];
t1.typeflags &= TYPE_MOD_RMASK;
assign_var_to_fulltype(&t2, argp[i]);
t2.typeflags &= 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"
, get_txt(p->name), i+1, get_two_types(t1, t2)
);
else if (pragma_check_overloads)
yywarnf("Argument type mismatch in "
"redefinition of '%s': arg %d %s"
, get_txt(p->name), i+1, get_two_types(t1, t2)
);
}
} /* for (all args) */
} /* if (compare_args) */
} /* if (exact_types && already defined) */
} /* if (!complete) */
/* Remember the heart_beat() function */
if (mstreq(p->name, STR_HEART_BEAT))
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;
free_fulltype_data(&funp->type);
funp->type = type;
ref_fulltype_data(&funp->type);
/* That's it */
return num;
} while(0); /* Test and handle for already defined functions */
/* It's a new function! */
if (mstreq(p->name, STR_HEART_BEAT))
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;
ref_fulltype_data(&fun.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(get_txt(p->name), I_TYPE_GLOBAL, 0);
}
/* should be I_TYPE_UNKNOWN now. */
init_global_identifier(p, /* bVariable: */ MY_TRUE);
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() */
/*-------------------------------------------------------------------------*/
static void
define_variable (ident_t *name, fulltype_t type)
/* Define a new global variable <name> of type <type>.
* The references of <type> are NOT adopted.
*/
{
variable_t dummy;
typeflags_t flags = type.typeflags;
int n;
if ((flags & PRIMARY_TYPE_MASK) == TYPE_VOID)
{
yyerrorf( "Illegal to define variable '%s' as type 'void'"
, get_txt(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(get_txt(name->name), I_TYPE_GLOBAL, 0);
}
init_global_identifier(name, /* bVariable: */ MY_TRUE);
name->next_all = all_globals;
all_globals = name;
}
else if (name->u.global.function == I_GLOBAL_FUNCTION_OTHER
&& (name->u.global.efun >= 0 || name->u.global.sim_efun >= 0)
)
{
/* 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;
}
/* 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;
}
/* If the variable already exists, make sure that we can redefine it */
if ( (n = name->u.global.variable) >= 0)
{
typeflags_t vn_flags = VARIABLE(n)->type.typeflags;
/* Visible nomask variables can't be redefined */
if ( vn_flags & TYPE_MOD_NO_MASK && !(flags & NAME_HIDDEN))
yyerrorf( "Illegal to redefine 'nomask' variable '%s'"
, get_txt(name->name));
/* We can redefine inherited variables if they are private or hidden,
* or if at least one of them is static.
*/
if ( ( !(vn_flags & NAME_INHERITED)
|| ( !(vn_flags & (TYPE_MOD_PRIVATE|NAME_HIDDEN))
&& !((flags | vn_flags) & TYPE_MOD_STATIC)
)
)
&& !(flags & NAME_INHERITED)
)
{
if (vn_flags & NAME_INHERITED)
yyerrorf("Illegal to redefine inherited variable '%s'"
, get_txt(name->name));
else
yyerrorf("Illegal to redefine global variable '%s'"
, get_txt(name->name));
}
if (((flags | vn_flags) & (TYPE_MOD_STATIC|TYPE_MOD_PRIVATE))
== TYPE_MOD_STATIC
&& !(flags & NAME_INHERITED)
)
{
yywarnf("Redefining inherited %s variable '%s' with a %s variable"
, (vn_flags & TYPE_MOD_STATIC)
? "nosave" : "non-nosave"
, get_txt(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 |= ~(vn_flags) & TYPE_MOD_STATIC;
}
else
{
vn_flags |= ~flags & TYPE_MOD_STATIC;
VARIABLE(n)->type.typeflags = vn_flags;
}
}
type.typeflags = flags;
dummy.name = ref_mstring(name->name);
dummy.type = type;
ref_fulltype_data(&dummy.type);
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);
}
else
{
if (!(flags & NAME_HIDDEN))
name->u.global.variable = NV_VARIABLE_COUNT;
add_to_mem_block(A_VARIABLES, &dummy, sizeof dummy);
}
} /* define_variable() */
/*-------------------------------------------------------------------------*/
static void
redeclare_variable (ident_t *name, fulltype_t type, int n)
/* The variable <name> is inherited virtually with number <n>.
* Redeclare it from its original type to <type>.
*/
{
typeflags_t flags = type.typeflags;
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 */
init_gloShowing the first 100 KB of 512.1 KB. Download the archive for the full file.