#include <stdlib.h>
#include <memory.h>
#include "lpc.h"
#include "lexer.h"
/*
* Lexical string space (designed for fast addition of strings!)
* ok - limited to no more than 1 Meg of strings while compiling..
* that should be plenty!
*/
#define MAX_BLOCKS 80
#define BLOCK_SIZE 30000
#define DONT_FREE 1
char *lex_string_space[MAX_BLOCKS];
int LSP = 0, LSP_where = 0, LSP_max = 1;
int lex_boundary = DONT_FREE;
void init_lex_space()
{
int i;
for (i = 0; i < MAX_BLOCKS; i++)
lex_string_space[i] = 0;
for (i = 0; i < lex_boundary; i++)
lex_string_space[i] = (char *) malloc(BLOCK_SIZE);
}
void free_lex_space()
{
for (; LSP >= lex_boundary; LSP--)
{
free(lex_string_space[LSP]);
lex_string_space[LSP] = 0;
}
LSP_where = 0;
}
lexar * lex_str_copy(char *s)
{
int l;
lexar *ret;
l = strlen(s);
if (l > BLOCK_SIZE)
fatal("HUGE string found in lex_str_copy.\n");
if (BLOCK_SIZE - LSP_where < l)
{
LSP++;
if (LSP > LSP_max)
LSP_max = LSP;
if (LSP == MAX_BLOCKS)
fatal("No string space in lexer.\n");
if (!lex_string_space[LSP])
{
lex_string_space[LSP] = (char *) malloc(BLOCK_SIZE);
}
LSP_where = 0;
}
strncpy(&(lex_string_space[LSP][LSP_where]), s, l);
ret = (lexar *) malloc(sizeof(lexar));
ret->length = l;
ret->s = &(lex_string_space[LSP][LSP_where]);
LSP_where += l;
return ret;
}
/* concatenates onto a */
void lex_strcat(lexar * a, lexar * b)
{
lexar *y, *z;
Shared *t1, *t2;
if ((a->length + (int) a->s) == (int) b->s)
{
/* already lined up */
/*printf("lexstr cat lined up\n"); */
a->length += b->length;
free(b);
return;
}
/* this occurs if we crossed a block boundary */
/* this COULD be a source of error for huge strings */
/* 2 lex_str_copies are done so the strings are sequential */
/* in lex string space */
y = lex_str_copy((t1 = to_Cstring(a))->str);
z = lex_str_copy((t2 = to_Cstring(b))->str);
a->s = y->s;
a->length += z->length;
free(y); /* free the lexars */
free(z);
free(b); /* free the joined one? */
free_string(t1); /* free the temporary shared strings */
free_string(t2);
}
char * lex_Cstr_copy(char *s)
{
int l;
char *ret;
l = strlen(s);
if (l > BLOCK_SIZE)
fatal("HUGE string found in lex_Cstr_copy.\n");
if (BLOCK_SIZE - LSP_where <= l)
{
LSP++;
if (LSP > LSP_max)
LSP_max = LSP;
if (LSP == MAX_BLOCKS)
fatal("No string space in lexer.\n");
if (!lex_string_space[LSP])
{
lex_string_space[LSP] = (char *) malloc(BLOCK_SIZE);
}
LSP_where = 0;
}
strcpy(&(lex_string_space[LSP][LSP_where]), s);
ret = &(lex_string_space[LSP][LSP_where]);
LSP_where += l + 1;
return ret;
}
Shared * to_Cstring(lexar * s)
{
char *t;
Shared *n;
t = (char *) malloc(s->length + 1);
strncpy(t, s->s, s->length);
t[s->length] = '\0';
n = string_copy(t);
free(t);
// free(s);
return n;
}
char * to_str(lexar * s)
{
char * t;
char * n;
t = (char *) malloc(s->length + 1);
strncpy(t, s->s, s->length);
t[s->length] = '\0';
n = str_copy(t);
free(t);
return n;
}