Exemple #1
0
int main( int argc, char** argv) {

    int ch = 0;
    char buf[STR_SIZE] = {};
    char* hisBuf = NULL;
    char str[STR_SIZE] = {};
    char historyArr[HISTORY_SIZE][STR_SIZE] = {};
    int inHistory = 0;
    int cmd = -1;

    List_t* list = new_list( );
    while( true) {
        getcwd( str, STR_SIZE);
        printf( "%s> ", str);

        fgets( buf, STR_SIZE, stdin);
        if( feof( stdin)) {
            printf( "logout\n");
            break;
        }
        if( buf[0] == '\n')
            continue;

        parse_program( list, buf);

        if( (cmd = commands( list->head->next->program)) >= 0) {
            switch( cmd) {
                case logout:
                    goto finish;
                    break;
                case cd:
                    if( chdir( list->head->next->program->arguments[0]) < 0)
                        warn( "Error while changing dir");
                    break;
                case history:
                    if( list->head->next->program->arguments[0][0]) {
                        hisBuf = get_history( historyArr, atoi( list->head->next->program->arguments[0]), inHistory);
                        if( hisBuf) {
                            strcpy( buf, hisBuf);
                            clear_list( list);
                            parse_program( list, buf);
                            printf( "%s\n", buf);
                            execute( list);
                        }
                    } else
                        dump_history( historyArr, inHistory);
                    break;
            }
        } else
            execute( list);
        if( cmd != history)
            inHistory = add_in_history( historyArr, buf, inHistory);
        clear_list( list);
    }

finish:
    destroy_list( list);
    return 0;
}
Exemple #2
0
static char *split_and_exec(int argc, char **args, char *tmpstr) {
	(void)args;
	int using_readline = argc == 1;
	int prev_point = 0;
	int next_point = 0;
	char *leftover = NULL;
	while ((next_point = get_split_point(tmpstr, prev_point)) != -1) {
		str = (char*)malloc(next_point - prev_point + 2);
		memcpy(str, tmpstr + prev_point, next_point - prev_point + 1);
		str[next_point - prev_point + 1] = '\0';
		prev_point = next_point + 1;
		if (strncmp(str,"exit", 3) == 0){
			printf("bye\n");
			free(str);
			free(tmpstr);
			exit(0);
		}
		int status;
		if (strlen(str) > 0) {
			status = -1;
			if (strlen(str) > 0 && is_unexpected_input(str)) {
				status = parse_program(str, using_readline);
			}
			myadd_history(str);
			while (!status) {
				status = exec(using_readline);
				if (!status) {
					status = parse_program(NULL, using_readline);
				} else if (!using_readline) {
					/* Stop execution */
					exit(1);
				}
			}
		}
		free(str);
		if (next_point == (int)strlen(tmpstr)) {
			break;
		}
	}
	/* copy leftover */
	if (next_point == -1) {
		leftover = (char*)malloc(strlen(tmpstr) - prev_point + 2);
		memcpy(leftover, tmpstr + prev_point ,strlen(tmpstr) - prev_point + 1);
		leftover[strlen(tmpstr) - prev_point] = ' ';
		leftover[strlen(tmpstr) - prev_point + 1] = '\0';
	}
	return leftover;
}
Exemple #3
0
bool parse() {
    tok = get_next_token();
    type program_type = parse_program();
    if (program_type == ERROR || program_type == ERROR_STAR)
        return true;
    return false;
}
Exemple #4
0
static void
digest_file (const char *file)
{
	scanner_t *scanner = scanner_new (file); 
	parse_program (scanner);
	scanner_free (scanner);
}
Exemple #5
0
/* wrap parse routines */
ast_node* parse() {
  ast_node* tree = ast_init();
  lookahead_1 = get_next_token(stdin);
  lookahead_2 = get_next_token(stdin);
  parse_program(tree);
  return tree;
}
Exemple #6
0
Parser::Parser(vector<Lexeme>& lexemes):
m_current_lexeme_index(0),
m_buf_lexeme_index(0),
m_lexemes(lexemes)
{
    m_program = parse_program();
}
Exemple #7
0
int main(int argc, char ** argv)
{
  arena_init();
  init_lexer();
  execute_program(parse_program());
  return 0;
}
Exemple #8
0
int
main( int argc, char **argv )
{
  char *buffer; size_t length;
  struct program *basic_program;
  int error;

  progname = argv[0];

  if( argc < 2 ) {
    fprintf( stderr, "%s: usage: %s <basic file>\n", progname, progname );
    return 1;
  }

  error = utils_read_file( &buffer, &length, argv[1] );
  if( error ) return error;

  basic_program = parse_program( buffer, length );
  if( !basic_program ) return 1;

  free( buffer );

  error = interpret_program( basic_program );
  if( error ) { program_free( basic_program ); return error; }

  if( program_free( basic_program ) ) {
    fprintf( stderr, "%s: error freeing program\n", progname );
    return 1;
  }

  return 0;
}
Exemple #9
0
bool VskBase::approve_program(VskProgram& program) {
    if (!m_program_approved) {
        if (!parse_program(program)) {
            return false;
        }
    }
    return true;
} // VskBase::approve_program
Exemple #10
0
int run_repl(context* ctx)
{
  parser_state* ps = calloc(sizeof(parser_state), 1);
  ps->die_on_error = 0;
  ps->error.max = 20;

  for(unsigned line = 1; ; ++line) {
    char* input = readline(">> ");

    if(input == NULL)
      break;

    add_history(input);

    char* ret = malloc(strlen(input) + 2);
    strcpy(ret, input);
    strcat(ret, "\n");
    free(input);

    reader r;
    string_reader_create(&r, ret);

    lexer_state* ls = calloc(sizeof(lexer_state), 1);
    lexer_create(ls, &r);

    ps->ls = ls;
    ps->ls->linenum = line;
    ps->t = lexer_next_token(ps->ls);

    expression_node* program = parse_program(ps);

    if(program && program->node.block) {

      for(struct expression_list* expr = program->node.block->list; expr; expr = expr->next) {

        expression_node* eval = expression_node_evaluate(expr->expression, ctx);
        char* str = expression_node_inspect(eval);

        printf("==> %s\n", str);

        free(str);
        expression_node_destroy(eval);
      }

      expression_node_destroy(program);

      free(r.fn_data);
      lexer_destroy(ls);
      free(ls);

      free(ret);
    }
  }

  free(ps);
  return 0;
}
Exemple #11
0
// Parse a range of tokens.
Tree*
Parser::operator()(Token_iterator f, Token_iterator l) {
  if (f == l)
    return nullptr;
  first = f; 
  last = l;
  current = first; 
  use_diagnostics(diags);
  return parse_program(*this);
}
Exemple #12
0
Program *
dbio_read_program(DB_Version version, const char *(*fmtr) (void *), void *data)
{
    struct state s;

    s.prev_char = '\n';
    s.fmtr = fmtr;
    s.data = data;
    return parse_program(version, parser_client, &s);
}
Exemple #13
0
int main(int argc, char ** argv){
  FILE * fp = stdout;
  if (argc < 2 || argc > 3){
    printf("Usage: %s input_file [output_file]\n", argv[0]);
    exit(1);
  }
  tokenizer_t t = mk_tokenizer(argv[1]);
  program_t p = parse_program(t);
  if (argc == 3) fp = safe_fopen(argv[2], "w");
  cogen_program(fp, p);
  return 0;
}
Exemple #14
0
int main(int argc, char **argv)
{
	arguments.debug = false;
	arguments.tree = false;
	arguments.symbols = false;
	arguments.checks = false;
	arguments.assemble = false;
	arguments.compile = false;
	arguments.output = "a.out";
	arguments.include = getcwd(NULL, 0);

	argp_parse(&argp, argc, argv, 0, 0, &arguments);

	char *objects = "";
	/* parse each input file as a new 'program' */
	for (int i = 0; arguments.input_files[i]; ++i) {
		char *filename = realpath(arguments.input_files[i], NULL);
		if (filename == NULL)
			log_error("could not find input file: %s",
			          arguments.input_files[i]);
		/* copy because Wormulon's basename modifies */
		char *copy = strdup(filename);
		const char *base = basename(copy);
		free(copy);
		/* append object name to end of objects */
		char *temp;
		asprintf(&temp, "%s %s.o", objects, base);
		/* free if previously allocated */
		if (strcmp(objects, "") != 0)
			free(objects);
		objects = temp;
		parse_program(filename);
	}

	/* link object files */
	if (!arguments.assemble && !arguments.compile) {
		char *command;
		asprintf(&command, "gcc -o %s%s", arguments.output, objects);
		int status = system(command);
		if (status != 0)
			log_error("command failed: %s", command);
		free(command);
		/* remove object files */
		asprintf(&command, "rm -f%s", objects);
		status = system(command);
		if (status != 0)
			log_error("command failed: %s", command);
		free(command);
	}

	return EXIT_SUCCESS;
}
Exemple #15
0
/*
parse

Starts the parsing process by creating a pointer to the tokens

Parameters: tokens
	a vector containg the tokens produced by lex.cpp

Return: none
*/
Tree parse(std::vector<Token>::iterator tokens){
	curr_token = tokens;
	int program_coutner = 0;
	
	// while(curr_token != tokens.end()){
		// std::cout << "\n-------------------------------------------------------\n"
		// 	<< "Program #" << ++program_coutner
		// 	<< "\n-------------------------------------------------------\n"
		// 	<< std::endl;
		Tree cst;
		parse_program(cst);

		// std::cout << "\n\n\tCST" << std::endl;
		// cst.print_tree(cst.get_root(), 0);
		return cst;
	// }
}
Exemple #16
0
std::pair<
  std::vector<std::unique_ptr<UnitEmitter>>,
  std::unique_ptr<ArrayTypeTable::Builder>
>
whole_program(std::vector<std::unique_ptr<UnitEmitter>> ues,
              int num_threads) {
  trace_time tracer("whole program");

  RuntimeOption::EvalLowStaticArrays = false;

  if (num_threads > 0) {
    parallel::num_threads = num_threads;
  }

  LitstrTable::get().setReading();

  auto program = parse_program(std::move(ues));

  state_after("parse", *program);

  Index index{borrow(program)};
  if (!options.NoOptimizations) {
    assert(check(*program));
    constant_pass(index, *program);
    analyze_iteratively(index, *program, AnalyzeMode::NormalPass);
    if (options.AnalyzePublicStatics) {
      analyze_public_statics(index, *program);
      analyze_iteratively(index, *program, AnalyzeMode::NormalPass);
    }
    final_pass(index, *program);
    state_after("optimize", *program);
  }

  if (options.AnalyzePublicStatics) {
    mark_persistent_static_properties(index, *program);
  }

  debug_dump_program(index, *program);
  print_stats(index, *program);

  LitstrTable::get().setWriting();
  ues = make_unit_emitters(index, *program);

  return { std::move(ues), std::move(index.array_table_builder()) };
}
/* parsing language hook */
static void slang_parse_file ()
{

    int i;
    for(i = 0; i<num_in_fnames; ++i) {
        parse_program(in_fnames[i]);
    } 
#if 0
  tree  char_p = build_pointer_type (char_type_node);
  tree  puts_type   = build_function_type_list (integer_type_node,
						char_p, NULL_TREE);
  tree  puts_fndecl = build_function_decl ("puts", true, puts_type);

  tree  main_type   = build_function_type_list (integer_type_node, NULL_TREE);
  tree  main_fndecl = build_function_decl ("main", false, main_type);

  const char *msg = "HelloWorld , ... This is pradeeps compiler";
  tree hello_str = build_string_literal (strlen(msg) + 1, msg);

  tree  call = build_call_expr (puts_fndecl,1, hello_str);
  tree block = make_node(BLOCK);
  tree       c1 = build_pointer_type (char_type_node);
  tree stmts = NULL_TREE ;//alloc_stmt_list ();
  append_to_statement_list (call, &stmts);

  build_function (main_fndecl, stmts, block);

  FILE *fd = fopen("/home/pradeep/Desktop/dump.txt","w");


  gimplify_function_tree (main_fndecl);

  dump_function_to_file (main_fndecl, fd, 0);

  fclose(fd);

  cgraph_finalize_function (main_fndecl, false);

  current_function_decl = NULL_TREE;
  pop_cfun();
#endif

}
void do_compile_job() {
	int mode;
	char input_name[1024];
	printf("Input your source file path:\n");
	scanf("%s", input_name);
	in = fopen(input_name, "r");
	printf("Input mode number:\n");
	printf("0 for bare running!\n");
	printf("1 to find local common subexpressions!\n");
	printf("2 to do temporary register allocation!\n");
	printf("3 to do live variable analysis!\n");
	scanf("%d", &mode);
	//////////////////////////////////////////////////////////////////////////
	get_token_with_history();
	parse_program();
	printf("**** quadruples before optimization ****\n");
	print_quadruples();
	//////////////////////////////////////////////////////////////////////////
	switch (mode) {
				case 0:
					gen_asm();
					break;
				case 1:
					gen_dag();
					printf("generated quadruples ****\n");
					print_quadruples();
					gen_asm();
					break;
				case 2:
					gen_asm_with_temp_reg_all();
					break;
				case 3:
					live_var_analysis();
					break;
				default:
					printf("Mode not accepted!\n");
					break;
	}
	printf("Compile successful!\n");
	printf("Filed stored to %s!\n", asm_path);
	fclose(stdout);
}
Exemple #19
0
bool settings_parser_c::parse(int argc, char *argv[]) {
    arg_c = argc;
    arg_v = argv;
    position = 1;
    for (int i = 0; i < parsers.size(); ++i) {
        parsers[i]->invoke_initialization(*this);
    }

    while (current_position() < argc && !stopped) {
        for (auto parser = parsers.begin(); parser != parsers.end(); parser++) {
            fetch_current_position();
            if ((*parser)->parse(*this)) {
                save_current_position((*parser));
            }
            restore_position();
        }
        if (saved_count() == 1) {
            try {
                pop_saved_parser()->invoke(*this);
            } catch (std::string error) {
                std::cerr << "Invalid parameter value: " << arg_v[position - 1] << " with error: " << error << std::endl;
                return false;
            }
        } else if (saved_count() > 1) {
            //ambiguous arguments
            //throw
            std::cerr << "ambiguous arguments" << std::endl;
        } else {
            if (is_program()) {
                parse_program();
                //parse_program//until separator detected
            } else {
                //unknown_argument
                std::cerr << "unknown argument " << arg_v[position] << std::endl;
                //throw "";
                return false;
            }
        }
    }
    return true;
}
Exemple #20
0
int main(int nc, char *np[]) {
	if(nc < 2){
		printf("File has not been specified\n");
		return -1;
	}
	if(init_scan(np[1]) < 0){
		printf("file: %s does not open\n",np[1]);
		return -1;
	}

	token = scan();
	init_cross();
	if(parse_program()==NORMAL){
		//クロスリファレンス表の出力
		printCrossRef();
	}

	//globalidrootのクリア
	release_globalidtab();
	end_scan();
	return 0;
}
void test_program() {
	char tmp;
	FILE *inn = fopen("tests/test_program.txt", "r");
	while (!feof(inn)) {
		in = fopen("test.txt", "w+");
		while ((tmp = fgetc(inn)) != '}' && tmp != -1)
			fprintf(in, "%c", tmp);
		if (tmp == EOF) break;
		if (tmp <= 31) continue;
		fseek(in, 0, SEEK_SET);
		idx = 0;
		get_token_with_history();
		label_top = 0;
		temp_table_top = 0;
		quadruple_top = 0;
		parse_program();
		printf("******************\n");
		print_quadruples();
		fclose(in);
		remove("test.txt");
	}
}
Exemple #22
0
int main(int argc, char* argv[]) {
	if (argc == 1) {
		printf("Duong dan file bi bo trong\n");
		return 0;
	}
	char* path = argv[1];
	
	if (!(f = fopen(path, "r"))) {
		printf("path:%s khong ton tai.\n",path);
		return 0;
	}
	if (!(f_output = fopen("machinecode.txt", "w"))) {
		printf("Khong the tao file code.\n");
		return 0;
	}
	
	struct token current_token;
	get_token_wrapper(&current_token);
	parse_program(&current_token, get_token_wrapper);
	fclose(f);
	fclose(f_output);
	return 0;
}
Exemple #23
0
int run_file(const char* filename, context* ctx)
{
  reader r;

  lexer_state* ls = calloc(sizeof(lexer_state), 1);
  parser_state* ps = calloc(sizeof(parser_state), 1);

  FILE* fp = fopen(filename, "r");

  if(!fp) {
    printf("Error: can't open file '%s'\n", filename);
    return 1;
  }

  file_reader_create(&r, fp);
  lexer_create(ls, &r);

  ps->ls = ls;
  ps->die_on_error = 0;
  ps->error.max = 20;
  ps->t = lexer_next_token(ps->ls);

  expression_node* program = parse_program(ps);
  expression_node* eval = expression_node_evaluate(program, ctx);
  expression_node_destroy(eval);
  expression_node_destroy(program);

  lexer_destroy(ls);
  free(ls);
  free(ps);

  free(r.fn_data);

  fclose(fp);

  return 0;
}
Exemple #24
0
int main(int argc, char *argv[]) {
  int opt;
  while ((opt = getopt(argc, argv, "i:")) != -1) {
    switch (opt) {
    case 'i':
      indent_step = atoi(optarg);
      break;
    default:
      usage(argv[0]);
    }
  }
  if (optind + 1 < argc) {
    usage(argv[0]);
  }
  if (optind < argc) {
    yyin = fopen(argv[optind], "r");
    if (!yyin) {
      err(1, argv[optind]);
    }
  }

  parse_program();
  return error_flag;
}
Exemple #25
0
Fichier : main.c Projet : gvlx/gawk
int
main(int argc, char **argv)
{
	/*
	 * The + on the front tells GNU getopt not to rearrange argv.
	 */
	const char *optlist = "+F:f:v:W;m:bcCd::D::e:E:gh:i:l:L:nNo::Op::MPrStVY";
	bool stopped_early = false;
	int old_optind;
	int i;
	int c;
	char *scan, *src;
	char *extra_stack;
	int have_srcfile = 0;
	SRCFILE *s;

	/* do these checks early */
	if (getenv("TIDYMEM") != NULL)
		do_flags |= DO_TIDY_MEM;

#ifdef HAVE_MCHECK_H
#ifdef HAVE_MTRACE
	if (do_tidy_mem)
		mtrace();
#endif /* HAVE_MTRACE */
#endif /* HAVE_MCHECK_H */

#if defined(LC_CTYPE)
	setlocale(LC_CTYPE, "");
#endif
#if defined(LC_COLLATE)
	setlocale(LC_COLLATE, "");
#endif
#if defined(LC_MESSAGES)
	setlocale(LC_MESSAGES, "");
#endif
#if defined(LC_NUMERIC) && defined(HAVE_LOCALE_H)
	/*
	 * Force the issue here.  According to POSIX 2001, decimal
	 * point is used for parsing source code and for command-line
	 * assignments and the locale value for processing input,
	 * number to string conversion, and printing output.
	 *
	 * 10/2005 --- see below also; we now only use the locale's
	 * decimal point if do_posix in effect.
	 *
	 * 9/2007:
	 * This is a mess. We need to get the locale's numeric info for
	 * the thousands separator for the %'d flag.
	 */
	setlocale(LC_NUMERIC, "");
	init_locale(& loc);
	setlocale(LC_NUMERIC, "C");
#endif
#if defined(LC_TIME)
	setlocale(LC_TIME, "");
#endif

#if MBS_SUPPORT
	/*
	 * In glibc, MB_CUR_MAX is actually a function.  This value is
	 * tested *a lot* in many speed-critical places in gawk. Caching
	 * this value once makes a speed difference.
	 */
	gawk_mb_cur_max = MB_CUR_MAX;
	/* Without MBS_SUPPORT, gawk_mb_cur_max is 1. */

	/* init the cache for checking bytes if they're characters */
	init_btowc_cache();
#endif

	(void) bindtextdomain(PACKAGE, LOCALEDIR);
	(void) textdomain(PACKAGE);

	(void) signal(SIGFPE, catchsig);
#ifdef SIGBUS
	(void) signal(SIGBUS, catchsig);
#endif

	(void) sigsegv_install_handler(catchsegv);
#define STACK_SIZE (16*1024)
	emalloc(extra_stack, char *, STACK_SIZE, "main");
	(void) stackoverflow_install_handler(catchstackoverflow, extra_stack, STACK_SIZE);
#undef STACK_SIZE

	myname = gawk_name(argv[0]);
	os_arg_fixup(&argc, &argv); /* emulate redirection, expand wildcards */

	if (argc < 2)
		usage(EXIT_FAILURE, stderr);

	/* initialize the null string */
	Nnull_string = make_string("", 0);

	/* Robustness: check that file descriptors 0, 1, 2 are open */
	init_fds();

	/* init array handling. */
	array_init();

	/* init the symbol tables */
	init_symbol_table();

	output_fp = stdout;

	/* we do error messages ourselves on invalid options */
	opterr = false;

	/* copy argv before getopt gets to it; used to restart the debugger */  
	save_argv(argc, argv);

	/* initialize global (main) execution context */
	push_context(new_context());

	/* option processing. ready, set, go! */
	for (optopt = 0, old_optind = 1;
	     (c = getopt_long(argc, argv, optlist, optab, NULL)) != EOF;
	     optopt = 0, old_optind = optind) {
		if (do_posix)
			opterr = true;

		switch (c) {
		case 'F':
			add_preassign(PRE_ASSIGN_FS, optarg);
			break;

		case 'E':
			disallow_var_assigns = true;
			/* fall through */
		case 'f':
			/*
			 * Allow multiple -f options.
			 * This makes function libraries real easy.
			 * Most of the magic is in the scanner.
			 *
			 * The following is to allow for whitespace at the end
			 * of a #! /bin/gawk line in an executable file
			 */
			scan = optarg;
			if (argv[optind-1] != optarg)
				while (isspace((unsigned char) *scan))
					scan++;
			src = (*scan == '\0' ? argv[optind++] : optarg);
			(void) add_srcfile((src && src[0] == '-' && src[1] == '\0') ?
					SRC_STDIN : SRC_FILE,
					src, srcfiles, NULL, NULL);

			break;

		case 'v':
			add_preassign(PRE_ASSIGN, optarg);
			break;

		case 'm':
			/*
			 * BWK awk extension.
			 *	-mf nnn		set # fields, gawk ignores
			 *	-mr nnn		set record length, ditto
			 *
			 * As of at least 10/2007, BWK awk also ignores it.
			 */
			if (do_lint)
				lintwarn(_("`-m[fr]' option irrelevant in gawk"));
			if (optarg[0] != 'r' && optarg[0] != 'f')
				warning(_("-m option usage: `-m[fr] nnn'"));
			break;

		case 'b':
			do_binary = true;
			break;

		case 'c':
			do_flags |= DO_TRADITIONAL;
			break;

		case 'C':
			copyleft();
			break;

		case 'd':
			do_flags |= DO_DUMP_VARS;
			if (optarg != NULL && optarg[0] != '\0')
				varfile = optarg;
			break;

		case 'D':
			do_flags |= DO_DEBUG;
			if (optarg != NULL && optarg[0] != '\0')
				command_file = optarg;
			break;

		case 'e':
			if (optarg[0] == '\0')
				warning(_("empty argument to `-e/--source' ignored"));
			else
				(void) add_srcfile(SRC_CMDLINE, optarg, srcfiles, NULL, NULL);
			break;

		case 'g':
			do_flags |= DO_INTL;
			break;

		case 'h':
			/* write usage to stdout, per GNU coding stds */
			usage(EXIT_SUCCESS, stdout);
			break;

		case 'i':
			(void) add_srcfile(SRC_INC, optarg, srcfiles, NULL, NULL);
			break;

		case 'l':
			(void) add_srcfile(SRC_EXTLIB, optarg, srcfiles, NULL, NULL);
			break;

		case 'L':
#ifndef NO_LINT
			do_flags |= DO_LINT_ALL;
			if (optarg != NULL) {
				if (strcmp(optarg, "fatal") == 0)
					lintfunc = r_fatal;
				else if (strcmp(optarg, "invalid") == 0) {
					do_flags &= ~DO_LINT_ALL;
					do_flags |= DO_LINT_INVALID;
				}
			}
			break;

		case 't':
			do_flags |= DO_LINT_OLD;
			break;
#else
		case 'L':
		case 't':
			break;
#endif

		case 'n':
			do_flags |= DO_NON_DEC_DATA;
			break;

		case 'N':
			use_lc_numeric = true;
			break;

		case 'O':
			do_optimize++;
			break;

		case 'p':
			do_flags |= DO_PROFILE;
			/* fall through */
		case 'o':
			do_flags |= DO_PRETTY_PRINT;
			if (optarg != NULL)
				set_prof_file(optarg);
			else
				set_prof_file(DEFAULT_PROFILE);
			break;

		case 'M':
#ifdef HAVE_MPFR
			do_flags |= DO_MPFR;
#endif
			break;

		case 'P':
			do_flags |= DO_POSIX;
			break;

		case 'r':
			do_flags |= DO_INTERVALS;
 			break;
 
		case 'S':
			do_flags |= DO_SANDBOX;
  			break;

		case 'V':
			do_version = true;
			break;

		case 'W':       /* gawk specific options - now in getopt_long */
			fprintf(stderr, _("%s: option `-W %s' unrecognized, ignored\n"),
				argv[0], optarg);
			break;

		case 0:
			/*
			 * getopt_long found an option that sets a variable
			 * instead of returning a letter. Do nothing, just
			 * cycle around for the next one.
			 */
			break;

		case 'Y':
#if defined(YYDEBUG) || defined(GAWKDEBUG)
			if (c == 'Y') {
				yydebug = 2;
				break;
			}
#endif
			/* if not debugging, fall through */
		case '?':
		default:
			/*
			 * If not posix, an unrecognized option stops argument
			 * processing so that it can go into ARGV for the awk
			 * program to see. This makes use of ``#! /bin/gawk -f''
			 * easier.
			 *
			 * However, it's never simple. If optopt is set,
			 * an option that requires an argument didn't get the
			 * argument. We care because if opterr is 0, then
			 * getopt_long won't print the error message for us.
			 */
			if (! do_posix
			    && (optopt == '\0' || strchr(optlist, optopt) == NULL)) {
				/*
				 * can't just do optind--. In case of an
				 * option with >= 2 letters, getopt_long
				 * won't have incremented optind.
				 */
				optind = old_optind;
				stopped_early = true;
				goto out;
			} else if (optopt != '\0') {
				/* Use POSIX required message format */
				fprintf(stderr,
					_("%s: option requires an argument -- %c\n"),
					myname, optopt);
				usage(EXIT_FAILURE, stderr);
			}
			/* else
				let getopt print error message for us */
			break;
		}
		if (c == 'E')	/* --exec ends option processing */
			break;
	}
out:

	if (do_nostalgia)
		nostalgia();

	/* check for POSIXLY_CORRECT environment variable */
	if (! do_posix && getenv("POSIXLY_CORRECT") != NULL) {
		do_flags |= DO_POSIX;
		if (do_lint)
			lintwarn(
	_("environment variable `POSIXLY_CORRECT' set: turning on `--posix'"));
	}

	if (do_posix) {
		use_lc_numeric = true;
		if (do_traditional)	/* both on command line */
			warning(_("`--posix' overrides `--traditional'"));
		else
			do_flags |= DO_TRADITIONAL;
			/*
			 * POSIX compliance also implies
			 * no GNU extensions either.
			 */
	}

	if (do_traditional && do_non_decimal_data) {
		do_flags &= ~DO_NON_DEC_DATA;
		warning(_("`--posix'/`--traditional' overrides `--non-decimal-data'"));
	}

	if (do_lint && os_is_setuid())
		warning(_("running %s setuid root may be a security problem"), myname);

#if MBS_SUPPORT
	if (do_binary) {
		if (do_posix)
			warning(_("`--posix' overrides `--characters-as-bytes'"));
		else
			gawk_mb_cur_max = 1;	/* hands off my data! */
#if defined(LC_ALL)
		setlocale(LC_ALL, "C");
#endif
	}
#endif

	if (do_debug)	/* Need to register the debugger pre-exec hook before any other */
		init_debug();

#ifdef HAVE_MPFR
	/* Set up MPFR defaults, and register pre-exec hook to process arithmetic opcodes */ 
	if (do_mpfr)
		init_mpfr(DEFAULT_PREC, DEFAULT_ROUNDMODE);
#endif

	/* load group set */
	init_groupset();

#ifdef HAVE_MPFR
	if (do_mpfr) {
		mpz_init(Nnull_string->mpg_i);
		Nnull_string->flags = (MALLOC|STRCUR|STRING|MPZN|NUMCUR|NUMBER);
	} else
#endif
	{
		Nnull_string->numbr = 0.0;
		Nnull_string->flags = (MALLOC|STRCUR|STRING|NUMCUR|NUMBER);
	}

	/*
	 * Tell the regex routines how they should work.
	 * Do this before initializing variables, since
	 * they could want to do a regexp compile.
	 */
	resetup();

	/* Set up the special variables */
	init_vars();

	/* Set up the field variables */
	init_fields();

	/* Now process the pre-assignments */
	for (i = 0; i <= numassigns; i++) {
		if (preassigns[i].type == PRE_ASSIGN)
			(void) arg_assign(preassigns[i].val, true);
		else	/* PRE_ASSIGN_FS */
			cmdline_fs(preassigns[i].val);
		efree(preassigns[i].val);
	}

	if (preassigns != NULL)
		efree(preassigns);

	if ((BINMODE & 1) != 0)
		if (os_setbinmode(fileno(stdin), O_BINARY) == -1)
			fatal(_("can't set binary mode on stdin (%s)"), strerror(errno));
	if ((BINMODE & 2) != 0) {
		if (os_setbinmode(fileno(stdout), O_BINARY) == -1)
			fatal(_("can't set binary mode on stdout (%s)"), strerror(errno));
		if (os_setbinmode(fileno(stderr), O_BINARY) == -1)
			fatal(_("can't set binary mode on stderr (%s)"), strerror(errno));
	}

#ifdef GAWKDEBUG
	setbuf(stdout, (char *) NULL);	/* make debugging easier */
#endif
	if (os_isatty(fileno(stdout)))
		output_is_tty = true;

	/* initialize API before loading extension libraries */
	init_ext_api();

	/* load extension libs */
        for (s = srcfiles->next; s != srcfiles; s = s->next) {
                if (s->stype == SRC_EXTLIB)
			load_ext(s->fullpath);
		else if (s->stype != SRC_INC)
			have_srcfile++;
        }

	/* do version check after extensions are loaded to get extension info */
	if (do_version)
		version();

	/* No -f or --source options, use next arg */
	if (! have_srcfile) {
		if (optind > argc - 1 || stopped_early) /* no args left or no program */
			usage(EXIT_FAILURE, stderr);
		(void) add_srcfile(SRC_CMDLINE, argv[optind], srcfiles, NULL, NULL);
		optind++;
	}

	/* Select the interpreter routine */
	init_interpret();

	init_args(optind, argc,
			do_posix ? argv[0] : myname,
			argv);

#if defined(LC_NUMERIC)
	/*
	 * FRAGILE!  CAREFUL!
	 * Pre-initing the variables with arg_assign() can change the
	 * locale.  Force it to C before parsing the program.
	 */
	setlocale(LC_NUMERIC, "C");
#endif
	/* Read in the program */
	if (parse_program(& code_block) != 0)
		exit(EXIT_FAILURE);
	
	if (do_intl)
		exit(EXIT_SUCCESS);

	if (do_lint)
		shadow_funcs();

	if (do_lint && code_block->nexti->opcode == Op_atexit)
		lintwarn(_("no program text at all!"));

	load_symbols();

	if (do_profile)
		init_profiling_signals();

#if defined(LC_NUMERIC)
	/*
	 * See comment above about using locale's decimal point.
	 *
	 * 10/2005:
	 * Bitter experience teaches us that most people the world over
	 * use period as the decimal point, not whatever their locale
	 * uses.  Thus, only use the locale's decimal point if being
	 * posixly anal-retentive.
	 *
	 * 7/2007:
	 * Be a little bit kinder. Allow the --use-lc-numeric option
	 * to also use the local decimal point. This avoids the draconian
	 * strictness of POSIX mode if someone just wants to parse their
	 * data using the local decimal point.
	 */
	if (use_lc_numeric)
		setlocale(LC_NUMERIC, "");
#endif
	
	init_io();
	output_fp = stdout;

	if (do_debug)
		debug_prog(code_block);
	else
		interpret(code_block);

	if (do_pretty_print) {
		dump_prog(code_block);
		dump_funcs();
	}

	if (do_dump_vars)
		dump_vars(varfile);

	if (do_tidy_mem)
		release_all_vars();
	
	/* keep valgrind happier */
	if (extra_stack)
		efree(extra_stack);

	final_exit(exit_val);
	return exit_val;	/* to suppress warnings */
}
Exemple #26
0
List_t* parse_program( List_t* list, char* buf) {
    int argmN = 0;
    int readN = 0;
	char* ptr = buf;

    Node_t* curr = new_node( );
    if( !curr) {
        printf( "Called by List_t* parse_program( List_t* list, char* buf)\n");
        return NULL;
    }

	if( sscanf( ptr, "%s%n", curr->program->name, &readN) < 1) {
        printf( "Error while reading input, "
                "maybe wrong format\n");
        if( !destroy_node( curr))
            printf( "Called by List_t* parse_program( List_t* list, char* buf)\n");
        return NULL;
    }

	ptr += readN;
	if( *ptr != ' ' ) {
//TODO add error check
        add( list, curr);
        return list;
    }
    ++ptr;

    if( *ptr == '>') {
        ++ptr;
        sscanf( ptr, "%s%n", curr->program->output_name, &readN);
        ptr += readN;
        if( *ptr == ' ')
            ++ptr;
    }
    if( *ptr == '<') {
        ++ptr;
        sscanf( ptr, "%s%n", curr->program->input_name, &readN);
        ptr += readN;
        if( *ptr == ' ')
            ++ptr;
    }


    if( *ptr == '|') {
        curr->type = inpipe;
        ++ptr;
        if( *ptr == ' ')
            ++ptr;
//TODO add error check
        add( list, curr);
        list = parse_program( list, ptr);
        return list;
    } else {
        while( sscanf( ptr, "%s%n", curr->program->arguments[argmN], &readN) == 1) {
            ++argmN;
            ptr += readN;

            if( *ptr != ' ') break;
            ++ptr;

            if( *ptr == '>') {
                ++ptr;
                sscanf( ptr, "%s%n", curr->program->output_name, &readN);
                ptr += readN;
                if( *ptr == ' ')
                    ++ptr;
            }
            if( *ptr == '<') {
                ++ptr;
                sscanf( ptr, "%s%n", curr->program->input_name, &readN);
                ptr += readN;
                if( *ptr == ' ')
                    ++ptr;
            }

            if( *ptr == '|') {
                curr->type = inpipe;
                ++ptr;
                if( *ptr == ' ')
                    ++ptr;
//TODO add error check
                add( list, curr);
                list = parse_program( list, ptr);
                return list;
            }
        }
        curr->type = last;
//TODO add error check
        add( list, curr);
    }
    return list;
}
static gboolean
parse_epg_dat_line (Request   *req,
                    gchar     *line,
                    GPtrArray *events)
{
  gchar *duration_s, *start_time_s, *end_time_s, *date_s;
  gboolean start_in_between, end_in_between, englobing;
  gint year, month, day, hours, minutes, duration;
  GDateTime *start_date, *end_date;
  gint n_parsed;

  duration_s = cut_last_field_out (line);
  if (duration_s == NULL)
    goto no_duration;

  end_time_s = cut_last_field_out (line);
  if (end_time_s == NULL)
    goto no_end_time;

  start_time_s = cut_last_field_out (line);
  if (start_time_s == NULL)
    goto no_start_time;

  date_s = cut_last_field_out (line);
  if (date_s == NULL)
    goto no_date;

  n_parsed = sscanf (date_s, "%d/%d/%d", &day, &month, &year);
  if (n_parsed != 3)
    goto scanf_failed;

  n_parsed = sscanf (start_time_s, "%d:%d", &hours, &minutes);
  if (n_parsed != 2)
    goto scanf_failed;

  duration = atoi (duration_s);
  if (duration == 0)
    return TRUE;

  /* duration is always is seconds in Mex, minutes in the data files */
  duration *= 60;

  start_date = g_date_time_new_local (year, month, day, hours, minutes, 0);
  end_date = g_date_time_add_seconds (start_date, duration);

  start_in_between = g_date_time_compare (start_date, req->start_date) >= 0
		     && g_date_time_compare (start_date, req->end_date) <= 0;
  end_in_between = g_date_time_compare (end_date, req->start_date) >= 0 &&
		   g_date_time_compare (end_date, req->end_date) <= 0;
  englobing = g_date_time_compare (start_date, req->start_date) <= 0 &&
              g_date_time_compare (end_date, req->end_date) >= 0;

  if (start_in_between || end_in_between || englobing)
    {
      MexEpgEvent *event;
      MexProgram *program;

      event = mex_epg_event_new_with_date_time (start_date, duration);

      program = parse_program (line);
      if (program == NULL)
        goto program_failed;

      /* we add the duration here as parse_program don't do it and that we
       * need the duration in seconds instead of minutes */
      duration_s = g_strdup_printf ("%d", duration);
      mex_program_set_metadata (program,
                                MEX_CONTENT_METADATA_DURATION,
                                duration_s);
      g_free (duration_s);

      mex_epg_event_set_program (event, program);
      g_object_unref (program);

      mex_epg_event_set_channel (event, req->channel);

      g_ptr_array_add (events, event);
    }

  return TRUE;

program_failed:
  MEX_WARN (EPG, "could not create the program: %s", line);
  return FALSE;
scanf_failed:
  MEX_WARN (EPG, "could not parse date or time: %s", line);
  return FALSE;
no_date:
  MEX_WARN (EPG, "could not find the date: %s", line);
  return FALSE;
no_start_time:
  MEX_WARN (EPG, "could not find the start time: %s", line);
  return FALSE;
no_end_time:
  MEX_WARN (EPG, "could not find the end time: %s", line);
  return FALSE;
no_duration:
  MEX_WARN (EPG, "could not find the duration: %s", line);
  return FALSE;
}
Exemple #28
0
int
main(int argc, char **argv)
{
	char **real_argv = argv;
	struct scan_st *sc;
	struct symbol_table *stab;
	struct ast *a;
	char *source = NULL;
	int opt;
	int err_count = 0;
#ifdef DEBUG
	int run_program = 1;
	int dump_symbols = 0;
	int dump_program = 0;
	int dump_icode = 0;
#endif

#ifdef DEBUG
	setvbuf(stdout, NULL, _IOLBF, 0);
#endif

	/*
	 * Get command-line arguments.
	 */
	while ((opt = getopt(argc, argv, OPTS)) != -1) {
		switch(opt) {
#ifdef DEBUG
		case 'c':
			trace_scheduling++;
			break;
#ifdef POOL_VALUES
		case 'd':
			trace_pool++;
			break;
#endif
		case 'g':
			trace_gc++;
			break;
#endif
		case 'G':
			gc_trigger = atoi(optarg);
			break;
#ifdef DEBUG
		case 'i':
			dump_icode++;
			break;
		case 'l':
			trace_gen++;
			break;
		case 'm':
			trace_vm++;
			break;
		case 'n':
			run_program = 0;
			break;
		case 'o':
			trace_valloc++;
			break;
		case 'p':
			dump_program = 1;
			break;
		case 's':
			dump_symbols = 1;
			break;
		case 'v':
			trace_activations++;
			break;
		case 'y':
			trace_type_inference++;
			break;
#endif
		case '?':
		default:
			usage(argv);
		}
	}
	argc -= optind;
	argv += optind;

	if (*argv != NULL)
		source = *argv;
	else
		usage(real_argv);

#ifdef POOL_VALUES
	value_pool_new();
#endif

	gc_target = gc_trigger;
	if ((sc = scan_open(source)) != NULL) {
		stab = symbol_table_new(NULL, 0);
		global_ar = activation_new_on_heap(100, NULL, NULL);
		register_std_builtins(stab);
		report_start();
		a = parse_program(sc, stab);
		scan_close(sc);
#ifdef DEBUG
		if (dump_symbols)
			symbol_table_dump(stab, 1);
		if (dump_program) {
			ast_dump(a, 0);
		}
#endif
#ifndef DEBUG
		symbol_table_free(stab);
		types_free();
#endif
		err_count = report_finish();
		if (err_count == 0) {
			struct iprogram *ip;
			struct vm *vm;
			struct process *p;
			unsigned char *program;

			program = bhuna_malloc(16384);

			ip = ast_gen_iprogram(a);
			iprogram_eliminate_nops(ip);
			iprogram_eliminate_useless_jumps(ip);
			iprogram_optimize_tail_calls(ip);
			iprogram_optimize_push_small_ints(ip);
			iprogram_eliminate_dead_code(ip);
			iprogram_gen(&program, ip);
#ifdef DEBUG
			if (dump_icode > 0)
				iprogram_dump(ip, program);
#endif

			vm = vm_new(program, 16384);
			vm_set_pc(vm, program);
			vm->current_ar = global_ar;
			p = process_new(vm);
			/* ast_dump(a, 0); */
			if (RUN_PROGRAM) {
				process_scheduler();
			}
			vm_free(vm);
			bhuna_free(program);
			/*value_dump_global_table();*/
		}

		ast_free(a);	/* XXX move on up */
		/* gc(); */		/* actually do a full blow out at the end */
		/* activation_free_from_stack(global_ar); */
#ifdef DEBUG
		symbol_table_free(stab);
		types_free();
		if (trace_valloc > 0) {
			/*
			value_dump_global_table();
			*/
			printf("Created:  %8d\n", num_vars_created);
			printf("Cached:   %8d\n", num_vars_cached);
			printf("Freed:    %8d\n", num_vars_freed);
		}
		if (trace_activations > 0) {
			printf("AR's alloc'ed:  %8d\n", activations_allocated);
			printf("AR's freed:     %8d\n", activations_freed);
		}
#ifdef POOL_VALUES
		if (trace_pool > 0) {
			pool_report();
		}
#endif
#endif
		return(0);
	} else {
		fprintf(stderr, "Can't open `%s'\n", source);
		return(1);
	}
}