Esempio n. 1
0
File: ftmenu.c Progetto: taq/ftmenu
static void proc_menu_line(char *line){
	regex_t reg_exec, reg_exec_icon, reg_submenu, reg_submenu_icon, reg_include, reg_end;

	regmatch_t *match_exec = NULL;
	regmatch_t *match_exec_icon = NULL;
	regmatch_t *match_submenu = NULL;
	regmatch_t *match_submenu_icon = NULL;
	regmatch_t *match_include = NULL;

	char title[MAX_LINE_LENGTH];
	char command[MAX_LINE_LENGTH];
	char icon[MAX_LINE_LENGTH];

	regcomp(&reg_exec			 ,"^(.*\\[exec\\]) (.*\\()(.+)(\\)) (.*\\{)(.+)(\\})",REG_EXTENDED);
	regcomp(&reg_exec_icon	 ,"^(.*\\[exec\\]) (.*\\()(.+)(\\)) (.*\\{)(.+)(\\}) (.*<)(.+)(>)",REG_EXTENDED);
	regcomp(&reg_submenu     ,"^(.*\\[submenu\\]) (.*\\()(.+)(\\))",REG_EXTENDED);
	regcomp(&reg_submenu_icon,"^(.*\\[submenu\\]) (.*\\()(.+)(\\)) (.*<)(.+)(>)",REG_EXTENDED);
	regcomp(&reg_include		 ,"^(.*\\[include\\]) (.*\\()(.+)(\\))",REG_EXTENDED);
	regcomp(&reg_end			 ,"^.*\\[end",REG_EXTENDED);

	match_exec				= (regmatch_t *) malloc((reg_exec.re_nsub+1)*sizeof(regmatch_t));
	match_exec_icon		= (regmatch_t *) malloc((reg_exec_icon.re_nsub+1)*sizeof(regmatch_t));
	match_submenu			= (regmatch_t *) malloc((reg_submenu.re_nsub+1)*sizeof(regmatch_t));
	match_submenu_icon	= (regmatch_t *) malloc((reg_submenu_icon.re_nsub+1)*sizeof(regmatch_t));
	match_include			= (regmatch_t *) malloc((reg_include.re_nsub+1)*sizeof(regmatch_t));

	// exec with icon
	if(regexec(&reg_exec_icon,line,reg_exec_icon.re_nsub+1,match_exec_icon,0)==0){
		substring(line,title  ,match_exec_icon[3].rm_so,match_exec_icon[3].rm_eo);
		substring(line,command,match_exec_icon[6].rm_so,match_exec_icon[6].rm_eo);
		substring(line,icon   ,match_exec_icon[9].rm_so,match_exec_icon[9].rm_eo);
		create_exec(title,command,icon);
	// regular exec
	}else if(regexec(&reg_exec,line,reg_exec.re_nsub+1,match_exec,0)==0){
		substring(line,title  ,match_exec[3].rm_so,match_exec[3].rm_eo);
		substring(line,command,match_exec[6].rm_so,match_exec[6].rm_eo);
		create_exec(title,command,NULL);
	// submenu with icon
	}else if(regexec(&reg_submenu_icon,line,reg_submenu_icon.re_nsub+1,match_submenu_icon,0)==0){
		substring(line,title  ,match_submenu_icon[3].rm_so,match_submenu_icon[3].rm_eo);
		substring(line,icon   ,match_submenu_icon[6].rm_so,match_submenu_icon[6].rm_eo);
		create_submenu(title,icon);
	// regular submenu
	}else if(regexec(&reg_submenu,line,reg_submenu.re_nsub+1,match_submenu,0)==0){
		substring(line,title  ,match_submenu[3].rm_so,match_submenu[3].rm_eo);
		create_submenu(title,NULL);
	}else if(regexec(&reg_include,line,reg_include.re_nsub+1,match_include,0)==0){
		substring(line,title  ,match_include[3].rm_so,match_include[3].rm_eo);
		include_file(title);
	}else if(regexec(&reg_end,line,0,NULL,0)==0){
		menu_depth--;		
	}

	regfree(&reg_exec);
	regfree(&reg_exec_icon);
	regfree(&reg_submenu);
	regfree(&reg_submenu_icon);
	regfree(&reg_end);
}
Esempio n. 2
0
void include(std::string str, std::vector<std::pair<std::pair<std::string, std::string>, int> >::iterator & it) {//it为#include语句这行的迭代器
	std::string name = str;
	name.erase(0, first_real(name));//删除前面的空格
	if (name[0] == '"') {
		name.erase(0, 1);
		int i = name.find_last_of('"');
		if (i == std::string::npos) {
			pre_err(all_line.back().second, " lack of \" after file name.");
			return;
		}
		name.erase(i, 1);
		std::cout << "++++++++++++>>>   " << name << "    <<<+++++++++++++++";
		include_file(name, 1, it);
		return;
	}
	if (name[0] == '<') {
		std::cout << "还没写" << std::endl;
		return;
	}
	else pre_err(all_line.back().second, "some err in #include");
}
Esempio n. 3
0
/* Try to include the file NAME.  Returns true if it does not
   exist. */
static int
try_include_file (const char *fname, int lnr, const char *name,
                  void (*outf)(char*))
{
  int rc;
  char *incfname;
  int repl_flag;

  repl_flag = !!strchr (name, '&');
  incfname = mk_include_name (name, repl_flag? host_triplet : NULL);
  rc = access (incfname, R_OK);
  if (rc && repl_flag)
    {
      free (incfname);
      incfname = mk_include_name (name, host_os);
      rc = access (incfname, R_OK);
    }
  if (!rc)
    include_file (fname, lnr, name, outf);

  free (incfname);
  return rc;
}
Esempio n. 4
0
int lookup_read_master(struct master *master, time_t age, void *context)
{
        int n, i;
	struct dirent **namelist = NULL;
	struct lookup_context *ctxt = (struct lookup_context *) context;
	unsigned int logopt = master->logopt;
	char buf[MAX_ERR_BUF];


	if (master->depth > MAX_INCLUDE_DEPTH) {
		error(logopt, MODPREFIX
		      "maximum include depth exceeded %s", master->name);
		return NSS_STATUS_UNAVAIL;
	}

	debug(logopt, MODPREFIX "scandir: %s", ctxt->mapname);
	n = scandir(ctxt->mapname, &namelist, acceptable_dirent_p, versionsort);
	if (n < 0) {
	       char *estr = strerror_r(errno, buf, MAX_ERR_BUF);

		error(logopt,
		      MODPREFIX "could not scan master map dir %s: %s",
		      ctxt->mapname,
		      estr);
		return NSS_STATUS_UNAVAIL;
	}

	for (i = 0; i < n; i++) {
		struct dirent *e = namelist[i];

		include_file(master, age, ctxt, e);
		free(e);
	}
	free(namelist);

	return NSS_STATUS_SUCCESS;
}
Esempio n. 5
0
int
main(int argc, char *argv[])
{
	int  ch;
	int  retval;
	char *inputfilename;
	scope_t *sentinal;

	STAILQ_INIT(&patches);
	SLIST_INIT(&search_path);
	STAILQ_INIT(&seq_program);
	TAILQ_INIT(&cs_tailq);
	SLIST_INIT(&scope_stack);

	/* Set Sentinal scope node */
	sentinal = scope_alloc();
	sentinal->type = SCOPE_ROOT;
	
	includes_search_curdir = 1;
	appname = *argv;
	regfile = NULL;
	listfile = NULL;
#if DEBUG
	yy_flex_debug = 0;
	mm_flex_debug = 0;
	yydebug = 0;
	mmdebug = 0;
#endif
	while ((ch = getopt(argc, argv, "d:i:l:n:o:p:r:I:X")) != -1) {
		switch(ch) {
		case 'd':
#if DEBUG
			if (strcmp(optarg, "s") == 0) {
				yy_flex_debug = 1;
				mm_flex_debug = 1;
			} else if (strcmp(optarg, "p") == 0) {
				yydebug = 1;
				mmdebug = 1;
			} else {
				fprintf(stderr, "%s: -d Requires either an "
					"'s' or 'p' argument\n", appname);
				usage();
			}
#else
			stop("-d: Assembler not built with debugging "
			     "information", EX_SOFTWARE);
#endif
			break;
		case 'i':
			stock_include_file = optarg;
			break;
		case 'l':
			/* Create a program listing */
			if ((listfile = fopen(optarg, "w")) == NULL) {
				perror(optarg);
				stop(NULL, EX_CANTCREAT);
			}
			listfilename = optarg;
			break;
		case 'n':
			/* Don't complain about the -nostdinc directrive */
			if (strcmp(optarg, "ostdinc")) {
				fprintf(stderr, "%s: Unknown option -%c%s\n",
					appname, ch, optarg);
				usage();
				/* NOTREACHED */
			}
			break;
		case 'o':
			if ((ofile = fopen(optarg, "w")) == NULL) {
				perror(optarg);
				stop(NULL, EX_CANTCREAT);
			}
			ofilename = optarg;
			break;
		case 'p':
			/* Create Register Diagnostic "printing" Functions */
			if ((regdiagfile = fopen(optarg, "w")) == NULL) {
				perror(optarg);
				stop(NULL, EX_CANTCREAT);
			}
			regdiagfilename = optarg;
			break;
		case 'r':
			if ((regfile = fopen(optarg, "w")) == NULL) {
				perror(optarg);
				stop(NULL, EX_CANTCREAT);
			}
			regfilename = optarg;
			break;
		case 'I':
		{
			path_entry_t include_dir;

			if (strcmp(optarg, "-") == 0) {
				if (includes_search_curdir == 0) {
					fprintf(stderr, "%s: Warning - '-I-' "
							"specified multiple "
							"times\n", appname);
				}
				includes_search_curdir = 0;
				for (include_dir = SLIST_FIRST(&search_path);
				     include_dir != NULL;
				     include_dir = SLIST_NEXT(include_dir,
							      links))
					/*
					 * All entries before a '-I-' only
					 * apply to includes specified with
					 * quotes instead of "<>".
					 */
					include_dir->quoted_includes_only = 1;
			} else {
				include_dir =
				    (path_entry_t)malloc(sizeof(*include_dir));
				if (include_dir == NULL) {
					perror(optarg);
					stop(NULL, EX_OSERR);
				}
				include_dir->directory = strdup(optarg);
				if (include_dir->directory == NULL) {
					perror(optarg);
					stop(NULL, EX_OSERR);
				}
				include_dir->quoted_includes_only = 0;
				SLIST_INSERT_HEAD(&search_path, include_dir,
						  links);
			}
			break;
		}
		case 'X':
			/* icc version of -nostdinc */
			break;
		case '?':
		default:
			usage();
			/* NOTREACHED */
		}
	}
	argc -= optind;
	argv += optind;

	if (argc != 1) {
		fprintf(stderr, "%s: No input file specifiled\n", appname);
		usage();
		/* NOTREACHED */
	}

	if (regdiagfile != NULL
	 && (regfile == NULL || stock_include_file == NULL)) {
		fprintf(stderr,
			"%s: The -p option requires the -r and -i options.\n",
			appname);
		usage();
		/* NOTREACHED */
	}
	symtable_open();
	inputfilename = *argv;
	include_file(*argv, SOURCE_FILE);
	retval = yyparse();
	if (retval == 0) {
		if (SLIST_FIRST(&scope_stack) == NULL
		 || SLIST_FIRST(&scope_stack)->type != SCOPE_ROOT) {
			stop("Unterminated conditional expression", EX_DATAERR);
			/* NOTREACHED */
		}

		/* Process outmost scope */
		process_scope(SLIST_FIRST(&scope_stack));
		/*
		 * Decend the tree of scopes and insert/emit
		 * patches as appropriate.  We perform a depth first
		 * tranversal, recursively handling each scope.
		 */
		/* start at the root scope */
		dump_scope(SLIST_FIRST(&scope_stack));

		/* Patch up forward jump addresses */
		back_patch();

		if (ofile != NULL)
			output_code();
		if (regfile != NULL)
			symtable_dump(regfile, regdiagfile);
		if (listfile != NULL)
			output_listing(inputfilename);
	}

	stop(NULL, 0);
	/* NOTREACHED */
	return (0);
}
Esempio n. 6
0
FILE *
collect(struct header *hp, int printheaders, struct message *mp,
		char *quotefile, int doprefix, int tflag)
{
	FILE *fbuf;
	struct ignoretab *quoteig;
	int lc, cc, escape, eofcount;
	int c, t;
	char *linebuf = NULL, *cp, *quote = NULL;
	size_t linesize;
	char *tempMail = NULL;
	int getfields;
	sigset_t oset, nset;
	long count;
	enum sendaction	action;
	sighandler_type	savedtop;
	const char tildehelp[] =
"-------------------- ~ ESCAPES ----------------------------\n\
~~              Quote a single tilde\n\
~@ [file ...]   Edit attachment list\n\
~b users        Add users to \"blind\" cc list\n\
~c users        Add users to cc list\n\
~d              Read in dead.letter\n\
~e              Edit the message buffer\n\
~f messages     Read in messages without indenting lines\n\
~F messages     Same as ~f, but keep all header lines\n\
~h              Prompt for to list, subject, cc, and \"blind\" cc list\n\
~r file         Read a file into the message buffer\n\
~p              Print the message buffer\n\
~q              Abort message composition and save text to dead.letter\n\
~m messages     Read in messages with each line indented\n\
~M messages     Same as ~m, but keep all header lines\n\
~s subject      Set subject\n\
~t users        Add users to to list\n\
~v              Invoke display editor on message\n\
~w file         Write message onto file\n\
~x              Abort message composition and discard text written so far\n\
~!command       Invoke the shell\n\
~:command       Execute a regular command\n\
-----------------------------------------------------------\n";

	(void) &escape;
	(void) &eofcount;
	(void) &getfields;
	(void) &tempMail;
	(void) &tflag;
	(void) &quote;

	collf = NULL;
	/*
	 * Start catching signals from here, but we're still die on interrupts
	 * until we're in the main loop.
	 */
	sigemptyset(&nset);
	sigaddset(&nset, SIGINT);
	sigaddset(&nset, SIGHUP);
	sigprocmask(SIG_BLOCK, &nset, &oset);
	handlerpush(collint);
	if ((saveint = safe_signal(SIGINT, SIG_IGN)) != SIG_IGN)
		safe_signal(SIGINT, collint);
	if ((savehup = safe_signal(SIGHUP, SIG_IGN)) != SIG_IGN)
		safe_signal(SIGHUP, collhup);
	savetstp = safe_signal(SIGTSTP, collstop);
	savettou = safe_signal(SIGTTOU, collstop);
	savettin = safe_signal(SIGTTIN, collstop);
	if (sigsetjmp(collabort, 1)) {
		if (tempMail != NULL) {
			rm(tempMail);
			Ftfree(&tempMail);
		}
		goto err;
	}
	if (sigsetjmp(colljmp, 1)) {
		if (tempMail != NULL) {
			rm(tempMail);
			Ftfree(&tempMail);
		}
		goto err;
	}
	sigprocmask(SIG_SETMASK, &oset, (sigset_t *)NULL);

	noreset++;
	if ((collf = Ftemp(&tempMail, "Rs", "w+", 0600, 1)) == NULL) {
		perror(catgets(catd, CATSET, 51, "temporary mail file"));
		goto err;
	}
	unlink(tempMail);
	Ftfree(&tempMail);

	if ((cp = value("MAILX_HEAD")) != NULL) {
		if (is_a_tty[0])
			putesc(cp, stdout);
		putesc(cp, collf);
	}

	/*
	 * If we are going to prompt for a subject,
	 * refrain from printing a newline after
	 * the headers (since some people mind).
	 */
	getfields = 0;
	if (!tflag) {
		t = GTO|GSUBJECT|GCC|GNL;
		if (value("fullnames"))
			t |= GCOMMA;
		if (hp->h_subject == NULL && value("interactive") != NULL &&
			    (value("ask") != NULL || value("asksub") != NULL))
			t &= ~GNL, getfields |= GSUBJECT;
		if (hp->h_to == NULL && value("interactive") != NULL)
			t &= ~GNL, getfields |= GTO;
		if (value("bsdcompat") == NULL && value("askatend") == NULL &&
				value("interactive")) {
			if (hp->h_bcc == NULL && value("askbcc"))
				t &= ~GNL, getfields |= GBCC;
			if (hp->h_cc == NULL && value("askcc"))
				t &= ~GNL, getfields |= GCC;
		}
		if (printheaders) {
			puthead(hp, stdout, t, SEND_TODISP, CONV_NONE,
					NULL, NULL);
			fflush(stdout);
		}
	}

	/*
	 * Quote an original message
	 */
	if (mp != NULL && (doprefix || (quote = value("quote")) != NULL)) {
		quoteig = allignore;
		action = SEND_QUOTE;
		if (doprefix) {
			quoteig = fwdignore;
			if ((cp = value("fwdheading")) == NULL)
				cp = "-------- Original Message --------";
			if (*cp) {
				fprintf(collf, "%s\n", cp);
				fprintf(stdout, "%s\n", cp);
			}
		} else if (strcmp(quote, "noheading") == 0) {
			/*EMPTY*/;
		} else if (strcmp(quote, "headers") == 0) {
			quoteig = ignore;
		} else if (strcmp(quote, "allheaders") == 0) {
			quoteig = NULL;
			action = SEND_QUOTE_ALL;
		} else {
			cp = hfield("from", mp);
			if (cp != NULL) {
				mime_write(cp, strlen(cp),
						collf, CONV_FROMHDR, TD_NONE,
						NULL, (size_t) 0,
						NULL, NULL);
				mime_write(cp, strlen(cp),
						stdout, CONV_FROMHDR, TD_NONE,
						NULL, (size_t) 0,
						NULL, NULL);
				fwrite(catgets(catd, CATSET, 52,
					" wrote:\n\n"), sizeof(char), 9, collf);
				fwrite(catgets(catd, CATSET, 52,
					" wrote:\n\n"), sizeof(char), 9, stdout);
			}
		}
		cp = value("indentprefix");
		if (cp != NULL && *cp == '\0')
			cp = "\t";
		send(mp, collf, quoteig, doprefix ? NULL : cp, action, NULL);
		send(mp, stdout, quoteig, doprefix ? NULL : cp, action, NULL);
	}

	if ((cp = value("escape")) != NULL)
		escape = *cp;
	else
		escape = ESCAPE;
	eofcount = 0;
	hadintr = 0;

	if (!sigsetjmp(colljmp, 1)) {
		if (getfields)
			grabh(hp, getfields, 1);
		if (quotefile != NULL) {
			if (include_file(NULL, quotefile, &lc, &cc, 1) != 0)
				goto err;
		}
	} else {
		/*
		 * Come here for printing the after-signal message.
		 * Duplicate messages won't be printed because
		 * the write is aborted if we get a SIGTTOU.
		 */
cont:
		if (hadintr) {
			fflush(stdout);
			fprintf(stderr, catgets(catd, CATSET, 53,
				"\n(Interrupt -- one more to kill letter)\n"));
		} else {
			printf(catgets(catd, CATSET, 54, "(continue)\n"));
			fflush(stdout);
		}
	}
	if (value("interactive") == NULL && tildeflag <= 0 && !is_a_tty[0] &&
			!tflag) {
		/*
		 * No tilde escapes, interrupts not expected. Copy
		 * standard input the simple way.
		 */
		linebuf = srealloc(linebuf, linesize = BUFSIZ);
		while ((count = fread(linebuf, sizeof *linebuf,
						linesize, stdin)) > 0) {
			if (fwrite(linebuf, sizeof *linebuf,
						count, collf) != count)
				goto err;
		}
		goto out;
	}
	for (;;) {
		colljmp_p = 1;
		count = readline(stdin, &linebuf, &linesize);
		colljmp_p = 0;
		if (count < 0) {
			if (value("interactive") != NULL &&
			    value("ignoreeof") != NULL && ++eofcount < 25) {
				printf(catgets(catd, CATSET, 55,
					"Use \".\" to terminate letter\n"));
				continue;
			}
			break;
		}
		if (tflag && count == 0) {
			rewind(collf);
			if (makeheader(collf, hp) != OKAY)
				goto err;
			rewind(collf);
			tflag = 0;
			continue;
		}
		eofcount = 0;
		hadintr = 0;
		if (linebuf[0] == '.' && linebuf[1] == '\0' &&
		    value("interactive") != NULL &&
		    (value("dot") != NULL || value("ignoreeof") != NULL))
			break;
		if (linebuf[0] != escape || (value("interactive") == NULL &&
					tildeflag == 0 ||
					tildeflag < 0)) {
			if (putline(collf, linebuf, count) < 0)
				goto err;
			continue;
		}
		c = linebuf[1];
		switch (c) {
		default:
			/*
			 * On double escape, just send the single one.
			 * Otherwise, it's an error.
			 */
			if (c == escape) {
				if (putline(collf, &linebuf[1], count - 1) < 0)
					goto err;
				else
					break;
			}
			printf(catgets(catd, CATSET, 56,
					"Unknown tilde escape.\n"));
			break;
#ifdef	DEBUG_COMMANDS
		case 'C':
			/*
			 * Dump core.
			 */
			core(NULL);
			break;
#endif	/* DEBUG_COMMANDS */
		case '!':
			/*
			 * Shell escape, send the balance of the
			 * line to sh -c.
			 */
			shell(&linebuf[2]);
			break;
		case ':':
		case '_':
			/*
			 * Escape to command mode, but be nice!
			 */
			inhook = 0;
			execute(&linebuf[2], 1, count - 2);
			goto cont;
		case '.':
			/*
			 * Simulate end of file on input.
			 */
			goto out;
		case 'x':
			/*
			 * Same as 'q', but no dead.letter saving.
			 */
			hadintr++;
			collint(0);
			exit(1);
			/*NOTREACHED*/
		case 'q':
			/*
			 * Force a quit of sending mail.
			 * Act like an interrupt happened.
			 */
			hadintr++;
			collint(SIGINT);
			exit(1);
			/*NOTREACHED*/
		case 'h':
			/*
			 * Grab a bunch of headers.
			 */
			do
				grabh(hp, GTO|GSUBJECT|GCC|GBCC,
						value("bsdcompat") != NULL &&
						value("bsdorder") != NULL);
			while (hp->h_to == NULL);
			goto cont;
		case 'H':
			/*
			 * Grab extra headers.
			 */
			do
				grabh(hp, GEXTRA, 0);
			while (check_from_and_sender(hp->h_from, hp->h_sender));
			goto cont;
		case 't':
			/*
			 * Add to the To list.
			 */
			while ((hp->h_to = checkaddrs(cat(hp->h_to,
					sextract(&linebuf[2], GTO|GFULL))))
				== NULL);
			break;
		case 's':
			/*
			 * Set the Subject list.
			 */
			cp = &linebuf[2];
			while (whitechar(*cp & 0377))
				cp++;
			hp->h_subject = savestr(cp);
			break;
		case '@':
			/*
			 * Edit the attachment list.
			 */
			if (linebuf[2] != '\0')
				hp->h_attach = append_attachments(hp->h_attach,
						&linebuf[2]);
			else
				hp->h_attach = edit_attachments(hp->h_attach);
			break;
		case 'c':
			/*
			 * Add to the CC list.
			 */
			hp->h_cc = checkaddrs(cat(hp->h_cc,
				sextract(&linebuf[2], GCC|GFULL)));
			break;
		case 'b':
			/*
			 * Add stuff to blind carbon copies list.
			 */
			hp->h_bcc = checkaddrs(cat(hp->h_bcc,
				sextract(&linebuf[2], GBCC|GFULL)));
			break;
		case 'd':
			strncpy(linebuf + 2, getdeadletter(), linesize - 2);
			linebuf[linesize-1]='\0';
			/*FALLTHRU*/
		case 'r':
		case '<':
			/*
			 * Invoke a file:
			 * Search for the file name,
			 * then open it and copy the contents to collf.
			 */
			cp = &linebuf[2];
			while (whitechar(*cp & 0377))
				cp++;
			if (*cp == '\0') {
				printf(catgets(catd, CATSET, 57,
						"Interpolate what file?\n"));
				break;
			}
			if (*cp == '!') {
				insertcommand(collf, cp + 1);
				break;
			}
			cp = expand(cp);
			if (cp == NULL)
				break;
			if (is_dir(cp)) {
				printf(catgets(catd, CATSET, 58,
						"%s: Directory\n"), cp);
				break;
			}
			if ((fbuf = Fopen(cp, "r")) == NULL) {
				perror(cp);
				break;
			}
			printf(catgets(catd, CATSET, 59, "\"%s\" "), cp);
			fflush(stdout);
			if (include_file(fbuf, cp, &lc, &cc, 0) != 0)
				goto err;
			printf(catgets(catd, CATSET, 60, "%d/%d\n"), lc, cc);
			break;
		case 'i':
			/*
			 * Insert an environment variable into the file.
			 */
			cp = &linebuf[2];
			while (whitechar(*cp & 0377))
				cp++;
			if ((cp = value(cp)) == NULL || *cp == '\0')
				break;
			if (is_a_tty[0])
				putesc(cp, stdout);
			putesc(cp, collf);
			break;
		case 'a':
		case 'A':
			/*
			 * Insert the contents of a signature variable.
			 */
			if ((cp = value(c == 'a' ? "sign" : "Sign")) != NULL &&
					*cp != '\0') {
				if (is_a_tty[0])
					putesc(cp, stdout);
				putesc(cp, collf);
			}
			break;
		case 'w':
			/*
			 * Write the message on a file.
			 */
			cp = &linebuf[2];
			while (blankchar(*cp & 0377))
				cp++;
			if (*cp == '\0') {
				fprintf(stderr, catgets(catd, CATSET, 61,
						"Write what file!?\n"));
				break;
			}
			if ((cp = expand(cp)) == NULL)
				break;
			rewind(collf);
			exwrite(cp, collf, 1);
			break;
		case 'm':
		case 'M':
		case 'f':
		case 'F':
			/*
			 * Interpolate the named messages, if we
			 * are in receiving mail mode.  Does the
			 * standard list processing garbage.
			 * If ~f is given, we don't shift over.
			 */
			if (forward(linebuf + 2, collf, c) < 0)
				goto err;
			goto cont;
		case '?':
			fputs(tildehelp, stdout);
			break;
		case 'p':
			/*
			 * Print out the current state of the
			 * message without altering anything.
			 */
			print_collf(collf, hp);
			goto cont;
		case '|':
			/*
			 * Pipe message through command.
			 * Collect output as new message.
			 */
			rewind(collf);
			mespipe(&linebuf[2]);
			goto cont;
		case 'v':
		case 'e':
			/*
			 * Edit the current message.
			 * 'e' means to use EDITOR
			 * 'v' means to use VISUAL
			 */
			rewind(collf);
			mesedit(c, value("editheaders") ? hp : NULL);
			goto cont;
		}
	}
	goto out;
err:
	if (collf != NULL) {
		Fclose(collf);
		collf = NULL;
	}
out:
	if (collf != NULL) {
		if ((cp = value("MAILX_TAIL")) != NULL) {
			if (is_a_tty[0])
				putesc(cp, stdout);
			fflush(collf);
			putesc(cp, collf);
		}
		rewind(collf);
	}
	handlerpop();
	noreset--;
	sigemptyset(&nset);
	sigaddset(&nset, SIGINT);
	sigaddset(&nset, SIGHUP);
#ifndef OLDBUG
	sigprocmask(SIG_BLOCK, &nset, (sigset_t *)NULL);
#else
	sigprocmask(SIG_BLOCK, &nset, &oset);
#endif
	safe_signal(SIGINT, saveint);
	safe_signal(SIGHUP, savehup);
	safe_signal(SIGTSTP, savetstp);
	safe_signal(SIGTTOU, savettou);
	safe_signal(SIGTTIN, savettin);
	sigprocmask(SIG_SETMASK, &oset, (sigset_t *)NULL);
	return collf;
}
Esempio n. 7
0
static int
write_special (const char *fname, int lnr, const char *tag)
{
  if (!strcmp (tag, "version"))
    {
      putchar ('\"');
      fputs (hdr_version, stdout);
      putchar ('\"');
    }
  else if (!strcmp (tag, "version-number"))
    {
      fputs (hdr_version_number, stdout);
    }
  else if (!strcmp (tag, "define:gpgrt_off_t"))
    {
      if (!replacement_for_off_type)
        {
          fprintf (stderr, "%s:%d: replacement for off_t not defined\n",
                   fname, lnr);
          exit (1);
        }
      else
        {
          if (!strcmp (replacement_for_off_type, "int64_t")
              && !stdint_h_included && have_stdint_h)
            {
              fputs ("#include <stdint.h>\n\n", stdout);
              stdint_h_included = 1;
            }
          printf ("typedef %s gpgrt_off_t;\n", replacement_for_off_type);
        }
    }
  else if (!strcmp (tag, "define:gpgrt_ssize_t"))
    {
      if (have_w64_system)
        {
          if (!stdint_h_included && have_stdint_h)
            {
              fputs ("# include <stdint.h>\n", stdout);
              stdint_h_included = 1;
            }
          fputs ("typedef int64_t gpgrt_ssize_t;\n", stdout);
        }
      else if (have_w32_system)
        {
          fputs ("typedef long    gpgrt_ssize_t;\n", stdout);
        }
      else
        {
          fputs ("#include <sys/types.h>\n"
                 "typedef ssize_t gpgrt_ssize_t;\n", stdout);
        }
    }
  else if (!strcmp (tag, "api_ssize_t"))
    {
      if (have_w32_system)
        fputs ("gpgrt_ssize_t", stdout);
      else
        fputs ("ssize_t", stdout);
    }
  else if (!strcmp (tag, "include:err-sources"))
    {
      write_sources_or_codes (NULL);
      include_file (fname, lnr, "err-sources.h.in", write_sources_or_codes);
    }
  else if (!strcmp (tag, "include:err-codes"))
    {
      write_sources_or_codes (NULL);
      include_file (fname, lnr, "err-codes.h.in", write_sources_or_codes);
    }
  else if (!strcmp (tag, "include:errnos"))
    {
      include_file (fname, lnr, "errnos.in", write_errnos_in);
    }
  else if (!strcmp (tag, "include:os-add"))
    {
      if (!strcmp (host_os, "mingw32"))
        {
          include_file (fname, lnr, "w32-add.h", write_line);
        }
      else if (!strcmp (host_os, "mingw32ce"))
        {
          include_file (fname, lnr, "w32-add.h", write_line);
          include_file (fname, lnr, "w32ce-add.h", write_line);
        }
    }
  else if (!strcmp (tag, "include:lock-obj"))
    {
      if (try_include_file (fname, lnr, "./lock-obj-pub.native.h", write_line))
        include_file (fname, lnr, "syscfg/lock-obj-pub.&.h", write_line);
    }
  else
    return 0; /* Unknown tag.  */

  return 1; /* Tag processed.  */
}
   void ftw::scan_folders() {

      if( !path_exists( _impl->_path.path() ) ) {
         throw bad_ftw( "folder doesn't exist: " + _impl->_path.path() );
      }

      if( !is_directory( _impl->_path.path() ) ) {
         throw bad_ftw( "input is not a folder: " + _impl->_path.path() );
      }

      //boost::regex pattern("*"); // list all files starting with a
      boost::filesystem::path  current_dir( _impl->_path.path() ); //

      for( recursive_directory_iterator iter( current_dir ), end;
            iter != end;
            ++iter ) {

         boost::filesystem::path p = iter->path();

         if( boost::filesystem::is_directory( p ) ) {
            std::string dname = p.string();
            size_t i = index( dname, ".tmp" );

            if( i != string::npos ) {
               i = 0;
            }

            bool b = exclude_folder( dname, _impl->_folder_exclude );

            if( b == false ) {
               t_filename fn;
               fn.path( dname );
               _impl->_folders.push_back( fn );
            }
         }

         if( boost::filesystem::is_regular_file( p ) ) {
            std::string name = p.string();
            t_filename fn = t_filename( name );
            string dir = fn.path();
            size_t i = index( dir, ".tmp" );

            if( i != string::npos ) {
               i = 0;
            }

            bool bdir = exclude_folder( dir, _impl->_folder_exclude );

            if( bdir == false ) {
               bool b_include = include_file( name, _impl->_file_include );

               if( b_include == true ) {
                  _impl->_files.push_back( name );
               }
            }

            //    if (regex_match(name, pattern))
            //      std::cout << iter->path() << "\n";
         }
      }
   }
Esempio n. 9
0
/**
 * Parse the configuration file. Creating objects and loading
 * the parameter objects
 */
void File::Parse() {
  LOG_TRACE();

  if (file_.fail() || !file_.is_open())
    LOG_CODE_ERROR() << "Unable to parse the configuration file because a previous error has not been reported.\nFile: " << file_name_;

  /**
   * Iterate through our file parsing the contents
   */
  string    current_line        = "";
  while (getline(file_, current_line)) {
    ++line_number_;

    if (current_line.length() == 0)
      continue;

    // Handle comments
    HandleComments(current_line);

    if (current_line.length() == 0)
      continue;

    /**
     * Change tabs to spaces, remove any leading/trailing or multiple spaces
     * so we can be sure the input is nicely formatted
     */
    boost::replace_all(current_line, "\t", " ");
    boost::trim_all(current_line);
    LOG_FINEST() << "current_line == '" << current_line << "'";

    /**
     * Now we need to check if this line is an include line for a new
     * file.
     */
    if (current_line.length() > strlen(CONFIG_INCLUDE) + 2) {
      string lower_line = util::ToLowercase(current_line);
      if (current_line.substr(0, strlen(CONFIG_INCLUDE)) == CONFIG_INCLUDE) {
        string include_name = current_line.substr(strlen(CONFIG_INCLUDE));
        LOG_FINEST() << "Loading new configuration file via include " << include_name;

        boost::replace_all(include_name, "\"", "");
        boost::trim_all(include_name);
        File include_file(loader_);

        if (include_name.find('\\') == string::npos && file_name_.find('\\') != string::npos)
          include_name = file_name_.substr(0, file_name_.find_last_of('\\') + 1) + include_name;
        if (include_name.find('/') == string::npos && file_name_.find('/') != string::npos)
          include_name = file_name_.substr(0, file_name_.find_last_of('/') + 1) + include_name;

        if (!include_file.OpenFile(include_name))
          LOG_FATAL() << "At line: " << line_number_ << " of " << file_name_
              << ": Include file '" << include_name << "' could not be opened. Does this file exist?";

        include_file.Parse();
        continue;
      }
    }


    /**
     * At this point everything is standard. We have a simple line of text that we now need to parse. All
     * comments etc have been removed and we've gone through any include_file directives
     */
    FileLine current_file_line;
    current_file_line.file_name_    = file_name_;
    current_file_line.line_number_  = line_number_;
    current_file_line.line_         = current_line;

    loader_.AddFileLine(current_file_line);
  } // while(get_line())
}
Esempio n. 10
0
/* include a file or directory */
void include_file(YYLTYPE *yylloc, const char *name) {
  struct stat st;
  struct dirent **namelist;
  char *fn;
  int n;

  struct sourceposition *pos;

  pos = make_sourcepos(yylloc);

  if (stat(name, &st)) {
    if (errno == ENOENT &&
        (index(name, '*') != NULL || index(name, '?') != NULL ||
         index(name, '[') != NULL)) {
      /* Globbing fiesta! */
      glob_t glob_buf;
      if (glob(name, 0, NULL, &glob_buf) != 0) {
        filter_error(pos, "failed to glob \"%s\": %s", name, strerror(errno));
      } else {
        /* We go through the list of files backwards, because
         * step_into_include_file() creates a stack of all the
         * files processed and then works on them in a LIFO
         * fashion -- which would make all of our rules files
         * go backwards.  Since I can't wrap my head around
         * why that is, exactly, I'm hacking it up with
         * this instead.  Fixination appreciated.
         */
        for (n = glob_buf.gl_pathc - 1; n >= 0; n--) {
          if (stat(glob_buf.gl_pathv[n], &st)) {
            filter_error(pos, "stat failed on globbed \"%s\": %s",
                         glob_buf.gl_pathv[n], strerror(errno));
          } else if (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode)) {
            if (sourcefile_push(pos, glob_buf.gl_pathv[n])) {
              filtergen_in = current_srcfile->f;
              filtergen_lineno = current_srcfile->lineno;
              // yycolumn = current_srcfile->column;
              if (!filtergen_in) {
                filter_error(pos, "failed to open %s", glob_buf.gl_pathv[n]);
              } else {
                filtergen_push_buffer_state(
                    filtergen__create_buffer(filtergen_in, YY_BUF_SIZE));
              }
            }
          }
        }
      }

      globfree(&glob_buf);
    } else {
      filter_error(pos, "stat failed on \"%s\": %s", name, strerror(errno));
    }
  } else {
    if (S_ISDIR(st.st_mode)) {
      char *b = strdup(name);
      char *base = basename(b);

      if (strcmp("/", base) == 0) {
        filter_error(pos, "cannot include / path; skipping");
        free(b);
        return;
      }
      free(b);

      if ((n = scandir(name, &namelist, NULL, alphasort)) < 0) {
        filter_error(pos, "scandir failed on \"%s\": %s", name,
                     strerror(errno));
      } else {
        while (n--) {
          /* FIXME: assumes d_name */
          if (namelist[n]->d_name[0] == '.') {
            free(namelist[n]);
            continue;
          }
          if (asprintf(&fn, "%s/%s", name, namelist[n]->d_name) < 0) {
            filter_error(
                NULL, "internal error: asprintf failed constructing pathname "
                      "for included file \"%s\"",
                namelist[n]->d_name);
            free(fn);
          } else {
            include_file(yylloc, fn);
            free(fn);
          }
          free(namelist[n]);
        }
        free(namelist);
      }
    } else {
      if (sourcefile_push(pos, name)) {
        filtergen_in = current_srcfile->f;
        filtergen_lineno = current_srcfile->lineno;
        //        yycolumn = current_srcfile->column;
        if (!filtergen_in) {
          filter_error(pos, "failed to open %s", name);
        } else {
          filtergen_push_buffer_state(
              filtergen__create_buffer(filtergen_in, YY_BUF_SIZE));
        }
      }
    }
  }
}
Esempio n. 11
0
void token_next()
{
    static int  i, len;
    static char buffer[1024];
    char * buffer_ptr = buffer;

    if ( !source_ptr )
    {
        token.type = NOTOKEN;
        return;
    }

    if ( use_saved )
    {
        token        = token_saved;
        line_count   = token.line;
        current_file = token.file;
        use_saved    = 0;
        return;
    }
    token.line = line_count;
    token.file = current_file;
    token_prev = token;

    while ( 1 )
    {
        SKIP_SPACES;

        if ( !disable_prepro && *source_ptr == '#' )
        {
            int line;
            const char * old_source_ptr;

            identifiers_as_strings = 0;

            /* Comandos de preprocesador */
            source_ptr++;

            line = line_count;

            SKIP_SPACES_UNTIL_LF_AND_COUNT_LINES;

            if ( *source_ptr == '\n' )
            {
                token.code = identifier_search_or_add( "#" );
                token.type = IDENTIFIER;
                line_count = line;
                compile_error( MSG_IDENTIFIER_EXP );
            }

            old_source_ptr = source_ptr;

            if ( ISWORDFIRST( *source_ptr ) )
            {
                GET_NEXT_TOKEN_IN_TMPBUFFER;

                /* #include "file.h" */

                if ( token.code == identifier_include && !use_saved )
                {
                    include_file( 1 );
                    return;
                }

                source_ptr = old_source_ptr;
            }

            preprocessor();

            buffer_ptr = buffer;
            *buffer_ptr = '\0';
            continue;
        }

        if ( !*source_ptr )
        {
            /* Casos de bloques manuales */
            if ( current_file == -1 )
            {
                token_endfile();
                token.type = NOTOKEN;
                return;
            }

            while ( !*source_ptr )
            {
                if ( sources == 0 )
                {
                    token.type = NOTOKEN;
                    return;
                }

                token_endfile();

                if ( !source_ptr )
                {
                    token.type = NOTOKEN;
                    return;
                }
            }
            continue;
        }

        /* Ignora comentarios */

        SKIP_COMMENTS;
        if ( !*source_ptr )
        {
            token.type = NOTOKEN;
            return;
        }

        /* Cadenas */

        if ( *source_ptr == '"' || *source_ptr == '\'' )
        {
            token.type = STRING;
            token.code = string_compile( &source_ptr );
            token.line = line_count;
            token.file = current_file;
            return;
        }

        /* Operadores de más de un caracter */

        len = 0;

        if ( *source_ptr == '<' )
        {
            if ( source_ptr[1] == '<' )
            {
                if ( source_ptr[2] == '=' ) len = 3;
                else                      len = 2;
            }
            else if ( source_ptr[1] == '>' )    len = 2;
            else if ( source_ptr[1] == '=' )    len = 2;
            else                              len = 1;
        }
        else if ( *source_ptr == '>' )
        {
            if ( source_ptr[1] == '>' )
            {
                if ( source_ptr[2] == '=' ) len = 3;
                else                      len = 2;
            }
            else if ( source_ptr[1] == '=' )    len = 2;
            else if ( source_ptr[1] == '>' )    len = 2;
            else                              len = 1;
        }
        else if ( *source_ptr == '|' )
        {
            if ( source_ptr[1] == '|' )
            {
                if ( source_ptr[2] == '=' ) len = 3;
                else                      len = 2;
            }
            else if ( source_ptr[1] == '=' )    len = 2;
            else                              len = 1;
        }
        else if ( *source_ptr == '=' )
        {
            if ( source_ptr[1] == '=' )     len = 2;
            else if ( source_ptr[1] == '>' )    len = 2;
            else if ( source_ptr[1] == '<' )    len = 2;
            else                              len = 1;
        }
        else if ( *source_ptr == '.' )
        {
            if ( source_ptr[1] == '.' )     len = 2;
            else                          len = 1;
        }
        else if ( strchr( "!&^%*+-/", *source_ptr ) )
        {
            if ( source_ptr[1] == '=' )     len = 2;
            else if ( strchr( "+-&^", *source_ptr ) && source_ptr[1] == *source_ptr ) len = 2;
            else                          len = 1;
        }

        if ( len )
        {
            strncpy( buffer, source_ptr, len );
            buffer[len] = 0;
            source_ptr += len;
            token.code = identifier_search_or_add( buffer );
            token.type = IDENTIFIER;
            token.line = line_count;
            token.file = current_file;
            return;
        }

        /* Numbers */

        if ( ISNUM( *source_ptr ) )
        {
            const char * ptr;
            double num = 0, dec;
            int base = 10;

            /* Hex/Bin/Octal numbers with the h/b/o sufix */
            ptr = source_ptr;
            while ( ISNUM( *ptr ) || ( *ptr >= 'a' && *ptr <= 'f' ) || ( *ptr >= 'A' && *ptr <= 'F' ) ) ptr++;

            if ( *ptr != 'h' && *ptr != 'H' && *ptr != 'o' && *ptr != 'O' && ( ptr[-1] == 'b' || ptr[-1] == 'B' ) ) ptr--;

            if ( *ptr == 'b' || *ptr == 'B' )
                base = 2;
            if ( *ptr == 'h' || *ptr == 'H' )
                base = 16;
            if ( *ptr == 'o' || *ptr == 'O' )
                base = 8;

            token.code = 0 ; /* for ints values */

            /* Calculate the number value */

            while ( ISNUM( *source_ptr ) || ( base > 10 && ISALNUM( *source_ptr ) ) )
            {
                if ( base == 2 && *source_ptr != '0' && *source_ptr != '1' ) break;
                if ( base == 8 && ( *source_ptr < '0' || *source_ptr > '7' ) ) break;
                if ( base == 10 && !ISNUM( *source_ptr ) ) break;
                if ( base == 16 && !ISNUM( *source_ptr ) && ( TOUPPER( *source_ptr ) < 'A' || TOUPPER( *source_ptr ) > 'F' ) ) break;

                if ( ISNUM( *source_ptr ) )
                {
                    num = num * base + ( *source_ptr - '0' );
                    token.code = token.code * base + ( *source_ptr - '0' );
                    source_ptr++;
                    continue;
                }
                if ( *source_ptr >= 'a' && *source_ptr <= 'f' && base > 10 )
                {
                    num = num * base + ( *source_ptr - 'a' + 10 );
                    token.code = token.code * base + ( *source_ptr - 'a' + 10 );
                    source_ptr++;
                    continue;
                }
                if ( *source_ptr >= 'A' && *source_ptr <= 'F' && base > 10 )
                {
                    num = num * base + ( *source_ptr - 'A' + 10 );
                    token.code = token.code * base + ( *source_ptr - 'A' + 10 );
                    source_ptr++;
                    continue;
                }
            }
            token.type = NUMBER;
            token.value = ( float )num;

            /* We have the integer part now - convert to int/float */

            if ( *source_ptr == '.' && base == 10 )
            {
                source_ptr++;
                if ( !ISNUM( *source_ptr ) )
                    source_ptr--;
                else
                {
                    dec = 1.0 / ( double )base;
                    while ( ISNUM( *source_ptr ) || ( base > 100 && ISALNUM( *source_ptr ) ) )
                    {
                        if ( ISNUM( *source_ptr ) ) num = num + dec * ( *source_ptr++ - '0' );
                        if ( *source_ptr >= 'a' && *source_ptr <= 'f' && base > 10 ) num = num + dec * ( *source_ptr++ - 'a' + 10 );
                        if ( *source_ptr >= 'A' && *source_ptr <= 'F' && base > 10 ) num = num + dec * ( *source_ptr++ - 'A' + 10 );
                        dec /= ( double )base;
                    }
                    token.type  = FLOAT;
                    token.value = ( float )num;
                }
            }

            /* Skip the base sufix */

            if ( base == 16 && ( *source_ptr == 'h' || *source_ptr == 'H' ) ) source_ptr++;
            if ( base == 8  && ( *source_ptr == 'o' || *source_ptr == 'O' ) ) source_ptr++;
            if ( base == 2  && ( *source_ptr == 'b' || *source_ptr == 'B' ) ) source_ptr++;

            token.line = line_count;
            token.file = current_file;
            return;
        }

        /* Identificadores */
        if ( ISWORDFIRST( *source_ptr ) )
        {
            int maybe_label = source_ptr[-1] == '\n';
            GET_NEXT_TOKEN_IN_TMPBUFFER;

            token.line = line_count;
            token.file = current_file;

            if ( maybe_label && *source_ptr == ':' )
            {
                source_ptr++;
                token.code = identifier_search_or_add( buffer );
                token.type = LABEL;
                return;
            }

            /* Search for #define constant inclusion at this point */

            if ( !disable_expand_defines )
            {
                if ( !strcmp( buffer, "__FILE__" ) )
                {
                    token.type = STRING;
                    token.code = string_new(( current_file != -1 && files[current_file] && *files[current_file] ) ? files[current_file] : "N/A" );
                    token.line = line_count;
                    token.file = current_file;
                    return;
                }

                if ( !strcmp( buffer, "__LINE__" ) )
                {
                    token.type = NUMBER;
                    token.code = ( int )line_count;
                    token.value = ( float )line_count;
                    token.line = line_count;
                    token.file = current_file;
                    return;
                }

                for ( i = 0; i < defines_count; i++ )
                {
                    if ( defines[i].code == token.code )
                    {
                        preprocessor_expand( &defines[i] );
                        token_next();
                        token.line = line_count;
                        token.file = current_file;
                        return;
                    }
                }
            }

            /* In a #if, all identifiers are strings */

            if ( identifiers_as_strings )
            {
                token.type = STRING;
                token.code = string_new( buffer );
                token.line = line_count;
                token.file = current_file;
                return;
            }

            /* Include */

            if ( !disable_prepro && token.code == identifier_include && !use_saved )
            {
                include_file( 0 );
                return;
            }
            return;
        }

        /* 1-char operator or invalid symbol */

        if ( !*source_ptr ) break;

        if ( *source_ptr > 0 && *source_ptr < 32 ) compile_error( MSG_INVALID_CHAR );

        *buffer_ptr++ = *source_ptr++;
        *buffer_ptr = 0;

        token.code = identifier_search_or_add( buffer );
        token.type = IDENTIFIER;
        token.line = line_count;
        token.file = current_file;

        return;
    }

    token.type = NOTOKEN;
    return;        /* End-of-file */
}
Esempio n. 12
0
void actual_assembly_parser(std::string const & file_name, std::string const & path, std::vector<std::string> const & include_directories)
{
	std::string input;
	bool success = nil::read_file(file_name, input);
	if(success == false)
	{
		throw std::runtime_error("Failed to open file \"" + file_name + "\"");
	}

	std::string::iterator
		begin = input.begin(),
		end = input.end();

	typedef std::map< std::string, std::vector<lexeme> > macro_map;

	macro_map macros;
	std::vector<lexeme> lexemes;

	unsigned int line = 1;
	while(true)
	{
		lexeme current_lexeme;
		bool not_done_yet = assembly_lexer(file_name, line, begin, end, current_lexeme);
		if(not_done_yet == true)
		{
			if(current_lexeme.type == lexeme_name)
			{
				std::vector<lexeme> line_lexemes;

				std::string const & name = current_lexeme.data;
				if(name == "include")
				{
					read_until_eol(file_name, line, begin, end, line_lexemes);
					if(line_lexemes.size() != 1)
					{
						parser_exception(file_name, line, "invalid argument count in include statement");
					}
					else if(line_lexemes[0].type != lexeme_string)
					{
						parser_exception(file_name, line, "invalid argument type in include statement");
					}
					std::string include_input;
					std::string const & include_file_name = line_lexemes[0].data;
					bool success = include_file(include_file_name, path, include_directories, include_input);
					if(success == false)
					{
						parser_exception(file_name, line, "failed to include file \"" + include_file_name + "\"");
					}
					input = include_input + std::string(begin, end);
					begin = input.begin();
					end = input.end();
				}
				else if(name == "define")
				{
					bool not_done_yet = read_until_eol(file_name, line, begin, end, line_lexemes);
					if(not_done_yet == false)
					{
						return;
					}
					else if(line_lexemes.size() < 1)
					{
						parser_exception(file_name, line, "invalid argument count in define statement");
					}
					else if(line_lexemes[0].type != lexeme_name)
					{
						parser_exception(file_name, line, "expected a name in define statement");
					}
					std::string define_name = line_lexemes[0].data;
					line_lexemes.erase(line_lexemes.begin());
					for(std::vector<lexeme>::iterator i = line_lexemes.begin(), end = line_lexemes.end(); i != end; ++i)
					{
						if(i->type == lexeme_name)
						{
							macro_map::iterator
								macros_end = macros.end(),
								search = macros.find(i->data);
							if(search != macros_end)
							{
								std::size_t backup = i - line_lexemes.begin();
								std::vector<lexeme> & macro_lexemes = search->second;
								line_lexemes.insert(i + 1, macro_lexemes.begin(), macro_lexemes.end());
								line_lexemes.erase(line_lexemes.begin() + backup);
								i = line_lexemes.begin() + backup + macro_lexemes.size();
								end = line_lexemes.end();
							}
						}
					}
					macros[define_name] = line_lexemes;
				}
				else
				{
					macro_map::iterator
						macros_end = macros.end(),
						search = macros.find(name);
					if(search == macros_end)
					{
						lexemes.push_back(current_lexeme);
					}
					else
					{
						std::vector<lexeme> & macro_lexemes = search->second;
						lexemes.insert(lexemes.end(), macro_lexemes.begin(), macro_lexemes.end());
					}
				}
			}
			else
			{
				lexemes.push_back(current_lexeme);
			}
		}
		else
		{
			break;
		}
	}

	unsigned int
		code_boundary = 0,
		data_boundary = 0;

	for(std::vector<lexeme>::iterator i = lexemes.begin(), end = lexemes.end(); i != end; ++i)
	{
		switch(i->type)
		{
			case lexeme_name:
			{
				std::vector<lexeme>::iterator line_begin = i;
				for(
					std::vector<lexeme>::iterator i = lexemes.begin(), end = lexemes.end();
					(i != end)
						&&
					(i->type != lexeme_newline);
					++i
				);
				std::size_t line_length = i - line_begin;
				std::string const & name = line_begin->data;
				if(name == "align")
				{
					if(line_length != 3)
					{
						parser_exception(file_name, line_length->line, "Illegal argument count for align statement");
					}
				}
				++i;
				break;
			}

			case lexeme_number:
			case lexeme_string:
			case lexeme_operator:
			{
				parser_exception(file_name, i->line, "Illegal lexeme type at the beginning of a line");
			}
		}
	}
}
Esempio n. 13
0
/*
** cg_read_conf()
** Read the configuration file.
*/
yerr_t cg_read_conf(cg_t *carta, const char *input, ybool_t initial)
{
    ydom_t *dom;
    ydom_node_t *root_node;
    yvect_t array;
    int i;
    char *pt = NULL, *pt2 = NULL;

    if (!(dom = ydom_new()))
    {
        YLOG_ADD(YLOG_ERR, "Memory error");
        return (YENOMEM);
    }
    if (ydom_read_file(dom, input) != YENOERR)
    {
        YLOG_ADD(YLOG_ERR, "Problem with file '%s'", input);
        ydom_del(dom);
        return (YEINVAL);
    }
    if (!(array = ydom_xpath(dom, "/pandocreon:carta-genius")) ||
            !yv_len(array) || !array[0])
    {
        YLOG_ADD(YLOG_ERR, "No configuration");
        yv_del(&array, NULL, NULL);
        ydom_del(dom);
        return (YEINVAL);
    }
    root_node = array[0];
    yv_del(&array, NULL, NULL);
    yv_add(&carta->xml_doms, dom);

    /* get document info */
    if ((array = ydom_node_xpath(root_node, "info")) &&
            yv_len(array) && array[0])
    {
        carta->author = ydom_node_get_attr_value(array[0], "author");
        carta->title = ydom_node_get_attr_value(array[0], "title");
        carta->subject = ydom_node_get_attr_value(array[0], "subject");
        carta->keywords = ydom_node_get_attr_value(array[0], "keywords");
        carta->copyright = ydom_node_get_attr_value(array[0], "copyright");
        carta->version = ydom_node_get_attr_value(array[0], "version");
        carta->language = ydom_node_get_attr_value(array[0], "lang");
        carta->note = ydom_node_get_attr_value(array[0], "note");
    }
    yv_del(&array, NULL, NULL);

    /* get PDF version */
    if ((array = ydom_node_xpath(root_node, "pdf")) &&
            yv_len(array) && array[0])
    {
        char *passwd1 = NULL, *passwd2 = NULL;
        pt = ydom_node_get_attr_value(array[0], "version");
        passwd1 = ydom_node_get_attr_value(array[0], "master-password");
        passwd2 = ydom_node_get_attr_value(array[0], "user-password");
        if (!passwd1 || !passwd2 || !strcmp(passwd1, passwd2))
        {
            free0(passwd1);
            free0(passwd2);
        }
        carta->master_password = passwd1;
        carta->user_password = passwd2;
    }
    if (pt && !strcmp(pt, "1.3"))
        carta->pdf_version = PDF_13;
    else if (pt && !strcmp(pt, "1.5"))
        carta->pdf_version = PDF_15;
    else
        carta->pdf_version = PDF_14;
    free0(pt);
    yv_del(&array, NULL, NULL);

    /* get general configuration */
    if (initial)
    {
        /* get default unit */
        if ((array = ydom_node_xpath(root_node, "unit")) &&
                yv_len(array) && array[0] &&
                (pt = ydom_node_get_attr_value(array[0], "base")))
        {
            if (!strcasecmp(pt, "mm") || !strcasecmp(pt, "millimeter"))
                carta->default_unit = YUNIT_MM;
            else if (!strcasecmp(pt, "cm") || !strcasecmp(pt, "centimeter"))
                carta->default_unit = YUNIT_CM;
            else if (!strcasecmp(pt, "in") || !strcasecmp(pt, "inch"))
                carta->default_unit = YUNIT_IN;
            else if (!strcasecmp(pt, "pt") || !strcasecmp(pt, "point"))
                carta->default_unit = YUNIT_PT;
            else
            {
                YLOG_ADD(YLOG_ERR, "Bad default unit [line %d]",
                         ((ydom_node_t*)array[0])->line_nbr);
                free0(pt);
                yv_del(&array, NULL, NULL);
                ydom_del(dom);
                return (YEINVAL);
            }
            free0(pt);
        }
        else
        {
            YLOG_ADD(YLOG_INFO, "No default unit. Set to mm.");
            carta->default_unit = YUNIT_MM;
        }
        yv_del(&array, NULL, NULL);

        /* get cards' back configuration */
        if ((array = ydom_node_xpath(root_node, "back")) &&
                yv_len(array) && array[0])
        {
            if ((pt = ydom_node_get_attr_value(array[0], "side")))
            {
                if (!strcasecmp(pt, "width"))
                    carta->do_back = BACK_WIDTH;
                else if (!strcasecmp(pt, "height"))
                    carta->do_back = BACK_HEIGHT;
                free0(pt);
            }
            else
                carta->do_back = BACK_NO;
            if ((pt = ydom_node_get_attr_value(array[0], "reverse")) &&
                    (!strcasecmp(pt, "yes") || !strcasecmp(pt, "true")))
                carta->reverse = YTRUE;
            free0(pt);
        }
        else
            carta->do_back = BACK_NO;
        yv_del(&array, NULL, NULL);
    }

    /* get templates */
    if ((array = ydom_node_xpath(root_node, "templates/template")) &&
            yv_len(array))
    {
        int i;

        for (i = 0; i < yv_len(array); ++i)
            yv_add(&carta->templates, array[i]);
    }
    yv_del(&array, NULL, NULL);

    /* get init variables */
    if ((array = ydom_node_xpath(root_node, "variables/var")) &&
            yv_len(array))
    {
        int i;

        for (i = 0; i < yv_len(array); ++i)
            yv_add(&carta->variables, array[i]);
    }
    yv_del(&array, NULL, NULL);

    /* get default font */
    if ((array = ydom_node_xpath(root_node, "fonts")) &&
            yv_len(array) && array[0])
    {
        char *default_font;

        if ((default_font = ydom_node_get_attr_value(array[0], "default")))
        {
            free0(carta->default_font);
            carta->default_font = default_font;
        }
    }
    yv_del(&array, NULL, NULL);

    /* get fonts */
    if ((array = ydom_node_xpath(root_node, "fonts/*")) &&
            yv_len(array) && array[0])
    {
        int i;

        for (i = 0; i < yv_len(array); ++i)
        {
            char *tag_name = ydom_node_get_name(array[i]);
            if (tag_name && !strcmp(tag_name, "font"))
                import_font(carta, array[i]);
            else if (tag_name && !strcmp(tag_name, "path"))
            {
                char *dir = ydom_node_get_attr_value(array[i], "dir");
                if (dir && strlen(dir))
                    add_font_paths(carta, dir);
                else
                    YLOG_ADD(YLOG_WARN, "Path without 'dir' argument [line %d].",
                             ((ydom_node_t*)array[i])->line_nbr);
                free0(dir);
            }
            free0(tag_name);
        }
    }
    yv_del(&array, NULL, NULL);

    /* get images */
    if ((array = ydom_node_xpath(root_node, "images/*")) &&
            yv_len(array) && array[0])
    {
        int i;

        for (i = 0; i < yv_len(array); ++i)
        {
            char *tag_name = ydom_node_get_name(array[i]);
            if (tag_name && !strcmp(tag_name, "image"))
                import_image(carta, array[i], YFALSE);
            else if (tag_name && !strcmp(tag_name, "mask"))
                import_image(carta, array[i], YTRUE);
            else if (tag_name && !strcmp(tag_name, "path"))
            {
                /* add a directory for path searching */
                char *dir = ydom_node_get_attr_value(array[i], "dir");
                if (dir && strlen(dir))
                    add_img_paths(carta, dir);
                else
                    YLOG_ADD(YLOG_WARN, "Path without 'dir' argument [line %d].",
                             ((ydom_node_t*)array[i])->line_nbr);
                free0(dir);
            }
            free0(tag_name);
        }
    }
    yv_del(&array, NULL, NULL);

    /* get all decks */
    array = ydom_node_xpath(root_node, "deck");
    for (i = 0; i < yv_len(array); ++i)
    {
        cg_deck_t *deck;
        ydom_node_t *deck_node = array[i];
        yvect_t array2;

        deck = malloc0(sizeof(cg_deck_t));
        deck->line_nbr = deck_node->line_nbr;
        /* get paper size */
        if ((array2 = ydom_node_xpath(deck_node, "paper")) &&
                yv_len(array2) && array2[0])
        {
            cg_expr_var_t e_w = {0}, e_h = {0};
            yvalue_t width, height, margin_w, margin_h;

            /* get width and height */
            if ((pt = ydom_node_get_attr_value(array2[0], "type")))
            {
                cg_paper_t paper_type = cg_get_paper(pt);
                width = cg_get_paper_width(paper_type);
                height = cg_get_paper_height(paper_type);
                if ((pt2 = ydom_node_get_attr_value(array2[0], "landscape")) &&
                        (!strcasecmp(pt2, "yes") || !strcasecmp(pt2, "true")))
                {
                    yvalue_t tmp_val = width;
                    width = height;
                    height = tmp_val;
                }
            }
            else if ((pt = ydom_node_get_attr_value(array2[0], "width")) &&
                     cg_expr(carta, pt, &e_w, carta->default_unit) == YENOERR &&
                     e_w.type == CG_EXPR_VALUE &&
                     (pt2 = ydom_node_get_attr_value(array2[0], "height")) &&
                     cg_expr(carta, pt2, &e_h, carta->default_unit) == YENOERR &&
                     e_h.type == CG_EXPR_VALUE)
            {
                width = e_w.value.value;
                height = e_h.value.value;
            }
            else
            {
                YLOG_ADD(YLOG_WARN, "No valid paper size. Set to a4.");
                width = cg_get_paper_width(A4);
                height = cg_get_paper_height(A4);
            }
            free0(pt);
            free0(pt2);
            free_var(&e_w, &e_w);
            free_var(&e_h, &e_h);
            /* get margin */
            if ((pt = ydom_node_get_attr_value(array2[0], "margin")))
                margin_w = margin_h = yvalue_read(pt, carta->default_unit);
            else
                margin_w = margin_h = yvalue_read(DEFAULT_MARGIN, carta->default_unit);
            free0(pt);
            if ((pt = ydom_node_get_attr_value(array2[0], "margin-width")) &&
                    cg_expr(carta, pt, &e_w, carta->default_unit) == YENOERR &&
                    e_w.type == CG_EXPR_VALUE)
                margin_w = e_w.value.value;
            free0(pt);
            if ((pt = ydom_node_get_attr_value(array2[0], "margin-height")) &&
                    cg_expr(carta, pt, &e_h, carta->default_unit) == YENOERR &&
                    e_h.type == CG_EXPR_VALUE)
                margin_h = e_h.value.value;
            free0(pt);
            free_var(&e_w, &e_w);
            free_var(&e_h, &e_h);
            deck->paper_width = width;
            deck->paper_height = height;
            deck->paper_margin_w = margin_w;
            deck->paper_margin_h = margin_h;
        }
        else
        {
            YLOG_ADD(YLOG_INFO, "No paper size, set to default (A4).");
            deck->paper_width = cg_get_paper_width(A4);
            deck->paper_height = cg_get_paper_height(A4);
            deck->paper_margin_w = deck->paper_margin_h =
                                       yvalue_read(DEFAULT_MARGIN, carta->default_unit);
        }
        yv_del(&array2, NULL, NULL);

        /* get hidden ditch config */
        if ((array2 = ydom_node_xpath(deck_node, "hidden-ditch")) &&
                yv_len(array2) && array2[0])
        {
            /* get margin */
            deck->ditch_even = ydom_node_get_attr_value(array2[0], "even");
            deck->ditch_odd = ydom_node_get_attr_value(array2[0], "odd");
        }
        yv_del(&array2, NULL, NULL);

        /* get card size */
        if ((array2 = ydom_node_xpath(deck_node, "cardsize")) &&
                yv_len(array2) && array2[0])
        {
            yvalue_t width, height, space_w, space_h;

            if ((pt = ydom_node_get_attr_value(array2[0], "type")))
            {
                cg_paper_t paper_type = cg_get_paper(pt);
                width = cg_get_paper_width(paper_type);
                height = cg_get_paper_height(paper_type);
                if ((pt2 = ydom_node_get_attr_value(array2[0], "landscape")) &&
                        (!strcasecmp(pt2, "yes") || !strcasecmp(pt2, "true")))
                {
                    yvalue_t tmp_val = width;
                    width = height;
                    height = tmp_val;
                }
            }
            else if ((pt = ydom_node_get_attr_value(array2[0], "width")) &&
                     (pt2 = ydom_node_get_attr_value(array2[0], "height")))
            {
                width = yvalue_read(pt, carta->default_unit);
                height = yvalue_read(pt2, carta->default_unit);
            }
            else
            {
                YLOG_ADD(YLOG_WARN, "No valid card size. Set to a6.");
                width = cg_get_paper_width(A6);
                height = cg_get_paper_height(A6);
            }
            free0(pt);
            free0(pt2);
            deck->card_width = width;
            deck->card_height = height;
            if ((pt = ydom_node_get_attr_value(array2[0], "space")))
                space_w = space_h = yvalue_read(pt, carta->default_unit);
            else if ((pt = ydom_node_get_attr_value(array2[0], "space-width")) &&
                     (pt2 = ydom_node_get_attr_value(array2[0], "space-height")))
            {
                space_w = yvalue_read(pt, carta->default_unit);
                space_h = yvalue_read(pt2, carta->default_unit);
            }
            else
            {
                space_w.unit = space_h.unit = YUNIT_PT;
                space_w.value = space_h.value = 0.0;
            }
            deck->space_width = space_w;
            deck->space_height = space_h;
            free0(pt);
            free0(pt2);
        }
        else
        {
            YLOG_ADD(YLOG_INFO, "No card size. Set to a6.");
            deck->card_width = cg_get_paper_width(A6);
            deck->card_height = cg_get_paper_height(A6);
        }
        yv_del(&array2, NULL, NULL);

        /* get cards */
        deck->cards = ydom_node_xpath(deck_node, "card");

        yv_add(&carta->decks, deck);
    }

    /* get included files */
    if ((array = ydom_node_xpath(root_node, "includes/*")) &&
            yv_len(array) && array[0])
    {
        int i;
        for (i = 0; i < yv_len(array); ++i)
        {
            char *tag_name = ydom_node_get_name(array[i]);
            if (tag_name && !strcmp(tag_name, "include"))
            {
                /* include a file */
                char *file = ydom_node_get_attr_value(array[i], "file");
                if (file && strlen(file))
                    include_file(carta, file);
                else
                    YLOG_ADD(YLOG_WARN, "Include without 'file' argument [line %d].",
                             ((ydom_node_t*)array[i])->line_nbr);
                free0(file);
            }
            else if (tag_name && !strcmp(tag_name, "path"))
            {
                /* add an include dir */
                char *dir = ydom_node_get_attr_value(array[i], "dir");
                if (dir && strlen(dir))
                    add_inc_paths(carta, dir);
                else
                    YLOG_ADD(YLOG_WARN, "Path without 'dir' argument [line %d].",
                             ((ydom_node_t*)array[i])->line_nbr);
                free0(dir);
            }
            free0(tag_name);
        }
    }
    yv_del(&array, NULL, NULL);

    return (YENOERR);
}
/*
* Routine: 
* Purpose: 
* Algorithm:
* Data Structures:
*
* Params:
* Returns:
* Called By: 
* Calls: 
* Assumptions:
* Side Effects:
* TODO: None
*/
void
parseTemplate(char *szFileName, int nIndex)
{
	int nWarning,
		nError;
	char szPath[1024];
			
		pCurrentQuery = (template_t *)malloc(sizeof(struct TEMPLATE_T));
		MALLOC_CHECK(pCurrentQuery);
		if (!pCurrentQuery)
			ReportErrorNoLine(QERR_NO_MEMORY, "parseQueries()", 1);
		memset(pCurrentQuery, 0, sizeof(struct TEMPLATE_T));
		pCurrentQuery->SegmentList = makeList(L_FL_TAIL, NULL);
		pCurrentQuery->SubstitutionList = makeList(L_FL_SORT, compareSubstitution);	
		pCurrentQuery->DistributionList = makeList(L_FL_SORT, di_compare);

		/*
		 * each query template is parsed as though:
		 *	it had explicitly included the dialect template
		 *	it began the query with a [_begin] substitution
		 *	it ended the query with an [_end] substitution
		 */
		pCurrentFile = NULL;
      if (is_set("DIRECTORY"))
		   sprintf(szPath, "%s/%s", get_str("DIRECTORY"),szFileName);
      else
         strcpy(szPath, szFileName);
		if (include_file(szPath, pCurrentQuery) < 0)
			ReportErrorNoLine(QERR_NO_FILE, szPath, 1);
		sprintf(szPath, "%s/%s.tpl", get_str("DIRECTORY"), get_str("DIALECT"));
		if (include_file(szPath, pCurrentQuery) < 0)
			ReportErrorNoLine(QERR_NO_FILE, szPath, 1);
	
		/* parse the template file */
		yyparse();

		/* 
		 * add in query start substitution, now that it has been defined 
		 */
		pCurrentQuery->SegmentList->nFlags &= ~L_FL_TAIL;
		pCurrentQuery->SegmentList->nFlags |= L_FL_HEAD;
		AddQuerySegment(pCurrentQuery, "\n");
		AddQuerySegment(pCurrentQuery, "");
		((segment_t *)pCurrentQuery->SegmentList->head->pData)->pSubstitution = findSubstitution(pCurrentQuery, "_BEGIN", 0);
		pCurrentQuery->SegmentList->nFlags &= ~L_FL_HEAD;
		pCurrentQuery->SegmentList->nFlags |= L_FL_TAIL;
		
		/* check for any parsing errors */
		GetErrorCounts(&nError, &nWarning);
		if (nError)
		{
			printf("%d Errors encountered parsing %s\n", 
				nError, szFileName);
			exit(1);
		}
		if (nWarning)
		{
			printf("WARRNING: %d warnings encountered parsing %s\nWARNING: Query output may not be correct!\n", 
				nWarning, szFileName);
		}
		
		addList(TemplateList, pCurrentQuery);
		pCurrentQuery->index = nIndex;
		pCurrentQuery->name = strdup(szFileName);

		return;
}
Esempio n. 15
0
ShaderPtr
Shader::from_file(GLenum type, std::string const& filename,
                  std::vector<std::string> const& defines)
{
  std::ifstream in(filename);
  if (!in)
  {
    throw std::runtime_error((boost::format("%s: failed to open file") % filename).str());
  }
  else
  {
    std::vector<std::string> sources;

    // add version declaration
#ifdef HAVE_OPENGLES2
    sources.emplace_back("#version 100\n");
#else
    sources.emplace_back("#version 330 core\n");
#endif

    { // add custom defines
      std::ostringstream os;
      for(auto const& def : defines)
      {
        auto equal_pos = def.find('=');
        if (equal_pos == std::string::npos)
        {
          os << "#define " << def << '\n';
        }
        else
        {
          os << "#define " << def.substr(0, equal_pos) << ' ' << def.substr(equal_pos+1) << '\n';
        }
      }
      sources.emplace_back(os.str());
    }

    { // add the actual source file
      std::regex include_rx("^#\\s*include\\s+\"([^\"]*)\".*$");
      int line_count = 0;
      std::ostringstream os;
      std::string line;
      while(std::getline(in, line))
      {
        std::smatch rx_results;
        if (std::regex_match(line, rx_results, include_rx))
        {
          boost::filesystem::path include_filename(rx_results[1]);
          if (include_filename.is_absolute())
          {
            include_file(include_filename.string(), os);
          }
          else
          {
            include_file((boost::filesystem::path(filename).parent_path() / include_filename).string(),
                         os);
          }
          os << "#line " << line_count << '\n';
        }
        else
        {
          os << line << '\n';
        }

        line_count += 1;
      }
      sources.emplace_back(os.str());
    }

    ShaderPtr shader = std::make_shared<Shader>(type);

    shader->source(sources);
    shader->compile();

    if (!shader->get_compile_status())
    {
      throw std::runtime_error((boost::format("%s: error:\n %s") % filename % shader->get_info_log()).str());
    }

    //log_debug("%s: shader compile successful", filename);

    return shader;
  }
}