Пример #1
0
pt_node *buildAST(const char *expr) {
	extern int yyparse(pt_node **, yyscan_t);

	FILE *file;
	yyscan_t scanner;
	pt_node *node = NULL;
	YY_BUFFER_STATE state;

	if(yylex_init(&scanner)) {
		fprintf(stderr, "Failed to initialize parser.\n");
		exit(-1);
	}

	file = fopen(expr, "r");
	if(file == NULL) {
		perror("fopen");
		exit(-1);
	}

	state = yy_create_buffer(file, 1024, scanner);
	yy_switch_to_buffer(state, scanner);

	if(yyparse(&node, scanner)) {
		fprintf(stderr, "Error parsing input.\n");
		exit(-1);
	}

	yy_delete_buffer(state, scanner);
	yylex_destroy(scanner);

	return node;
}
Пример #2
0
Файл: main.c Проект: cls/bohm
/* input and call the parser function.			*/
static void compile(char *file)
{
     printf("\n******** loading file %s ********\n",file);
     yypush_buffer_state(yy_create_buffer( yyin, 16384));
     yyin = fopen(file,"r");
     if (yyin==NULL)
	   printf("Fatal Error: cannot open file %s.\n",file);
     else
	{
	   loading_mode = 1;
	   while ((quit == 0) && (error_detected == false))
	     {
		yyparse();
	     }
	   if (error_detected == false)
	      printf("\n******** %s loaded ********\n",file);
	   else
	      {
		 printf("\n***** loading file %s aborted *****\n",file);
		 error_detected = false;
	      }
	   quit = 0;
	   loading_mode = 0;
	 }
     yypop_buffer_state();
}
Пример #3
0
int source_parse_file(source *src, const char *filename, const char *modname)
{
  YY_BUFFER_STATE bufstate;
  int r;

  if (NULL == (yyin = fopen(filename,"r"))) {
    perror(filename);
    return -1;
  }

  yyfilename = filename;
  yyfileno = add_parsedfile(src,filename);    ////yyfileno is the index in the src->parsedfiles
  yylloc.first_line = 1;

  bufstate = yy_create_buffer(yyin,YY_BUF_SIZE);
  yy_switch_to_buffer(bufstate);
  parse_src = src;
  parse_modname = modname ? modname : "";
  r = yyparse();
  yy_delete_buffer(bufstate);
#if HAVE_YYLEX_DESTROY
  yylex_destroy();
#endif

  if (yyin)
    fclose(yyin);

  return r;
}
Пример #4
0
ULONG fstk_RunInclude(char *s)
{
	FILE *f;
	char tzFileName[_MAX_PATH + 1];

	//printf( "INCLUDE: %s\n", s );

	strcpy(tzFileName, s);
	fstk_FindFile(tzFileName);
	//printf( "INCLUDING: %s\n", tzFileName );

	if ((f = fopen(tzFileName, "rt")) != NULL) {
		pushcontext();
		nLineNo = 1;
		nCurrentStatus = STAT_isInclude;
		strcpy(tzCurrentFileName, tzFileName);
		pCurrentFile = f;
		CurrentFlexHandle = yy_create_buffer(pCurrentFile);
		yy_switch_to_buffer(CurrentFlexHandle);

		//      Dirty hack to give the INCLUDE directive a linefeed

		yyunput('\n');
		nLineNo -= 1;

		return (1);
	} else
		return (0);
}
Пример #5
0
/*
 * Set up an include file for parsing
 */
void
fstk_RunInclude(char *tzFileName)
{
	FILE *f;

	f = fstk_FindFile(tzFileName);

	if (f == NULL) {
		err(1, "Unable to open included file '%s'",
		    tzFileName);
	}

	pushcontext();
	nLineNo = 1;
	nCurrentStatus = STAT_isInclude;
	strcpy(tzCurrentFileName, tzFileName);
	pCurrentFile = f;
	CurrentFlexHandle = yy_create_buffer(pCurrentFile);
	yy_switch_to_buffer(CurrentFlexHandle);

	//Dirty hack to give the INCLUDE directive a linefeed

	yyunput('\n');
	nLineNo -= 1;
}
Пример #6
0
void
lexer_set_buffer(RemarkFile *rf)
{
	yyin = rf->file;
	file = rf;
	yy_switch_to_buffer(yy_create_buffer(rf->file,YY_BUF_SIZE));
	rf->lex_buffer = YY_CURRENT_BUFFER;
}
Пример #7
0
Файл: read.c Проект: orodley/ali
LispObj *read_from_stream(FILE *stream)
{
	YY_BUFFER_STATE yy_buf = yy_create_buffer(stream, YY_BUF_SIZE);
	LispObj *obj = read_from_yybuf(yy_buf);
	yy_delete_buffer(yy_buf);

	return obj;
}
Пример #8
0
void parseFile(FILE* in)
{
  YY_BUFFER_STATE* tmp =  new YY_BUFFER_STATE;
  *tmp = yy_create_buffer(in, YY_BUF_SIZE);
  yy_switch_to_buffer(*tmp);
  if(buffer)
    yy_delete_buffer(*buffer);
    delete buffer;
  buffer = tmp;
}
Пример #9
0
TEST(BisonFlexTest, Test0009)
{
    FileHolder holder("./Resources/Example0009.titan");
    GTEST_ASSERT_NE((void*)0, holder.f);
    BufferStateHolder bp(yy_create_buffer(holder.f, YY_BUF_SIZE));
    yy_switch_to_buffer(bp.bp);
    int ans = yyparse();
    yy_flush_buffer(bp.bp);
    GTEST_ASSERT_EQ(0, ans);
}
Пример #10
0
/** Immediately switch to a different input stream.
 * @param input_file A readable stream.
 * 
 * @note This function does not reset the start condition to @c INITIAL .
 */
    void yyrestart  (FILE * input_file )
{
    
	if ( ! YY_CURRENT_BUFFER ){
        yyensure_buffer_stack ();
		YY_CURRENT_BUFFER_LVALUE =
            yy_create_buffer(yyin,YY_BUF_SIZE );
	}

	yy_init_buffer(YY_CURRENT_BUFFER,input_file );
	yy_load_buffer_state( );
}
Пример #11
0
void FidlParser::parse_import(const std::string& filename)
{
  //std::cout << "Parsing include file '" << filename << "'\n";

  bool ok = open_and_buffer_file(&open_files_, filename);
  if (!ok)
  {
    return;
  }

  YY_BUFFER_STATE new_buf = yy_create_buffer(open_files_.back().file_ptr_, YY_BUF_SIZE, lexer_);
  yypush_buffer_state(new_buf, lexer_);
}
Пример #12
0
int main(int argc, char **argv) {

  struct node *root = NULL;

  int i;
  int code = -1;
  const char *filelist[argc];

  if(argc == 1) {
    printf("No files to (F)lex!\n");
    return 0;
  }
  /* Put file names in list */
  argc--;
  argv++;
  for (i = 0; i < argc; i++) {
    filelist[i] = argv[i];
  }

  /* Push onto flex's convenient buffer */
  for (i = 0; i < argc; i++) {
    //    yyin = fopen(filelist[i],"r");
    yyin = fopen(argv[i],"r");
    if (yyin == NULL) {
      printf("%s is not a file!\n",filelist[i]);
      return 0;
    }

    
    /* Push onto filestack as defined in token.c */
    push_node(&filestack, filelist[i]);
    yypush_buffer_state(yy_create_buffer(yyin, YY_BUF_SIZE));
  }

  printf("FILES TO BE PARSED:\n");
  print_stack(&filestack);
    
  int parse_code = 0;

  
  while(!feof(yyin)) {
      parse_code = yyparse();

    }
  
  printf("Result: %d\n", parse_code);
  //      printf("%s\n",yylval.tptr->name);
  treeprint(t_unit, 0);
  return 0;
}
Пример #13
0
int yy_lex(){
	if (yy_buffer == NULL){
		yy_create_buffer();
	}
	int current_state = dfa_start, next_state, last_ac_state, act;
	char *last_ac_cp;
	while (1){
		last_ac_state = -1;
		last_ac_cp = NULL;
		if(*yy_cp == '\0'){
			return YY_NULL;
		}
		next_state = current_state;
		do{
			if(accept(next_state)){
				last_ac_cp = yy_cp;
				last_ac_state = next_state;
			}
			current_state = next_state;
			next_state = dfa_table[current_state][CHAR_TO_INT(*yy_cp)];
			yy_cp++;
		}while(next_state != -1);
		if(last_ac_state != -1){
			act = accept(last_ac_state);
			yy_cp = last_ac_cp;
			current_state = dfa_start;
		}else{
		return YY_ERROR;
		}
		switch(act){
case 1:
;
break;
case 2:
printf("find 'if'\n");
break;
case 3:
printf("find 'else'\n");
break;
case 4:
printf("find 'while'\n");
break;
case 5:
printf("find id\n");
break;
default:
return YY_ERROR;
		}
	}
}
Пример #14
0
int	yyincl(char *fn, int fil) {
	char		*s;

	DEBUG(CURDLEV+1,"Going to include (ptr=%d) %s \'%s\'.\n",include_stack_ptr,fil?"file":"string",fn);
	if (include_stack_ptr>=MAX_INCLUDE_DEPTH || include_stack_ptr<-MAX_INCLUDE_DEPTH) {
		PROGERROR("Includes are nested too deeply! %d",include_stack_ptr);
		exit(-1);
	}
	if (include_stack_ptr<0) {
		include_stack_ptr = -1;	 include_app = 0;
		inpfile = NULL;  include_stack_file[0] = NULL;
	}
			/* opens the given include file for reading */
	if (fil) {
		if (include_stack_ptr>0)	/* (tries also the subdir of the previous include) */
			s = fdir_extract(include_stack_fn[include_stack_ptr-1]);
		else  s = NULL;
		yyin = fopen_path(fn,"r",frame_path_read,s,frame_extension);
		//********* add stdin as an input "-" (interactive input) ........
		if (!yyin) {
			LERROR("Cannot open include file \'%s\'!",fn);
			return -1;
		}
		if (!FRNAME(curframe)) {
			frame_setname(curframe,s=fname_extract(fn));
			FREE(s);	/* (this s is a private copy of the string) */
		}
	}
	if (include_stack_ptr>=0) {	/* stores the current buffer, and opens a new buffer */
		include_stack[include_stack_ptr] = YY_CURRENT_BUFFER;
	}
	if (fil) {
		yy_switch_to_buffer(yy_create_buffer(yyin,YY_BUF_SIZE));
		if (include_stack_ptr+1>=0)  include_stack_file[include_stack_ptr+1] = yyin;
	} else {
		yy_scan_string(fn);
		if (include_stack_ptr+1>=0)  include_stack_file[include_stack_ptr+1] = NULL;
	}
	if (include_stack_ptr>=0) {	/* stores the whole current state on the stack */
		yy_push_state(INITIAL);
		include_stack_fn[include_stack_ptr] = inpfile;
		include_stack_ln[include_stack_ptr] = inpline;
	}
	inpfile = MSTRDUP(fn);	/* (freed in yywrap()) */
	inpline = 1;
	include_stack_ptr++;
	inpspecial = !fil;	/* whether special-lines should apply to this include - see SPECMATRIXLINE */
	return 0;
}
Пример #15
0
static VALUE
parse_file(VALUE self) {
  VALUE filename = rb_funcall(self, rb_intern("filename"), 0);
  VALUE lineno = rb_funcall(self, rb_intern("lineno"), 0);
  char *str = StringValueCStr(filename);
  FILE *f = fopen(str, "r");
  if(!f) {
    rb_funcall(self, rb_intern("file_error"), 2, rb_str_new2("Could not open file"), rb_str_new2(str));
    return Qnil;
  }
  YY_BUFFER_STATE buffstate = yy_create_buffer(f, YY_BUF_SIZE);
  yy_switch_to_buffer(buffstate);
  yylineno = NUM2INT(lineno);
  yyparse(self);
  yy_delete_buffer(buffstate);
  fclose(f);
  return self;
}
Пример #16
0
ULONG fstk_Init(char *s)
{
	char tzFileName[_MAX_PATH + 1];

	sym_AddString("__FILE__", s);

	strcpy(tzFileName, s);
	fstk_FindFile(tzFileName);

	pFileStack = NULL;
	if ((pCurrentFile = fopen(tzFileName, "rt")) != NULL) {
		nMacroCount = 0;
		nCurrentStatus = STAT_isInclude;
		strcpy(tzCurrentFileName, tzFileName);
		CurrentFlexHandle = yy_create_buffer(pCurrentFile);
		yy_switch_to_buffer(CurrentFlexHandle);
		nLineNo = 1;
		return (1);
	} else
		return (0);
}
Пример #17
0
/*
 * Initialize the filestack routines
 */
void
fstk_Init(char *s)
{
	char tzFileName[_MAX_PATH + 1];

	sym_AddString("__FILE__", s);

	strcpy(tzFileName, s);
	pFileStack = NULL;
	pCurrentFile = fopen(tzFileName, "rb");
	if (pCurrentFile == NULL) {
		err(1, "Unable to open file '%s'", tzFileName);
	}

	nMacroCount = 0;
	nCurrentStatus = STAT_isInclude;
	strcpy(tzCurrentFileName, tzFileName);
	CurrentFlexHandle = yy_create_buffer(pCurrentFile);
	yy_switch_to_buffer(CurrentFlexHandle);
	nLineNo = 1;
}
Пример #18
0
/* Compile a file */
void compile_file(compiler_type *comp_void, char *file_name, bool include_baselib) {
  compiler_core_type *compiler = (compiler_core_type *)comp_void;
  ins_stream_type *baselib = 0; /* TODO: should be gc root */
  FILE *in = 0;
  char path[PATH_MAX];

  /* Actually parse the input stream. */
  yylex_init_extra(compiler, &(compiler->scanner));

  in = fopen(file_name, "r");
  if (!in) {
    (void)fprintf(stderr, "Error %i while attempting to open '%s'\n",
      errno, file_name);
      assert(0);
  }

  //yyset_in(in, compiler->scanner);
  yy_switch_to_buffer(
    yy_create_buffer(in, YY_BUF_SIZE, compiler->scanner), compiler->scanner);

  push_include_path(compiler, file_name);

  /* TODO: Need a better way to handle GC than leaking */
  gc_protect(compiler->gc);

  /* Inject include for base library */
  if (include_baselib) {
    strcpy(path, compiler->home);
    strcat(path, "/lib/baselib.scm");

    STREAM_NEW(baselib, string, path);
    setup_include(compiler, baselib); 
  }
  
  parse_internal(compiler, compiler->scanner);
  
  gc_unprotect(compiler->gc);

  yylex_destroy(compiler->scanner);
}
Пример #19
0
/*
 * Set up an include file for parsing
 */
void fstk_RunInclude(char *tzFileName)
{
	char *incPathUsed = "";
	FILE *f = fstk_FindFile(tzFileName, &incPathUsed);

	if (f == NULL)
		err(1, "Unable to open included file '%s'", tzFileName);

	pushcontext();
	nLineNo = 1;
	nCurrentStatus = STAT_isInclude;
	snprintf(tzCurrentFileName, sizeof(tzCurrentFileName), "%s%s",
		 incPathUsed, tzFileName);
	pCurrentFile = f;
	CurrentFlexHandle = yy_create_buffer(pCurrentFile);
	yy_switch_to_buffer(CurrentFlexHandle);

	/* Dirty hack to give the INCLUDE directive a linefeed */

	yyunput('\n');
	nLineNo -= 1;
}
Пример #20
0
/* nested input files */
int newFile(char * _fileName)
{
	FILE * file = fopen(_fileName, "r");
	bufferStack * buffStack = 0;

	if(!file)
	{
		perror(_fileName);
		return -1;
	}

	buffStack = malloc(sizeof(bufferStack));
	if(!buffStack)
	{
		perror("malloc");
		exit(1);
	}

	// remember state
	if(curbs)
	{
		curbs->lineno = yylineno;
	}

	buffStack->previous = curbs;
	buffStack->currentFile = file;
	buffStack->fileName = _fileName;

	// set up current entry
	buffStack->bufferState = yy_create_buffer(file, YY_BUF_SIZE);
	yy_switch_to_buffer(buffStack->bufferState);
	curbs = buffStack;
	yylineno = 1;
	currentFileName = _fileName;

	return 1;
}
Пример #21
0
JSNode*
js_node_new_from_file (const gchar *name)
{
	FILE *f = fopen (name, "r");
	JSNodePrivate *priv;

	line_missed_semicolon = NULL;
	global = NULL;
	yyset_lineno (1);
	YY_BUFFER_STATE b = yy_create_buffer (f, 10000);
	yy_switch_to_buffer (b);

	yyparse ();

	fclose (f);

	yy_delete_buffer (b);
	if (!global)
		return g_object_new (JS_TYPE_NODE, NULL);
	priv = JS_NODE_GET_PRIVATE (global);

	priv->missed = line_missed_semicolon;
	return global;
}
Пример #22
0
int FOpenEntity(char *pName) {
    PEntRec p;
    FILE *pf;
    char *pcT1;
    char *pcT2;
    char rgTempnames[L_tmpnam];

#ifdef DEBUGGING
    MsgKwS(msgDEBUG,"FOpenEntity called to open ",pName,NULL);
    FILESTATUS(stdout,"stdout");
    FILESTATUS(stdin,"stdin");
    FILESTATUS(stderr,"stderr");
    FILESTATUS(yyin,"yyin");
#endif
    /* suppress the pero and the trailing reference close, if any */
    /* N.B. this assumes the reference concrete syntax and is
       VERY DIRTY.  You hear me?  DIRTY, DIRTY, DIRTY!!
    */
    pName = PCCleanperef(pName);
/*  for (pcT1 = pcT2 = pName; *pcT1 ; pcT1++) {
         if ((*pcT1 != '%')  && (*pcT1 != ';')
          && (*pcT1 != '\n') && (*pcT1 != '\r') && (*pcT1 != '\t')) {
              *pcT2++ = *pcT1;
         }
    }
    *pcT2 = '\0';
*/
    if (cEntCur == cEntMax) {
         MsgKwS(msgERROR,"Cannot open entity ", pName,
                ", too many entities open",NULL);
         return 0;
    }
    rgPCPos[cEntCur]     = pcEntpos;
    rgILine[cEntCur]     = cLinecount;
    if (yyin == stdin)
         rgPCFn[cEntCur] = fnCurrent = "<stdin>";
    rgBuffers[cEntCur++] = YY_CURRENT_BUFFER;
    p = PERLookup(pName);
    if (p == NULL) {
         MsgKwS(msgERROR,"Could not open entity ",pName,
               " (no record for it)",NULL);
              return 0;
    }
    rgEntities[cEntCur] = p;
    if (p->fExtern) {
         MsgKwS(msgVERBOSE,"Opening entity ",pName," (",
                   p->pcSysid,")",NULL);
         yyin = PFileOpenFnEnvMode(p->pcSysid,"DPP_PATH","r");
         if (yyin == NULL) {
              MsgKwS(msgERROR,"Could not open entity ",pName,
                   " (file ",p->pcSysid,")",NULL);
              cEntCur--;
              return 0;
         }
         yy_switch_to_buffer(yy_create_buffer(yyin,YY_BUF_SIZE));
#ifdef DEBUGGING
    FILESTATUS(stdout,"stdout");
    FILESTATUS(stdin,"stdin");
    FILESTATUS(stderr,"stderr");
    FILESTATUS(yyin,"yyin");
#endif
         fRdexternal = 1;
         pcEntpos = "";
         fnCurrent = rgPCFn[cEntCur] = p->pcSysid;
         cLinecount = 1;
         return 1;
    } else { /* handle internal entities */
         MsgKwS(msgTRACE,"Opening entity ",pName," (internal)",NULL);
         yy_switch_to_buffer(yy_create_buffer(yyin,YY_BUF_SIZE));
         pcEntpos = p->pcEnttext;
         fRdexternal = 0;
         fnCurrent = rgPCFn[cEntCur] = mycat2("%", p->pcEntname);
         cLinecount = 1;
         return 1;
    }
};
Пример #23
0
void parse_program(char *filename)
{
	printf("parsing file: %s\n", filename);

	yyfiles = list_new(NULL, &free);
	log_assert(yyfiles);
	list_push_back(yyfiles, filename);
	yyclibs = list_new(NULL, &free);
	log_assert(yyclibs);

	yyincludes = hasht_new(8, true, NULL, NULL, NULL);
	log_assert(yyincludes);


	/* open file for lexer */
	yyin = fopen(filename, "r");
	if (yyin == NULL)
		log_error("could not open input file: %s", filename);

	/* push buffer state for lexer */
	yypush_buffer_state(yy_create_buffer(yyin, YY_BUF_SIZE));

	/* setup yytypes table for lexer */
	yytypes = hasht_new(8, true, NULL, NULL, &free_typename);
	log_assert(yytypes);

	/* reset library flags */
	libs.usingstd	= false;
	libs.cstdlib	= false;
	libs.cmath	= false;
	libs.ctime	= false;
	libs.cstring	= false;
	libs.fstream	= false;
	libs.iostream	= false;
	libs.string	= false;
	libs.iomanip	= false;

	log_debug("invoking Bison");
	int result = yyparse();
	if (result != 0)
		exit(2);

	/* print syntax tree */
	if (arguments.tree)
		tree_traverse(yyprogram, 0, &print_tree, NULL, NULL);

	/* initialize scope stack */
	log_debug("setting up for semantic analysis");
	yyscopes = list_new(NULL, NULL);
	log_assert(yyscopes);

	struct hasht *global = hasht_new(32, true, NULL, NULL, &symbol_free);
	log_assert(global);
	list_push_back(yyscopes, global);

	/* build the symbol tables */
	log_debug("populating symbol tables");
	region = GLOBE_R;
	offset = 0;
	symbol_populate(yyprogram);
	log_debug("global scope had %zu symbols", hasht_used(global));

	/* constant symbol table put in front of stack for known location */
	struct hasht *constant = hasht_new(32, true, NULL, NULL, &symbol_free);
	log_assert(constant);
	list_push_front(yyscopes, constant);

	region = CONST_R;
	offset = 0;
	log_debug("type checking");
	type_check(yyprogram);

	/* generating intermediate code */
	log_debug("generating intermediate code");
	yylabels = 0; /* reset label counter */
	code_generate(yyprogram);
	struct list *code = ((struct node *)yyprogram->data)->code;

	/* iterate to get correct size of constant region */
	size_t string_size = 0;
	for (size_t i = 0; i < constant->size; ++i) {
		struct hasht_node *slot = constant->table[i];
		if (slot && !hasht_node_deleted(slot)) {
			struct typeinfo *v = slot->value;
			if (v->base == FLOAT_T)
				string_size += 8;
			else if (v->base == CHAR_T && v->pointer)
				string_size += v->token->ssize;
		}
	}

	/* print intermediate code file if debugging */
	if (arguments.debug) {
		char *output_file;
		asprintf(&output_file, "%s.ic", filename);
		FILE *ic = fopen(output_file, "w");
		if (ic == NULL)
			log_error("could not save to output file: %s",
			          output_file);

		fprintf(ic, ".file \"%s\"\n", filename);

		/* print .string region */
		fprintf(ic, ".string %zu\n", string_size);
		/* iterate to print everything but ints, chars, and bools */
		for (size_t i = 0; i < constant->size; ++i) {
			struct hasht_node *slot = constant->table[i];
			if (slot && !hasht_node_deleted(slot)) {
				struct typeinfo *v = slot->value;
				if (v->base == FLOAT_T
				    || (v->base == CHAR_T && v->pointer)) {
					fprintf(ic, "    ");
					print_typeinfo(ic, slot->key, v);
					fprintf(ic, "\n");
				}
			}
		}

		/* print .data region */
		fprintf(ic, ".data\n");
		for (size_t i = 0; i < global->size; ++i) {
			struct hasht_node *slot = global->table[i];
			if (slot && !hasht_node_deleted(slot)) {
				struct typeinfo *value = slot->value;
				if (value->base != FUNCTION_T) {
					fprintf(ic, "    ");
					print_typeinfo(ic, slot->key, value);
					fprintf(ic, "\n");
				}
			}
		}
		fprintf(ic, ".code\n");
		print_code(ic, code);
		fclose(ic);
		free(output_file);
	}

	log_debug("generating final code");
	/* copy because Wormulon */
	char *copy = strdup(filename);
	char *base = basename(copy);
	free(copy);
	char *output_file;
	asprintf(&output_file, "%s.c", base);
	FILE *fc = fopen(output_file, "w");
	if (fc == NULL)
		log_error("could not save to output file: %s", output_file);

	time_t t = time(NULL);
	struct tm *local = localtime(&t);
	char timestamp[60];
	strftime(timestamp, sizeof(timestamp), "%F %T", local);
	fprintf(fc, "/*\n");
	fprintf(fc, " * %s - 120++ Three-Address C Code\n", output_file);
	fprintf(fc, " * Generated @ %s\n", timestamp);
	fprintf(fc, " *\n");
	fprintf(fc, " * Created by Andrew Schwartzmeyer's 120++ Compiler\n");
	fprintf(fc, " * Project located @ https://github.com/andschwa/uidaho-cs445\n");
	fprintf(fc, " */\n\n");

	fprintf(fc, "/* Required includes for TAC-C */\n");
	fprintf(fc, "#include <stdlib.h>\n");
	fprintf(fc, "#include <stdbool.h>\n");
	fprintf(fc, "#include <string.h>\n");
	if (libs.usingstd && libs.iostream)
		fprintf(fc, "#include <stdio.h>\n");
	fprintf(fc, "\n");

	/* include passed-through C headers */
	fprintf(fc, "/* Source-file C headers */\n");
	struct list_node *iter = list_head(yyclibs);
	while (!list_end(iter)) {
		fprintf(fc, "#include %s\n", (char *)iter->data);
		iter = iter->next;
	}
	fprintf(fc, "\n");

	/* get maximum param size for faux stack */
	size_t max_param_size = 0;
	iter = list_head(code);
	while (!list_end(iter)) {
		struct op *op = iter->data;
		if (op->code == PROC_O) {
			size_t param_size = op->address[0].offset;
			if (param_size > max_param_size)
				max_param_size = param_size;
		}
		iter = iter->next;
	}

	fprintf(fc, "/* Memory regions */\n");
	fprintf(fc, "char constant[%zu];\n", string_size);
	fprintf(fc, "char global[%zu];\n", global->size);
	fprintf(fc, "char stack[%zu];\n", max_param_size);
	fprintf(fc, "\n");

	fprintf(fc, "/* Final Three-Address C Generated Code */\n");
	final_code(fc, code);
	fclose(fc);

	/* remove TAC-C "assembler" code */
	if (!arguments.assemble) {
		/* compile object files */
		char *command;
		asprintf(&command, "gcc -c %s", output_file);
		int status = system(command);
		if (status != 0)
			log_error("command failed: %s", command);

		remove(output_file);
	}

	free(output_file);

	/* clean up */
	log_debug("cleaning up");
	tree_free(yyprogram);
	yylex_destroy();
	hasht_free(yytypes);
	free(yyincludes); /* values all referenced elsewhere */
	list_free(yyfiles);
	list_free(yyclibs);
	list_free(yyscopes);
}
Пример #24
0
int main(int argc, char **argv) {
	for (;;) {
		int c = getopt(argc, argv, "y");
		if (c == -1) break;
		switch (c) {
		case 'y':
			option_easy = 1;
			option_prompt = "> ";
			break;
		default:
			fprintf(stderr, "unrecognized option: %c\n", c);
			break;
		}
	}

	field_init_z(Z);
	field_init_multiz(M);
	symtab_init(tab);

	builtin(fun_rnd);
	builtin(fun_random);
	builtin(fun_ord);
	builtin(fun_order);
	builtin(fun_nextprime);
	builtin(fun_sqrt);
	builtin(fun_inv);
	builtin(fun_type);
	builtin(fun_pairing);
	builtin(fun_zmod);
	builtin(fun_poly);
	builtin(fun_polymod);
	builtin(fun_extend);
	builtin(fun_exit);
	builtin(fun_CHECK);
	builtin(fun_init_pairing_a);
	builtin(fun_init_pairing_d);
	builtin(fun_init_pairing_e);
	builtin(fun_init_pairing_f);
	builtin(fun_init_pairing_g);
	builtin(fun_init_pairing_i);
	run_init_pairing_a(NULL);
	symtab_put(reserved, val_new_field(M), "M");
	symtab_put(reserved, val_new_field(Z), "Z");

	if (argc > optind) {
		FILE *fp = fopen(argv[optind], "r");
		if (!fp) pbc_die("fopen failed on %s", argv[optind]);
		YY_BUFFER_STATE st = yy_create_buffer(fp, YY_BUF_SIZE);
		yy_switch_to_buffer(st);
		yywrapfun = yywrap_return1;
		yyparse();
		yy_delete_buffer(st);
	}
	else {
		yywrapfun = yywrap_readline;
		yywrap();
		while (!end_of_input) {
			if (2 == yyparse()) pbc_die("parser out of memory");
		}
		putchar('\n');
	}

	symtab_clear(tab);
	field_clear(M);
	return 0;
}
Пример #25
0
void EHI::parse_file(FILE *infile) {
	yy_buffer = yy_create_buffer(infile, YY_BUF_SIZE, scanner);
	yy_switch_to_buffer(yy_buffer, scanner);
	do_parse();
}