Esempio n. 1
0
void            get_calc(t_list **list, char *ref_num, char *ref_op)
{
  char		op;
  t_list	*nb1;
  t_list	*nb2;

  *list = (*list)->befo;
  while ((*list)->befo != NULL && isnum((*list)->cha, ref_num) == 1)
    *list = (*list)->befo;
  if ((*list)->next != NULL && isop((*list)->cha, ref_op) == 2)
    {
      *list = (*list)->next;
      op = ((*list)->befo)->cha;
    }
  else
    op = (*list)->cha;
  nb2 = take_nb(*list, ref_num);
  *list = (*list)->befo;
  while ((*list) != NULL && isnum((*list)->cha, ref_num) == 0)
    *list = (*list)->befo;
  while ((*list)->befo != NULL && isnum(((*list)->befo)->cha, ref_num) == 1)
    *list = (*list)->befo;
  if ((*list)->befo != NULL && isop(((*list)->befo)->cha, ref_op) == 2)
    *list = (*list)->befo;
  nb1 = take_nb(*list, ref_num);
  *list = replace(list, calc(nb1, isop(op, ref_op), nb2, NUM_OP), NUM_OP);
  del_par(list, ref_num, ref_op);
}
Esempio n. 2
0
int CMPolynomial::find_bugs()
{
	int err = -1;
	int nmod,next;
   unsigned short i;
	for (i=0;i<expression.Count() && err<0;i++) {
		if (isop(expression[i]))
			continue;
		else if (isspecialfunc(expression[i])) {
			nmod = expression[i+1];
			i += (1 + nmod*2);
		}
		else if (expression[i]==Constant || expression[i]==Definition)
			i++;
		else if (expression[i]==Function) {
			nmod = expression[i+2];
			i += (2 + nmod*2);
		}
		else if (expression[i]==Variable || expression[i]==VariableOrig) {
			nmod = expression[i+2];
			i += (2 + nmod*3);
		}
		else if (expression[i]==If) {
			nmod = expression[i+1];
			i += (1 + nmod*2);
		}
		next = (i+1<expression.Count()) ? expression[i+1] : NoToken;
		if (!isop(next) && next!=NoToken)
			err = XBadExpression;
	}
	return err;
}
int main()
{
    int i=0,j=0,x,item;
    printf("enter infix expression\n");
    gets(inexp);
   // puts(inexp);
    item=inexp[i];i++;
    while(item!='\0')
    {
                  if(item=='(')
                  {
                               push(item);
                               }
                  else if((item>='A'&&item<='Z')||(item>='a'&&item<='z'))
                  {
                       postexp[j]=item;j++;
                       }
                  else if(isop(item)==1)
                  {
                       x=pop();
                     while(isop(x)==1&&(preced(x)>=preced(item)))
                     {
                          postexp[j]=x;j++;
                          x=pop();
                          }
                         push(x);
                         push(item);
                         }
                  else if(item==')')
                  {
                                   x=pop();
                                   while(x!='(')
                                   {
                                                postexp[j]=x;
                                                j++;
                                                x=pop();
                                                }
                                                }
                      else
                      {
                          printf("\ninvalid arithmetic expression");
                          }
                  item=inexp[i];
                  i++;
                  }
                  x=pop();
                  while(x!='a')
                  {
                               postexp[j]=x;
                               j++;
                               x=pop();
                               }
                  postexp[j++]='\0';
                  printf("\npostfix expression\n");
                  puts(postexp);
                  getch();
                  return 0;
}
Esempio n. 4
0
void reptree(struct tree *thetree)
{
	if(thetree != NULL){
		if(isop(thetree->data))
			printf("(");
		reptree(thetree->left);
		printf("%c", thetree->data);
		reptree(thetree->right);
		if(isop(thetree->data))
			printf(")");
	}
}
vector<int> diffWaysToCompute_1(string input) {
    int n = input.length();
    vector<int> nums;
    vector<char> ops;
    
    for(int i = 0; i < n; i ++) {
        char ch = input[i];
        if(isop(ch)) {
            ops.push_back(ch);
        }
        else {
            nums.push_back(atoi(input.c_str()+i));
            while(isnum(input[i]) && i < n) i++;
            i--;
        }
    }
    //note: n changed
    n = nums.size();

    vector<int> ans;
    ans = solve(nums, ops, 0, n-1);
    printVector(ans);


    return ans;
}
Esempio n. 6
0
File: cb.c Progetto: 00001/plan9port
void
gotop(int c)
{
	char optmp[OPLENGTH];
	char *op_ptr;
	struct op *s_op;
	char *a, *b;
	op_ptr = optmp;
	*op_ptr++ = c;
	while (isop((uchar)( *op_ptr = getch())))op_ptr++;
	if(!strict)unget(*op_ptr);
	else if (*op_ptr != ' ')unget( *op_ptr);
	*op_ptr = '\0';
	s_op = op;
	b = optmp;
	while ((a = s_op->name) != 0){
		op_ptr = b;
		while ((*op_ptr == *a) && (*op_ptr != '\0')){
			a++;
			op_ptr++;
		}
		if (*a == '\0'){
			keep(s_op);
			opflag = s_op->setop;
			if (*op_ptr != '\0'){
				b = op_ptr;
				s_op = op;
				continue;
			}
			else break;
		}
		else s_op++;
	}
}
Esempio n. 7
0
File: parse.c Progetto: GJDuck/SMCHR
/*
 * Get an operator token.
 */
static token_t token_getop(context_t cxt)
{
    char buf0[TOKEN_MAXLEN+1];
    char *buf = buf0, *str = cxt->str;
    size_t len = 0;
    token_t token = TOKEN_ERROR;

    while (isop(*str))
    {
        buf[len++] = *str++;
        if (len >= TOKEN_MAXLEN)
            return TOKEN_ERROR;
        buf[len] = '\0';
        name_t entry = name_lookup(buf);
        if (entry != NULL)
        {
            token = entry->token;
            cxt->str = str;
        }
        else if (binop_lookup(cxt->opinfo, buf, NULL, NULL, NULL, NULL))
        {
            token = TOKEN_OP;
            cxt->str = str;
        }
    }
    return token;
}
Esempio n. 8
0
list<pair<char, double> >& ArithmeticCalculator::to_rpn(string const& expr, list<pair<char, double> >& rpnExpr) {
	string::const_iterator p = expr.begin();
	stack<string::const_iterator> ops;

	while (p != expr.end()) {
		if (*p == '(')
			ops.push(p);
		else if (isop(p)) {
			while (!ops.empty() &&
				   priority(ops.top()) >= priority(p))
				{ rpnExpr.push_back(make_pair(*(ops.top()), 0.0)); ops.pop(); }
			ops.push(p);
		}
		else if (isdigit(*p) || *p == '.')
            rpnExpr.push_back(make_pair('\0', valueof(p)));
        else if (*p == 'x' || *p == 'X' || *p == 'y' || *p == 'Y' || *p == 'z' || *p == 'Z')
            rpnExpr.push_back(make_pair(*p, 0.0));
		else if (*p == ')') {
				while(*(ops.top()) != '(')
					{ rpnExpr.push_back(make_pair(*(ops.top()), 0.0)); ops.pop(); }
				// махаме и (
				ops.pop();
		}
		p++;
	}
	// изпразваме стека
	while (!ops.empty()) {
		rpnExpr.push_back(make_pair(*(ops.top()), 0.0)); ops.pop();
    }
	return rpnExpr;
}
Esempio n. 9
0
File: cb.c Progetto: 00001/plan9port
char *
getnext(int must){
	int c;
	char *beg;
	int prect,nlct;
	prect = nlct = 0;
	if(tptr > lastplace){
		tptr = lastplace = temp;
		err = 0;
		inswitch = 0;
	}
	tp = lastplace;
	if(inswitch && tptr <= lastplace)
		if (isalnum((uchar)*lastplace)||ispunct((uchar)*lastplace)||isop((uchar)*lastplace))return(lastplace);
space:
	while(isspace(c=Bgetc(input)))puttmp(c,1);
	beg = tp;
	puttmp(c,1);
	if(c == '/'){
		if(puttmp(Bgetc(input),1) == '*'){
cont:
			while((c=Bgetc(input)) != '*'){
				puttmp(c,0);
				if(must == 0 && c == '\n')
					if(nlct++ > 2)goto done;
			}
			puttmp(c,1);
	star:
			if(puttmp((c=Bgetc(input)),1) == '/'){
				beg = tp;
				puttmp((c=Bgetc(input)),1);
			}
			else if(c == '*')goto star;
			else goto cont;
		}
		else goto done;
	}
	if(isspace(c))goto space;
	if(c == '#' && tp > temp+1 && *(tp-2) == '\n'){
		if(prect++ > 2)goto done;
		while(puttmp((c=Bgetc(input)),1) != '\n')
			if(c == '\\')puttmp(Bgetc(input),1);
		goto space;
	}
	if(isalnum(c)){
		while(isalnum(c = Bgetc(input)))puttmp(c,1);
		Bungetc(input);
	}
done:
	puttmp('\0',1);
	lastplace = tp-1;
	inswitch = 1;
	return(beg);
}
Esempio n. 10
0
File: lex_3.c Progetto: Fusiow/msh
static char	*istild(int *i, char *str, int start)
{
	char	*tmp;
	char	*result;

	++*i;
	while (!(iswhite(str[*i])) && !(isop(str[*i])) && str[*i])
		++*i;
	tmp = ft_strsub(str, start + 1, (*i - start - 1));
	result = ft_strjoin(find_value_envir(g_env, "HOME"), tmp);
	return (result);
}
Esempio n. 11
0
int nonreptree(struct tree *thetree)
{
	FILE *fp;
	fp = fopen("output.txt", "w");
  	
	struct tree *current = thetree;
  	struct stack buf;
	stack_create(&buf);
	int done = 0;

	/* если дерево состоит из единственного элемента */
	if(current !=NULL){
		fprintf(fp,"Л К П\n");
		if( current->left == NULL &&  current->right == NULL ){
	  		fprintf(fp,"  %c", current->data);
			fclose(fp);
			return 1;
		}
	}
  	while (!done){
		/* пока левый потомок не NULL - пихаем элемент в стек */
    	if(current !=  NULL){
      		stack_push(&buf, current);
      		current = current->left;
    	}else{

			if (!is_stk_empty(&buf)){
        		current = stack_pop(&buf);

			if(isop(current->data)){
				if(current->left != NULL)
					fprintf(fp,"%c", current->left->data);
				else
					fprintf(fp," ");

				fprintf(fp," %c", current->data);
				
				if(current->right != NULL)
					fprintf(fp," %c", current->right->data);
				else
					fprintf(fp," ");
				fprintf(fp,"\n");
			}	
			current = current->right;
		}else
			done = 1; /* конец работы */
    }
  }
	fclose(fp);
	return 0;
}
Esempio n. 12
0
int	is_empty(char *expr, char *num, char *op)
{
  int	i;

  i = 0;
  while (expr[i])
    {
      if (isop(expr[i], op) > 0 || isnum(expr[i], num) != 0)
	return (0);
      i = i + 1;
    }
  my_putstr("ERROR : No one valid character !\n");
  return (1);
}
vector<int> diffWaysToCompute(string input) {
    int n = input.length();
    vector<int> nums;
    vector<char> ops;
    
    for(int i = 0; i < n; i ++) {
        char ch = input[i];
        if(isop(ch)) {
            ops.push_back(ch);
        }
        else {
            nums.push_back(atoi(input.c_str()+i));
            while(isnum(input[i]) && i < n) i++;
            i--;
        }
    }
    //note: n changed
    n = nums.size();

    vector<vector<vector<int> > > dp;
    dp.resize(n+5);
    for(int i = 0; i < n; i ++) {
        dp[i].resize(n+5);
    }

    for(int k = 0; k < n; k ++) {
        for(int i = 0; i+k < n; i ++) {
            if(k == 0) {
                vector<int> tmp;
                tmp.push_back(nums[i]);
                dp[i][i] = tmp;
            }
            else {
                for(int j = i; j < i+k; j ++) {
                    vector<int>& a = dp[i][j];
                    vector<int>& b = dp[j+1][i+k];
                    for(int ii = 0; ii < a.size(); ii ++) {
                        for(int jj = 0; jj < b.size(); jj ++) {
                            int c = calc(ops[j], a[ii], b[jj]);
                            dp[i][i+k].push_back(c);
                        }
                    }
                }
            }
        }
    }

    return dp[0][n-1];
}
Esempio n. 14
0
int	val_cha(char *begin, char *ref_num,char *ref_op)
{
  int	i;

  i = 0;
  while (begin[i])
    {
      if (isop(begin[i], ref_op) == -1 && isnum(begin[i], ref_num) == 0)
	{
	  my_putstr("WARNING : Invalid character are delete for calcul\n");
	  return (0);
	}
      i = i + 1;
    }
  return (0);
}
Esempio n. 15
0
static char *get_attr_name(char *src, char *dest, int sz)
{
	int		i	= 0,
			ct	= 0;


	while ( (src[i] != '\0') && isblank(src[i]) ) i++;			/* skip whitespaces */
	while ( (src[i] != '\n') && (src[i] != '\0') && !isop(src[i]) && !isblank(src[i]) )
	{
		if ( ct < sz ) 
			dest[ct++] = src[i];
		i++;
	}
	dest[ct] = '\0';

	return src+i;
}
Esempio n. 16
0
struct Nodetype* Binarytree::insert(Nodetype *node, std::string data)
{
isinright=false;
    //bool checkInsert = false; //PEDRO TIROU POIS NÃO TEM PQ ESTA AQUI.
    if(node==NULL) {
        // checkInsert = true; //PEDRO TIROU POIS NÃO TEM PQ ESTA AQUI.
        isinright = true;
        return (build_node(data));}
    else
    {
        if(isop(node->data)){

            node->right_child=insert(node->right_child,data);
            //std::cout<<"2"<<node->right_child->data<<std::endl;

            if(isinright==false){
                node->left_child=insert(node->left_child,data);
                // std::cout<<"3"<<node->left_child->data<<std::endl;

            }
        }
    }
    return node;
}
Esempio n. 17
0
/* getop: get next operator or numeric operand, return type */
int getop(char s[])
{
	int i, c, type;

	i = 0;
	while ( (s[i] = c = getch()) == ' ' || c == '\t')
		;		/* skip white space */
	if (c == '-') {		/* '-' could be operator or negative indicator */
		s[++i] = c = getch();
		if (!isdigit(c)) {
			ungetch(c);
			s[i] = '\0';
			return s[0];
		}
	}
	if (isop(c) || c == '\n') {
	        s[i] = '\0';
		return c;
	} else if (isdigit(c) || c == '.') { /* digit */
		type = NUMBER;
		if (isdigit(c))		/* collect integer part */
			while (isdigit(s[++i] = c = getch()))
				;
		if (c == '.')		/* collect fraction part */
			while (isdigit(s[++i] = c = getch()))
				;
	} else {		/* handles any other input */
		while ( (s[++i] = c = getch()) != ' ' && c != '\t' && c != '\n')
			;
		type = optype(s, i-1);
	}
	s[i] = '\0';
	if (c != EOF)
		ungetch(c);
	return type;
}
Esempio n. 18
0
char *FParser::GetTokens(char *s)
{
	char *tokn = NULL;

	Rover = s;
	NumTokens = 1;
	Tokens[0][0] = 0; TokenType[NumTokens-1] = name_;
	
	Section = NULL;   // default to no section found
	
	NextToken();
	LineStart = Rover;      // save the start
	
	if(*Rover)
	{
		while(1)
		{
			tokn = Tokens[NumTokens-1];
			if(Section)
			{
				// a { or } section brace has been found
				break;        // stop parsing now
			}
			else if(TokenType[NumTokens-1] != string_)
			{
				if(*Rover == ';') break;     // check for end of command ';'
			}
			
			switch(TokenType[NumTokens-1])
			{
			case unset:
			case string_:
				while(*Rover != '\"')     // dedicated loop for speed
				{
					if(*Rover == '\\')       // escape sequences
					{
						Rover++;
						if (*Rover>='0' && *Rover<='9')
						{
							add_char(tokn, TEXTCOLOR_ESCAPE);
							add_char(tokn, *Rover+'A'-'0');
						}
						else add_char(tokn, escape_sequence(*Rover));
					}
					else
						add_char(tokn, *Rover);
					Rover++;
				}
				Rover++;
				NextToken();       // end of this token
				continue;
				
			case operator_:
				// all 2-character operators either end in '=' or
				// are 2 of the same character
				// do not allow 2-characters for brackets '(' ')'
				// which are still being considered as operators
				
				// operators are only 2-char max, do not need
				// a seperate loop
				
				if((*tokn && *Rover != '=' && *Rover!=*tokn) ||
					*tokn == '(' || *tokn == ')')
				{
					// end of operator
					NextToken();
					continue;
				}
				add_char(tokn, *Rover);
				break;
				
			case number:
				
				// haleyjd: 8-17
				// add while number chars are read
				
				while(isnum(*Rover))       // dedicated loop
					add_char(tokn, *Rover++);
				NextToken();
				continue;
				
			case name_:
				
				// add the chars
				
				while(!isop(*Rover))        // dedicated loop
					add_char(tokn, *Rover++);
				NextToken();
				continue;
				
			default:
				break;
			}
			Rover++;
		}
	}
		
	// check for empty last token
	
	if(!tokn || !tokn[0])
	{
		NumTokens = NumTokens - 1;
	}
	
	Rover++;
	return Rover;
}
Esempio n. 19
0
bool Token::isop(char b)
{
    return isop(string(1, b)) || b == ':';
}
Esempio n. 20
0
void get_tokens(char *s)
{
	rover = s;
	num_tokens = 1;
	tokens[0][0] = 0; tt = name_;
	
	current_section = NULL;   // default to no section found
	
	next_token();
	linestart = rover;      // save the start
	
	if(*rover)
		while(1)
		{
			if(killscript) return;
			if(current_section)
			{
				// a { or } section brace has been found
				break;        // stop parsing now
			}
			else if(tt != string_)
			{
				if(*rover == ';') break;     // check for end of command ';'
			}
			
			switch(tt)
			{
			case unset:
			case string_:
				while(*rover != '\"')     // dedicated loop for speed
				{
					if(*rover == '\\')       // escape sequences
					{
						rover++;
						if (*rover>='0' && *rover<='9')
						{
							add_char(TEXTCOLOR_ESCAPE);
							add_char(*rover+'A'-'0');
						}
						else add_char(escape_sequence(*rover));
					}
					else
						add_char(*rover);
					rover++;
				}
				rover++;
				next_token();       // end of this token
				continue;
				
			case operator_:
				// all 2-character operators either end in '=' or
				// are 2 of the same character
				// do not allow 2-characters for brackets '(' ')'
				// which are still being considered as operators
				
				// operators are only 2-char max, do not need
				// a seperate loop
				
				if((*tok && *rover != '=' && *rover!=*tok) ||
					*tok == '(' || *tok == ')')
				{
					// end of operator
					next_token();
					continue;
				}
				add_char(*rover);
				break;
				
			case number:
				
				// haleyjd: 8-17
				// add while number chars are read
				
				while(isnum(*rover))       // dedicated loop
					add_char(*rover++);
				next_token();
				continue;
				
			case name_:
				
				// add the chars
				
				while(!isop(*rover))        // dedicated loop
					add_char(*rover++);
				next_token();
				continue;
				
			default:
				break;
			}
			rover++;
		}
		
	// check for empty last token
	
	if(!tok[0])
	{
		num_tokens = num_tokens - 1;
	}
	
	rover++;
}
Esempio n. 21
0
File: cb.c Progetto: 00001/plan9port
void
work(void){
	int c;
	struct keyw *lptr;
	char *pt;
	int cc;
	int ct;

	while ((c = getch()) != Beof){
		switch (c){
		case '{':
			if ((lptr = lookup(lastlook,p)) != 0){
				if (lptr->type == ELSE)gotelse();
				else if(lptr->type == DO)gotdo();
				else if(lptr->type == STRUCT)structlev++;
			}
			if(++clev >= &ind[CLEVEL-1]){
				fprint(2,"too many levels of curly brackets\n");
				clev = &ind[CLEVEL-1];
			}
			clev->pdepth = 0;
			clev->tabs = (clev-1)->tabs;
			clearif(clev);
			if(strict && clev->tabs > 0)
				putspace(' ',NO);
			putch(c,NO);
			getnl();
			if(keyflag == DATADEF){
				OUT;
			}
			else {
				OUTK;
			}
			clev->tabs++;
			pt = getnext(0);		/* to handle initialized structures */
			if(*pt == '{'){		/* hide one level of {} */
				while((c=getch()) != '{')
					if(c == Beof)error("{");
				putch(c,NO);
				if(strict){
					putch(' ',NO);
					eatspace();
				}
				keyflag = SINIT;
			}
			continue;
		case '}':
			pt = getnext(0);		/* to handle initialized structures */
			if(*pt == ','){
				if(strict){
					putspace(' ',NO);
					eatspace();
				}
				putch(c,NO);
				putch(*pt,NO);
				*pt = '\0';
				ct = getnl();
				pt = getnext(0);
				if(*pt == '{'){
					OUT;
					while((cc = getch()) != '{')
						if(cc == Beof)error("}");
					putch(cc,NO);
					if(strict){
						putch(' ',NO);
						eatspace();
					}
					getnext(0);
					continue;
				}
				else if(strict || ct){
					OUT;
				}
				continue;
			}
			else if(keyflag == SINIT && *pt == '}'){
				if(strict)
					putspace(' ',NO);
				putch(c,NO);
				getnl();
				OUT;
				keyflag = DATADEF;
				*pt = '\0';
				pt = getnext(0);
			}
			outs(clev->tabs);
			if(--clev < ind)clev = ind;
			ptabs(clev->tabs);
			putch(c,NO);
			lbegin = 0;
			lptr=lookup(pt,lastplace+1);
			c = *pt;
			if(*pt == ';' || *pt == ','){
				putch(*pt,NO);
				*pt = '\0';
				lastplace=pt;
			}
			ct = getnl();
			if((dolevel && clev->tabs <= dotabs[dolevel]) || (structlev )
			    || (lptr != 0 &&lptr->type == ELSE&& clev->pdepth == 0)){
				if(c == ';'){
					OUTK;
				}
				else if(strict || (lptr != 0 && lptr->type == ELSE && ct == 0)){
					putspace(' ',NO);
					eatspace();
				}
				else if(lptr != 0 && lptr->type == ELSE){
					OUTK;
				}
				if(structlev){
					structlev--;
					keyflag = DATADEF;
				}
			}
			else {
				OUTK;
				if(strict && clev->tabs == 0){
					if((c=getch()) != '\n'){
						Bputc(output, '\n');
						Bputc(output, '\n');
						unget(c);
					}
					else {
						lineno++;
						Bputc(output, '\n');
						if((c=getch()) != '\n')unget(c);
						else lineno++;
						Bputc(output, '\n');
					}
				}
			}
			if(lptr != 0 && lptr->type == ELSE && clev->pdepth != 0){
				UNBUMP;
			}
			if(lptr == 0 || lptr->type != ELSE){
				clev->iflev = 0;
				if(dolevel && docurly[dolevel] == NO && clev->tabs == dotabs[dolevel]+1)
					clev->tabs--;
				else if(clev->pdepth != 0){
					UNBUMP;
				}
			}
			continue;
		case '(':
			paren++;
			if ((lptr = lookup(lastlook,p)) != 0){
				if(!(lptr->type == TYPE || lptr->type == STRUCT))keyflag=KEYWORD;
				if (strict){
					putspace(lptr->punc,NO);
					opflag = 1;
				}
				putch(c,NO);
				if (lptr->type == IF)gotif();
			}
			else {
				putch(c,NO);
				lastlook = p;
				opflag = 1;
			}
			continue;
		case ')':
			if(--paren < 0)paren = 0;
			putch(c,NO);
			if((lptr = lookup(lastlook,p)) != 0){
				if(lptr->type == TYPE || lptr->type == STRUCT)
					opflag = 1;
			}
			else if(keyflag == DATADEF)opflag = 1;
			else opflag = 0;
			outs(clev->tabs);
			pt = getnext(1);
			if ((ct = getnl()) == 1 && !strict){
				if(dolevel && clev->tabs <= dotabs[dolevel])
					resetdo();
				if(clev->tabs > 0 && (paren != 0 || keyflag == 0)){
					if(join){
						eatspace();
						putch(' ',YES);
						continue;
					} else {
						OUT;
						split = 1;
						continue;
					}
				}
				else if(clev->tabs > 0 && *pt != '{'){
					BUMP;
				}
				OUTK;
			}
			else if(strict){
				if(clev->tabs == 0){
					if(*pt != ';' && *pt != ',' && *pt != '(' && *pt != '['){
						OUTK;
					}
				}
				else {
					if(keyflag == KEYWORD && paren == 0){
						if(dolevel && clev->tabs <= dotabs[dolevel]){
							resetdo();
							eatspace();
							continue;
						}
						if(*pt != '{'){
							BUMP;
							OUTK;
						}
						else {
							*pt='\0';
							eatspace();
							unget('{');
						}
					}
					else if(ct){
						if(paren){
							if(join){
								eatspace();
							} else {
								split = 1;
								OUT;
							}
						}
						else {
							OUTK;
						}
					}
				}
			}
			else if(dolevel && clev->tabs <= dotabs[dolevel])
				resetdo();
			continue;
		case ' ':
		case '\t':
			if ((lptr = lookup(lastlook,p)) != 0){
				if(!(lptr->type==TYPE||lptr->type==STRUCT))
					keyflag = KEYWORD;
				else if(paren == 0)keyflag = DATADEF;
				if(strict){
					if(lptr->type != ELSE){
						if(lptr->type == TYPE){
							if(paren != 0)putch(' ',YES);
						}
						else
							putch(lptr->punc,NO);
						eatspace();
					}
				}
				else putch(c,YES);
				switch(lptr->type){
				case CASE:
					outs(clev->tabs-1);
					continue;
				case ELSE:
					pt = getnext(1);
					eatspace();
					if((cc = getch()) == '\n' && !strict){
						unget(cc);
					}
					else {
						unget(cc);
						if(checkif(pt))continue;
					}
					gotelse();
					if(strict) unget(c);
					if(getnl() == 1 && !strict){
						OUTK;
						if(*pt != '{'){
							BUMP;
						}
					}
					else if(strict){
						if(*pt != '{'){
							OUTK;
							BUMP;
						}
					}
					continue;
				case IF:
					gotif();
					continue;
				case DO:
					gotdo();
					pt = getnext(1);
					if(*pt != '{'){
						eatallsp();
						OUTK;
						docurly[dolevel] = NO;
						dopdepth[dolevel] = clev->pdepth;
						clev->pdepth = 0;
						clev->tabs++;
					}
					continue;
				case TYPE:
					if(paren)continue;
					if(!strict)continue;
					gottype(lptr);
					continue;
				case STRUCT:
					gotstruct();
					continue;
				}
			}
			else if (lbegin == 0 || p > string) 
				if(strict)
					putch(c,NO);
				else putch(c,YES);
			continue;
		case ';':
			putch(c,NO);
			if(paren != 0){
				if(strict){
					putch(' ',YES);
					eatspace();
				}
				opflag = 1;
				continue;
			}
			outs(clev->tabs);
			pt = getnext(0);
			lptr=lookup(pt,lastplace+1);
			if(lptr == 0 || lptr->type != ELSE){
				clev->iflev = 0;
				if(clev->pdepth != 0){
					UNBUMP;
				}
				if(dolevel && docurly[dolevel] == NO && clev->tabs <= dotabs[dolevel]+1)
					clev->tabs--;
/*
				else if(clev->pdepth != 0){
					UNBUMP;
				}
*/
			}
			getnl();
			OUTK;
			continue;
		case '\n':
			if ((lptr = lookup(lastlook,p)) != 0){
				pt = getnext(1);
				if (lptr->type == ELSE){
					if(strict)
						if(checkif(pt))continue;
					gotelse();
					OUTK;
					if(*pt != '{'){
						BUMP;
					}
				}
				else if(lptr->type == DO){
					OUTK;
					gotdo();
					if(*pt != '{'){
						docurly[dolevel] = NO;
						dopdepth[dolevel] = clev->pdepth;
						clev->pdepth = 0;
						clev->tabs++;
					}
				}
				else {
					OUTK;
					if(lptr->type == STRUCT)gotstruct();
				}
			}
			else if(p == string)Bputc(output, '\n');
			else {
				if(clev->tabs > 0 &&(paren != 0 || keyflag == 0)){
					if(join){
						putch(' ',YES);
						eatspace();
						continue;
					} else {
						OUT;
						split = 1;
						continue;
					}
				}
				else if(keyflag == KEYWORD){
					OUTK;
					continue;
				}
				OUT;
			}
			continue;
		case '"':
		case '\'':
			putch(c,NO);
			while ((cc = getch()) != c){
				if(cc == Beof)
					error("\" or '");
				putch(cc,NO);
				if (cc == '\\'){
					putch(getch(),NO);
				}
				if (cc == '\n'){
					outs(clev->tabs);
					lbegin = 1;
					count = 0;
				}
			}
			putch(cc,NO);
			opflag=0;
			if (getnl() == 1){
				unget('\n');
			}
			continue;
		case '\\':
			putch(c,NO);
			putch(getch(),NO);
			continue;
		case '?':
			question = 1;
			gotop(c);
			continue;
		case ':':
			if (question == 1){
				question = 0;
				gotop(c);
				continue;
			}
			putch(c,NO);
			if(structlev)continue;
			if ((lptr = lookup(lastlook,p)) != 0){
				if (lptr->type == CASE)outs(clev->tabs - 1);
			}
			else {
				lbegin = 0;
				outs(clev->tabs);
			}
			getnl();
			OUTK;
			continue;
		case '/':
			if ((cc = getch()) == '/') {
				putch(c,NO);
				putch(cc,NO);
				cpp_comment(YES);
				OUT;
				lastlook = 0;
				continue;
			}
			else if (cc != '*') {
				unget(cc);
				gotop(c);
				continue;
			}
			putch(c,NO);
			putch(cc,NO);
			cc = comment(YES);
			if(getnl() == 1){
				if(cc == 0){
					OUT;
				}
				else {
					outs(0);
					Bputc(output, '\n');
					lbegin = 1;
					count = 0;
				}
				lastlook = 0;
			}
			continue;
		case '[':
			putch(c,NO);
			ct = 0;
			while((c = getch()) != ']' || ct > 0){
				if(c == Beof)error("]");
				putch(c,NO);
				if(c == '[')ct++;
				if(c == ']')ct--;
			}
			putch(c,NO);
			continue;
		case '#':
			putch(c,NO);
			while ((cc = getch()) != '\n'){
				if(cc == Beof)error("newline");
				if (cc == '\\'){
					putch(cc,NO);
					cc = getch();
				}
				putch(cc,NO);
			}
			putch(cc,NO);
			lbegin = 0;
			outs(clev->tabs);
			lbegin = 1;
			count = 0;
			continue;
		default:
			if (c == ','){
				opflag = 1;
				putch(c,YES);
				if (strict){
					if ((cc = getch()) != ' ')unget(cc);
					if(cc != '\n')putch(' ',YES);
				}
			}
			else if(isop(c))gotop(c);
			else {
				if(isalnum(c) && lastlook == 0)lastlook = p;
				if(isdigit(c)){
					putch(c,NO);
					while(isdigit(c=Bgetc(input))||c == '.')putch(c,NO);
					if(c == 'e'){
						putch(c,NO);
						c = Bgetc(input);
						putch(c, NO);
						while(isdigit(c=Bgetc(input)))putch(c,NO);
					}
					Bungetc(input);
				}
				else putch(c,NO);
				if(keyflag != DATADEF)opflag = 0;
			}
		}
	}
}
Esempio n. 22
0
static int
vnop_lookup_9p(struct vnop_lookup_args *ap)
{
	struct componentname *cnp;
	node_9p *dnp;
	vnode_t *vpp, dvp;
	fid_9p fid;
	qid_9p qid;
	int e;

	TRACE();
	dvp = ap->a_dvp;
	vpp = ap->a_vpp;
	cnp = ap->a_cnp;
	dnp = NTO9P(dvp);

	if(!vnode_isdir(dvp))
		return ENOTDIR;

	if (isdotdot(cnp) && vnode_isvroot(dvp))
		return EIO;

	if (islastcn(cnp) && !isop(cnp, LOOKUP) && vnode_vfsisrdonly(dvp))
		return EROFS;

	if (isdot(cnp)) {
		if (islastcn(cnp) && isop(cnp, RENAME))
			return EISDIR;

		if ((e=vnode_get(dvp)))
			return e;
		*vpp = dvp;
		return 0;
	}

	if (isdotdot(cnp)) {
		*vpp = vnode_getparent(dvp);
		if (*vpp == NULL)
			return ENOENT;
		return 0;
	}

	e = cache_lookup(dvp, vpp, cnp);
	if (e == -1)	/* found */
		return 0;
	if (e != 0)		/* errno */
		return e;

	/* not in cache */
	nlock_9p(dnp, NODE_LCK_EXCLUSIVE);
	e = walk_9p(dnp->nmp, dnp->fid, cnp->cn_nameptr, cnp->cn_namelen, &fid, &qid);
	if (e) {
		if (islastcn(cnp)) {
			if (isop(cnp, CREATE) || isop(cnp, RENAME))
				e = EJUSTRETURN;
			else if (ismkentry(cnp) && dnp->dir.qid.vers!=0)
				cache_enter(dvp, NULL, cnp);
		}
		goto error;
	}

	e = nget_9p(dnp->nmp, fid, qid, dvp, vpp, cnp, ap->a_context);
	if (e || *vpp==NULL || NTO9P(*vpp)->fid!=fid) 
		clunk_9p(dnp->nmp, fid);

	if (*vpp)
		nunlock_9p(NTO9P(*vpp));

error:
	nunlock_9p(dnp);
	return e;
}
Esempio n. 23
0
char *DFsScript::ProcessFindChar(char *datap, char find)
{
	while(*datap)
    {
		if(*datap==find) return datap;
		if(*datap=='\"')       // found a quote: ignore stuff in it
		{
			datap++;
			while(*datap && *datap != '\"')
			{
				// escape sequence ?
				if(*datap=='\\') datap++;
				datap++;
			}
			// error: end of script in a constant
			if(!*datap) return NULL;
		}
		
		// comments: blank out
		
		if(*datap=='/' && *(datap+1)=='*')        // /* -- */ comment
		{
			while(*datap && (*datap != '*' || *(datap+1) != '/') )
			{
				*datap=' '; datap++;
			}
			if(*datap)
				*datap = *(datap+1) = ' ';   // blank the last bit
			else
			{
				// script terminated in comment
				script_error("script terminated inside comment\n");
			}
		}
		if(*datap=='/' && *(datap+1)=='/')        // // -- comment
		{
			while(*datap != '\n')
			{
				*datap=' '; datap++;       // blank out
			}
		}
		
		/********** labels ****************/

		// labels are also found during the
		// preprocessing. these are of the form
		//
		//      label_name:
		//
		// and are used for the goto function.
		// goto labels are stored as variables.

		if(*datap==':' && scriptnum != -1) // not in global scripts
		{
			char *labelptr = datap-1;
			
			while(!isop(*labelptr)) labelptr--;

			FString labelname(labelptr+1, strcspn(labelptr+1, ":"));
			
			if (labelname.Len() == 0)
			{
				Printf(PRINT_BOLD,"Script %d: ':' encountrered in incorrect position!\n",scriptnum);
			}

			DFsVariable *newlabel = NewVariable(labelname, svt_label);
			newlabel->value.i = MakeIndex(labelptr);
		}
		
		if(*datap=='{')  // { -- } sections: add 'em
		{
			DFsSection *newsec = NewSection(datap);
			
			newsec->type = st_empty;
			// find the ending } and save
			char * theend = ProcessFindChar(datap+1, '}');
			if(!theend)
			{                // brace not found
				// This is fatal because it will cause a crash later
				// if the game isn't terminated.
				I_Error("Script %d: section error: no ending brace\n", scriptnum);
			}

			newsec->end_index = MakeIndex(theend);
			// continue from the end of the section
			datap = theend;
		}
		datap++;
    }
	return NULL;
}
Esempio n. 24
0
static void next_token()
{
	if(tok[0] || tt==string_)
    {
		num_tokens++;
		tokens[num_tokens-1] = tokens[num_tokens-2]
			+ strlen(tokens[num_tokens-2]) + 1;
		tok[0] = 0;
    }
	
	// get to the next token, ignoring spaces, newlines,
	// useless chars, comments etc
	
	while(1)
    {
		// empty whitespace
		if(*rover && (*rover==' ' || *rover<32))
		{
			while((*rover==' ' || *rover<32) && *rover) rover++;
		}
		// end-of-script?
		if(!*rover)
		{
			if(tokens[0][0])
			{
			/*
			C_Printf("%s %i %i\n", tokens[0],
			rover-current_script->data, current_script->len);
				*/
				// line contains text, but no semicolon: an error
				script_error("missing ';'\n");
			}
			// empty line, end of command-list
			return;
		}
		// 11/8 comments moved to new preprocessor
		
		break;  // otherwise
    }
	
	if(num_tokens>1 && *rover == '(' && tokentype[num_tokens-2] == name_)
		tokentype[num_tokens-2] = function;
	
	if(*rover == '{' || *rover == '}')
    {
		if(*rover == '{')
		{
			bracetype = bracket_open;
			current_section = find_section_start(rover);
		}
		else            // closing brace
		{
			bracetype = bracket_close;
			current_section = find_section_end(rover);
		}
		if(!current_section)
		{
			I_Error("section not found!\n");
			return;
		}
    }
	else if(*rover == ':')  // label
    {
		// ignore the label : reset
		num_tokens = 1;
		tokens[0][0] = 0; tt = name_;
		rover++;        // ignore
    }
	else if(*rover == '\"')
    {
		tt = string_;
		if(tokentype[num_tokens-2] == string_)
			num_tokens--;   // join strings
		rover++;
    }
	else
    {
		tt = isop(*rover) ? operator_ : isnum(*rover) ? number : name_;
    }
}
Esempio n. 25
0
CMString CMPolynomial::GetString()
{
	CMString ret;
	if (Fail()) {
   		if (original) 
			return *original;
		else
			return L"ERROR!";
   }
	int nmod;
   unsigned short i;
	for (i=0;i<expression.Count();i++) {
		if (expression[i]==Constant)
      	ret += constants[expression[++i]];
		else if (expression[i]==Definition)
			ret += CMDefinitions::GetDefinitionName(expression[++i]);
		else if (expression[i]==If) {
			nmod = expression[++i];
			ret += L"@IF (";
			if (expression[++i]==Constant)
	      	ret += constants[expression[++i]];
			else
				ret += expressions[expression[++i]]->GetString();
			ret += L") {";
			if (expression[++i]==Constant)
	      	ret += constants[expression[++i]];
			else
				ret += expressions[expression[++i]]->GetString();
			ret += L"}";
			if (nmod==3) {
				ret += L" @ELSE {";
				if (expression[++i]==Constant)
		      	ret += constants[expression[++i]];
				else
					ret += expressions[expression[++i]]->GetString();
				ret += L"}";
			}
		}
		else if (expression[i]==Variable||expression[i]==VariableOrig) {
			int isorig = (expression[i]==VariableOrig);
			ret += varnames[expression[++i]];
			if (isorig) ret += L"~";
			nmod = expression[++i];
			if(nmod) i++;
			for (int j=0;j<nmod;j++) {
				ret += L"[";
				switch (expression[i]) {
					case Lag: case Fwd: ret+= L"_t"; break;
					case LagSecond: case FwdSecond: ret+= L"_s"; break;
					case LagMinute: case FwdMinute: ret+= L"_i"; break;
					case LagHour: case FwdHour: ret+= L"_h"; break;
					case LagDay: case FwdDay: ret+= L"_d"; break;
					case LagWeek: case FwdWeek: ret+= L"_w"; break;
					case LagMonth: case FwdMonth: ret+= L"_m"; break;
					case LagYear: case FwdYear: ret+= L"_y"; break;
				}
				if (expression[i] >= Lag && expression[i] <= LagYear)
					ret += L"-";
				if (expression[i] >= Fwd && expression[i] <= FwdYear)
					ret += L"+";
				if (expression[++i]==Constant)
		      	ret += constants[expression[++i]];
				else
					ret += expressions[expression[++i]]->GetString();
				ret += L"]";
				if (j<nmod-1) i++;
			}
		}
		else if (isop(expression[i]))
			ret += ops[expression[i]-FirstOp];
		else if (expression[i]==Function||isspecialfunc(expression[i])) {
         if (expression[i]==Function)
				ret += functions[expression[++i]].GetName();
   		else
				ret += special_funcs[expression[i]-FirstSpecialFunc];
         ret += L"(";
			nmod = expression[++i];
			i++;
			for (int j=0;j<nmod;j++) {
				if (expression[i++]==Constant)
		      	ret += constants[expression[i]];
				else
					ret += expressions[expression[i]]->GetString();
				ret += ((j==nmod-1) ? L")" : L",");
				if (j<nmod-1) i++;
			}
		}
	}
	return ret;
}
Esempio n. 26
0
void ParseExpression(TokenList &a_list, const std::string &a_expression)
{
	enum class ParseState {None, Number, Name} state = ParseState::None;
	int elen = a_expression.length() + 1;
	int idx = 0;
	int tstart = 0;
	char c_char, n_char;

	while (true)
	{
		if (idx < elen)
		{
			c_char = a_expression[idx];
			if (idx + 1 < elen) n_char = a_expression[idx + 1];
			else n_char = 0;
			idx++;
		}
		else
		{
			if (state == ParseState::Name)
			{
				a_list.AddToken(ExtractValue(a_expression, tstart, idx - 1, Token::Type::Name));
				a_list.tail->index = tstart + 1;
			}
			else if (state == ParseState::Number)
			{
				a_list.AddToken(ExtractValue(a_expression, tstart, idx - 1, Token::Type::Number));
				a_list.tail->index = tstart + 1;
			}
			break;
		}

		if (std::isspace(c_char) && state != ParseState::None)
		{
			a_list.AddToken(ExtractValue(a_expression, tstart, idx - 1, (state == ParseState::Name ? Token::Type::Name : Token::Type::Number)));
			a_list.tail->index = tstart + 1;
			state = ParseState::None;
		}
		else if (isop(c_char))
		{
			if (state != ParseState::None)
			{
				a_list.AddToken(ExtractValue(a_expression, tstart, idx - 1, (state == ParseState::Name ? Token::Type::Name : Token::Type::Number)));
				a_list.tail->index = tstart + 1;
			}

			switch (c_char)
			{
			case '+': a_list.AddToken(new Token(Token::OpType::Add, idx)); break;
			case '-':
				if (a_list.count == 0 || a_list.tail->optype != Token::OpType::None)
					a_list.AddToken(new Token(Token::OpType::Unary, idx));
				else a_list.AddToken(new Token(Token::OpType::Sub, idx));
				break;
			case '*': a_list.AddToken(new Token(Token::OpType::Mul, idx)); break;
			case '/': a_list.AddToken(new Token(Token::OpType::Div, idx)); break;
			case '^': a_list.AddToken(new Token(Token::OpType::Pow, idx)); break;
			case '%': a_list.AddToken(new Token(Token::OpType::Mod, idx)); break;
			case '(': a_list.AddToken(new Token(Token::OpType::LPar, idx)); break;
			case ')': a_list.AddToken(new Token(Token::OpType::RPar, idx)); break;
			case ',': a_list.AddToken(new Token(Token::OpType::Comma, idx)); break;
			case '<':
				if (n_char == '=')
				{
					a_list.AddToken(new Token(Token::OpType::LE, idx));
					idx++;
				}
				else a_list.AddToken(new Token(Token::OpType::LT, idx));
				break;
			case '>':
				if (n_char == '=')
				{
					a_list.AddToken(new Token(Token::OpType::GE, idx));
					idx++;
				}
				else a_list.AddToken(new Token(Token::OpType::GT, idx));
				break;
			case '=':
				if (n_char == '=')
				{
					a_list.AddToken(new Token(Token::OpType::EQ, idx));
					idx++;
				}
				break;
			case '!':
				if (n_char == '=')
				{
					a_list.AddToken(new Token(Token::OpType::NE, idx));
					idx++;
				}
				break;
			}
			state = ParseState::None;
		}
		else if (issp(c_char) && state == ParseState::None && !isalpha(n_char))
		{
			switch (c_char)
			{
			case 't': a_list.AddToken(new Token(Token::SpecialType::Time, idx)); break;
			case 'x': a_list.AddToken(new Token(Token::SpecialType::XAxis, idx)); break;
			}
		}
		else if (state == ParseState::None && std::isalnum(c_char))
		{
			if (std::isdigit(c_char))
			{
				tstart = idx - 1;
				state = ParseState::Number;
			}
			else if (std::isalpha(c_char))
			{
				tstart = idx - 1;
				state = ParseState::Name;
			}
		}
	}
}
Esempio n. 27
0
void FParser::NextToken()
{
	if(Tokens[NumTokens-1][0] || TokenType[NumTokens-1]==string_)
    {
		NumTokens++;
		Tokens[NumTokens-1] = Tokens[NumTokens-2] + strlen(Tokens[NumTokens-2]) + 1;
		Tokens[NumTokens-1][0] = 0;
    }
	
	// get to the next token, ignoring spaces, newlines,
	// useless chars, comments etc
	
	while(1)
    {
		// empty whitespace
		if(*Rover && (*Rover==' ' || *Rover<32))
		{
			while((*Rover==' ' || *Rover<32) && *Rover) Rover++;
		}
		// end-of-script?
		if(!*Rover)
		{
			if(Tokens[0][0])
			{
				// line contains text, but no semicolon: an error
				script_error("missing ';'\n");
			}
			// empty line, end of command-list
			return;
		}
		break;  // otherwise
    }
	
	if(NumTokens>1 && *Rover == '(' && TokenType[NumTokens-2] == name_)
		TokenType[NumTokens-2] = function;
	
	if(*Rover == '{' || *Rover == '}')
    {
		if(*Rover == '{')
		{
			BraceType = bracket_open;
			Section = Script->FindSectionStart(Rover);
		}
		else            // closing brace
		{
			BraceType = bracket_close;
			Section = Script->FindSectionEnd(Rover);
		}
		if(!Section)
		{
			I_Error("section not found!\n");
			return;
		}
    }
	else if(*Rover == ':')  // label
    {
		// ignore the label : reset
		NumTokens = 1;
		Tokens[0][0] = 0; TokenType[NumTokens-1] = name_;
		Rover++;        // ignore
    }
	else if(*Rover == '\"')
    {
		TokenType[NumTokens-1] = string_;
		if(TokenType[NumTokens-2] == string_) NumTokens--;   // join strings
		Rover++;
    }
	else
    {
		TokenType[NumTokens-1] = isop(*Rover) ? operator_ : isnum(*Rover) ? number : name_;
    }
}
Esempio n. 28
0
File: parse.c Progetto: GJDuck/SMCHR
/*
 * Get a token from a string.
 */
static token_t token_get(context_t cxt, term_t *val, char *tokstr)
{
    term_t dummy;
    if (val == NULL)
        val = &dummy;
    
    if (cxt->peeked_token != TOKEN_NONE)
    {
        token_t token = cxt->peeked_token;
        *val = cxt->peeked_val;
        cxt->peeked_token = TOKEN_NONE;
        if (tokstr != NULL)
            strcpy(tokstr, cxt->peeked_str);
        return token;
    }

token_get_start: {}
    token_t token;
    char *start = cxt->str;
    char c = *cxt->str;
    switch (c)
    {
        case '\0':
            token = TOKEN_END;
            goto token_get_exit;
        case ';':
            cxt->str++;
            token = TOKEN_END;
            goto token_get_exit;
        case '/':
            if (cxt->str[1] == '/')
            {
                cxt->str += 2;
                while ((c = *cxt->str) != '\n' && c != '\0')
                    cxt->str++;
                goto token_get_start;
            }
            if (cxt->str[1] == '*')
            {
                cxt->str += 2;
                token_getcomment(cxt);
                goto token_get_start;
            }
            break;
        case '\n':
            cxt->line++;
            // Fallthrough
        case ' ': case '\t': case '\r':
            cxt->str++;
            goto token_get_start;
        case '(': case ')': case ',':
            cxt->str++;
            token = (token_t)c;
            goto token_get_exit;
        case '_': case '\'':
            token = token_getname(cxt, val);
            goto token_get_exit;
        case '@':
            cxt->str++;
            token = token_getname(cxt, val);
            if (token != TOKEN_VARIABLE)
            {
                token = TOKEN_ERROR;
                goto token_get_exit;
            }
            atom_t atom = make_atom(var(*val)->name, 0);
            *val = term_atom(atom);
            goto token_get_exit;
        case '"':
            token = token_getstring(cxt, val);
            goto token_get_exit;
        default:
            break;
    }

    if (isdigit(c))
        token = token_getnum(cxt, val);
    else if (isalpha(c))
        token = token_getname(cxt, val);
    else if (isop(c))
        token = token_getop(cxt);
    else
    {
        if (isprint(c))
            parse_error(cxt, "unexpected character `!y%c!d'", c);
        else
            parse_error(cxt, "unexpected character (!y0x%.2X!d)", c);
        token = TOKEN_ERROR;
    }

token_get_exit: {}

    size_t len = cxt->str - start;
    if (tokstr != NULL)
    {
        len = (len > TOKEN_MAXLEN? TOKEN_MAXLEN: len);
        strncpy(tokstr, start, len);
        tokstr[len] = '\0';
    }
    if (token == TOKEN_ERROR)
    {
        if (len == 0)
        {
            len++;
            if (tokstr != NULL)
            {
                tokstr[0] = cxt->str[0];
                tokstr[1] = '\0';
            }
        }
        parse_error(cxt, "bad token `%.*s'", len, start);
    }
    if (token == TOKEN_END && tokstr != NULL)
        strcpy(tokstr, "<END>");

    return token;
}
Esempio n. 29
0
char *process_find_char(char *data, char find)
{
  while(*data)
    {
      if(*data==find) return data;
      if(*data=='\"')       // found a quote: ignore stuff in it
	{
	  data++;
	  while(*data && *data != '\"')
	    {
	      // escape sequence ?
	      if(*data=='\\') data++;
	      data++;
	    }
	  // error: end of script in a constant
	  if(!*data) return NULL;
	}

      // comments: blank out

      if(*data=='/' && *(data+1)=='*')        // /* -- */ comment
	{
	  while(*data && (*data != '*' || *(data+1) != '/') )
	    {
	      *data=' '; data++;
	    }
	  if(*data)
	    *data = *(data+1) = ' ';   // blank the last bit
	  else
	    {
	      rover = data;
	      // script terminated in comment
	      script_error("script terminated inside comment\n");
	    }
	}
      if(*data=='/' && *(data+1)=='/')        // // -- comment
	while(*data != '\n')
	  {
	    *data=' '; data++;       // blank out
	  }

      // labels

      if(*data==':'  // ':' -- a label
	 && current_script->scriptnum != -1)   // not levelscript
	{
	  char *labelptr = data-1;
	  
	  while(!isop(*labelptr)) labelptr--;
	  new_label(labelptr+1);
	}
      
      if(*data=='{')  // { -- } sections: add 'em
	{
	  section_t *newsec = new_section(data);
	  
	  newsec->type = st_empty;
	  // find the ending } and save
	  newsec->end = process_find_char(data+1, '}');
	  if(!newsec->end)
	    {                // brace not found
	      rover = data;
	      script_error("section error: no ending brace\n");
	      return NULL;
	    }
	  // continue from the end of the section
	  data = newsec->end;
	}
      data++;
    }

  return NULL;
}