Example #1
0
FILE *
Swig_open(const String_or_char *name) {
    FILE        *f;
    String   *filename;
    List     *spath = 0;
    char        *cname;
    int          i;

    if (!directories) directories = NewList();
    assert(directories);

    cname = Char(name);
    filename = NewString(cname);
    assert(filename);
    f = fopen(Char(filename),"r");
    if (!f) {
        spath = Swig_search_path();
        for (i = 0; i < Len(spath); i++) {
            Clear(filename);
            Printf(filename,"%s%s", Getitem(spath,i), cname);
            f = fopen(Char(filename),"r");
            if (f) break;
        }
        Delete(spath);
    }
    if (f) {
        Delete(lastpath);
        lastpath = Copy(filename);
    }
    Delete(filename);
    return f;
}
Example #2
0
bool wxUIActionSimulator::Select(const wxString& text)
{
    wxWindow* const focus = wxWindow::FindFocus();
    if ( !focus )
        return false;

    // We can only select something in controls inheriting from
    // wxItemContainer, so check that we have it.
#ifdef wxNO_RTTI
    wxItemContainer* container = NULL;

    if ( wxComboBox* combo = wxDynamicCast(focus, wxComboBox) )
        container = combo;
    else if ( wxChoice* choice = wxDynamicCast(focus, wxChoice) )
        container = choice;
    else if ( wxListBox* listbox = wxDynamicCast(focus, wxListBox) )
        container = listbox;
#else // !wxNO_RTTI
    wxItemContainer* const container = dynamic_cast<wxItemContainer*>(focus);
#endif // wxNO_RTTI/!wxNO_RTTI

    if ( !container )
        return false;

    // We prefer to exactly emulate what a (keyboard) user would do, so prefer
    // to emulate selecting the first item of the control if possible (this
    // works with wxChoice, wxListBox and wxComboBox with wxCB_READONLY style
    // under MSW).
    if ( container->GetSelection() != 0 )
    {
        Char(WXK_HOME);
        wxYield();

        // But if this didn't work, set the selection programmatically.
        if ( container->GetSelection() != 0 )
            container->SetSelection(0);
    }

    // And then go down in the control until we reach the item we want.
    for ( ;; )
    {
        if ( container->GetStringSelection() == text )
            return true;

        // We could test if the selection becomes equal to its maximal value
        // (i.e. GetCount() - 1), but if, for some reason, pressing WXK_DOWN
        // doesn't move it, this would still result in an infinite loop, so
        // check that the selection changed for additional safety.
        const int current = container->GetSelection();

        Char(WXK_DOWN);
        wxYield();

        if ( container->GetSelection() == current )
            break;
    }

    return false;
}
Example #3
0
void Scanner_pushtoken(Scanner *s, int nt, const_String_or_char_ptr val) {
  assert(s);
  assert((nt >= 0) && (nt < SWIG_MAXTOKENS));
  s->nexttoken = nt;
  if ( Char(val) != Char(s->text) ) {
    Clear(s->text);
    Append(s->text,val);
  }
}
ReBackReferenceGroupExprNode* ReSyntaxTreeBuilder::BackReference()
{
	ReBackReferenceGroupExprNode* res = ReNodeFactory<ReBackReferenceGroupExprNode>().Create();
	if (!tokenizer.NextIfMatch(__R('('))){ ReportError("Leak parentheses in backref"); delete res; return nullptr; }
	if (!tokenizer.NextIfMatch(__R('<'))){ ReportError("Leak parentheses in backref"); delete res; return nullptr; }
	if (!tokenizer.NextIfMatch(__R('#'))){ ReportError("Leak # in backref"); delete res; return nullptr; }

	if (!tokenizer.IsPosAlpha()){ ReportError("BackReference Without Name");  delete res; return nullptr; }

	while (!tokenizer.Finish() && tokenizer.IsPosAlpha())
	{
		ReCharExprNode* tmp;
		Char(tmp);
		res->AddCharsToName(tmp);
		delete tmp;
	}

	//找到对应的Captured Group
	ReCapturedGroupExprNode* _CNode = FindCapturedGroupByName(res->name, GetRoot());
	if (_CNode == nullptr)//没有找到,报错
	{
		ReportError("No corresponsible captured group");
		delete res; 
		return nullptr;
	}
	else	//找到了,用找到的node的Regular Expression来构造语法数,并且连接
	{
		res->AddLeftChild(BuildChildReTree(_CNode->regularExpression));
	}

	if (!tokenizer.NextIfMatch(__R('>'))){ ReportError("Leak > in backref"); delete res; return nullptr; }
	if (!tokenizer.NextIfMatch(__R(')'))){ ReportError("Leak parentheses in backref"); delete res; return nullptr; }

	return res;
}
Example #5
0
DOHString *
DohNewStringWithSize(const DOH *so, int len)
{
    int l = 0, max;
    String *str;
    char *s;
    if (DohCheck(so)) s = Char(so);
    else s = (char *) so;
    str = (String *) DohMalloc(sizeof(String));
    str->hashkey = -1;
    str->sp = 0;
    str->line = 1;
    str->file = 0;
    max = INIT_MAXSIZE;
    if (s) {
      l = (int) len;
      if ((l+1) > max) max = l+1;
    }
    str->str = (char *) DohMalloc(max);
    str->maxsize = max;
    if (s) {
	strncpy(str->str,s,len);
	str->len = l;
	str->sp = l;
    } else {
	str->str[0] = 0;
	str->len = 0;
    }
    return DohObjMalloc(&DohStringType,str);
}
Example #6
0
static QVector<Char*> qWinCmdLine(Char *cmdParam, int length, int &argc)
{
    QVector<Char*> argv(8);
    Char *p = cmdParam;
    Char *p_end = p + length;

    argc = 0;

    while (*p && p < p_end) {                                // parse cmd line arguments
        while (QChar((short)(*p)).isSpace())                          // skip white space
            p++;
        if (*p && p < p_end) {                                // arg starts
            int quote;
            Char *start, *r;
            if (*p == Char('\"') || *p == Char('\'')) {        // " or ' quote
                quote = *p;
                start = ++p;
            } else {
                quote = 0;
                start = p;
            }
            r = start;
            while (*p && p < p_end) {
                if (quote) {
                    if (*p == quote) {
                        p++;
                        if (QChar((short)(*p)).isSpace())
                            break;
                        quote = 0;
                    }
                }
                if (*p == '\\') {                // escape char?
                    p++;
                    if (*p == Char('\"') || *p == Char('\''))
                        ;                        // yes
                    else
                        p--;                        // treat \ literally
                } else {
                    if (!quote && (*p == Char('\"') || *p == Char('\''))) {        // " or ' quote
                        quote = *p++;
                        continue;
                    } else if (QChar((short)(*p)).isSpace() && !quote)
                        break;
                }
                if (*p)
                    *r++ = *p++;
            }
            if (*p && p < p_end)
                p++;
            *r = Char('\0');

            if (argc >= (int)argv.size()-1)        // expand array
                argv.resize(argv.size()*2);
            argv[argc++] = start;
        }
    }
    argv[argc] = nullptr;

    return argv;
}
DOHString *DohNewStringf(const DOHString_or_char *fmt, ...) {
  va_list ap;
  DOH *r;
  va_start(ap, fmt);
  r = NewStringEmpty();
  DohvPrintf(r, Char(fmt), ap);
  va_end(ap);
  return (DOHString *) r;
}
Example #8
0
char *
Swig_file_basename(const String_or_char *filename)
{
    static char tmp[1024];
    char *c;
    strcpy(tmp,Char(filename));
    c = Swig_file_suffix(tmp);
    *c = 0;
    return tmp;
}
static int String_replace(DOH *stro, const DOHString_or_char *token, const DOHString_or_char *rep, int flags) {
  int count = -1;
  String *str = (String *) ObjData(stro);

  if (flags & DOH_REPLACE_FIRST)
    count = 1;

  if (flags & DOH_REPLACE_ID_END) {
    return replace_simple(str, Char(token), Char(rep), flags, count, match_identifier_end);
  } else if (flags & DOH_REPLACE_ID_BEGIN) {
    return replace_simple(str, Char(token), Char(rep), flags, count, match_identifier_begin);
  } else if (flags & DOH_REPLACE_ID) {
    return replace_simple(str, Char(token), Char(rep), flags, count, match_identifier);
  } else if (flags & DOH_REPLACE_NUMBER_END) {
    return replace_simple(str, Char(token), Char(rep), flags, count, match_number_end);
  } else {
    return replace_simple(str, Char(token), Char(rep), flags, count, match_simple);
  }
}
Example #10
0
/* -----------------------------------------------------------------------------
 * Swig_file_filename()
 *
 * Return the file with any leading path stripped off
 * ----------------------------------------------------------------------------- */
char *
Swig_file_filename(const String_or_char *filename)
{
    static char tmp[1024];
    const char *delim = SWIG_FILE_DELIMETER;
    char *c;

    strcpy(tmp,Char(filename));
    if ((c=strrchr(tmp,*delim))) return c+1;
    else return tmp;
}
Example #11
0
bool wxUIActionSimulator::Text(const char *s)
{
    while ( *s != '\0' )
    {
        const char ch = *s++;
        if ( !Char(ch, isupper(ch) ? wxMOD_SHIFT : 0) )
            return false;
    }

    return true;
}
Example #12
0
DOH *DohGetFlagAttr(DOH *obj, const DOH *name) {
  DOH *val = Getattr(obj, (DOH *) name);
  if (!val) {
    return NULL;
  } else {
    const char *cval = Char(val);
    if (!cval)
      return val;
    return (strcmp(cval, "0") != 0) ? val : NULL;
  }
}
Example #13
0
char *
Swig_file_suffix(const String_or_char *filename) {
    char *d;
    char *c = Char(filename);
    if (strlen(c)) {
        d = c + Len(filename) - 1;
        while (d != c) {
            if (*d == '.') return d;
            d--;
        }
        return c+Len(filename);
    }
    return c;
}
Example #14
0
void ReSyntaxTreeBuilder::NamedGroupConstraint(ReCapturedGroupExprNode* _Node)
{
	if (!tokenizer.NextIfMatch(__R('<'))){ ReportError("No < in a named group"); return; }

	while (!tokenizer.Finish() && !tokenizer.Match(__R('>')))
	{
		ReCharExprNode* tmp;
		Char(tmp);
		_Node->AddCharsToName(tmp);
		delete tmp;
	}

	if (!tokenizer.NextIfMatch(__R('>'))){ ReportError("No > in a named group"); return; }
}
Example #15
0
Any x1x_f ( Any a0 ){
  Any a2 = Int(0);
  Any a1 = a2;
  int count = a0[0];
  loop_start_label114: ;
  if(count == a0[1]){ goto label114; }
  Any a4 = Char( a0[count] );
  count++;
  Any a7 = wyce_add( a1 , a4);
  a1 = a7;
  goto loop_start_label114;
  label114: ;
  return a1;
}
Example #16
0
/* -----------------------------------------------------------------------------
 * retract()
 *
 * Retract n characters
 * ----------------------------------------------------------------------------- */
static void retract(Scanner *s, int n) {
  int i, l;
  char *str;

  str = Char(s->text);
  l = Len(s->text);
  assert(n <= l);
  for (i = 0; i < n; i++) {
    if (str[l - 1] == '\n') {
      if (!s->freeze_line) s->line--;
    }
    (void)Seek(s->str, -1, SEEK_CUR);
    Delitem(s->text, DOH_END);
  }
}
Example #17
0
void ReSyntaxTreeBuilder::SelectionContent(ReSelectionExprNode* _Node)
{
	ReCharExprNode* node;

	Char(node);
	_Node->AddChars(node);		//记住对于Selection来说,Chars里面的东西全是成对出现的,就算不是a-z这样的形式,也是a-a这样的

	if (tokenizer.Match(__R('-')))
	{
		tokenizer.Next();
		Char(node);
		_Node->AddChars(node);
	}
	else
	{
		_Node->AddChars(new ReCharExprNode(*node));
	}
	if (!tokenizer.Match(__R(']')))
	{
		SelectionContent(_Node);
	}

	return;
}
Example #18
0
/* -----------------------------------------------------------------------------
 * Swig_file_dirname()
 *
 * Return the name of the directory associated with a file
 * ----------------------------------------------------------------------------- */
char *
Swig_file_dirname(const String_or_char *filename)
{
    static char tmp[1024];
    const char *delim = SWIG_FILE_DELIMETER;
    char *c;
    strcpy(tmp,Char(filename));
    if (!strstr(tmp,delim)) {
        return "";
    }
    c = tmp + strlen(tmp) -1;
    while (*c != *delim) c--;
    *(++c) = 0;
    return tmp;
}
Example #19
0
Any x1x_codeLength ( Attribute a0 ){
  if(a0.type == ){ goto label370; };
  label377: ;
  goto label371;
  label370: ;
  Any a1 = a0.data;
  int count = 0;
  loop_start_label372: ;
  if(count == a1.i )){ goto label372; }
  Any a2 = Char( a1[count] );
  count++;
  label375: ;
  if(a2.type == ){ goto label373; };
  if( !a2.type == ){ goto label374; };
  Any a3 = a2.type;
  label374: ;
  if( !a3.type == INT_TYPE){ goto label375; };
  label373: ;
Example #20
0
char *Wrapper_new_local(Wrapper *w, const_String_or_char_ptr name, const_String_or_char_ptr decl) {
  int i;
  String *nname = NewString(name);
  String *ndecl = NewString(decl);
  char *ret;

  i = 0;

  while (Wrapper_check_local(w, nname)) {
    Clear(nname);
    Printf(nname, "%s%d", name, i);
    i++;
  }
  Replace(ndecl, name, nname, DOH_REPLACE_ID);
  Setattr(w->localh, nname, ndecl);
  Printf(w->locals, "%s;\n", ndecl);
  ret = Char(nname);
  Delete(nname);
  Delete(ndecl);
  return ret;			/* Note: nname should still exists in the w->localh hash */
}
Example #21
0
void Lexer::ProcessTokens()
{
    Character Char(NULL, NULL, NULL, NULL, NULL);
    Char = scanner.GetChar();
    token = Token(Char, &scanner, NULL);

    while (true)
    {
        char prevToken[256];
        token.GetType(prevToken);

        if (strcmp(prevToken, WHITESPACE))
            AddToTree(token);

        Char = scanner.GetChar();
        if (Char.cargo == ENDMARK)
            break;

        token = Token(Char, &scanner, prevToken);
    }
}
Example #22
0
String *Swig_cresult(SwigType *t, const_String_or_char_ptr name, const_String_or_char_ptr decl) {
    String *fcall;

    fcall = NewStringEmpty();
    switch (SwigType_type(t)) {
    case T_VOID:
        break;
    case T_REFERENCE:
    {
        String *lstr = SwigType_lstr(t, 0);
        Printf(fcall, "%s = (%s) &", name, lstr);
        Delete(lstr);
    }
    break;
    case T_USER:
        Printf(fcall, "%s = ", name);
        break;

    default:
        /* Normal return value */
    {
        String *lstr = SwigType_lstr(t, 0);
        Printf(fcall, "%s = (%s)", name, lstr);
        Delete(lstr);
    }
    break;
    }

    /* Now print out function call */
    Append(fcall, decl);

    /* A sick hack */
    {
        char *c = Char(decl) + Len(decl) - 1;
        if (!((*c == ';') || (*c == '}')))
            Append(fcall, ";");
    }

    return fcall;
}
Example #23
0
File: file.c Project: 0xb1dd1e/swig
DOH *DohNewFile(DOH *filename, const char *mode, DOHList *newfiles) {
  DohFile *f;
  FILE *file;
  char *filen;

  filen = Char(filename);
  file = fopen(filen, mode);
  if (!file)
    return 0;

  f = (DohFile *) DohMalloc(sizeof(DohFile));
  if (!f) {
    fclose(file);
    return 0;
  }
  if (newfiles)
    Append(newfiles, filename);
  f->filep = file;
  f->fd = 0;
  f->closeondel = 1;
  return DohObjMalloc(&DohFileType, f);
}
Example #24
0
void Scanner_locator(Scanner *s, String *loc) {
  static Locator *locs = 0;
  static int expanding_macro = 0;

  if (!follow_locators) {
    if (Equal(loc, "/*@SWIG@*/")) {
      /* End locator. */
      if (expanding_macro)
	--expanding_macro;
    } else {
      /* Begin locator. */
      ++expanding_macro;
    }
    /* Freeze line number processing in Scanner */
    freeze_line(s,expanding_macro);
  } else {
    int c;
    Locator *l;
    (void)Seek(loc, 7, SEEK_SET);
    c = Getc(loc);
    if (c == '@') {
      /* Empty locator.  We pop the last location off */
      if (locs) {
	Scanner_set_location(s, locs->filename, locs->line_number);
	cparse_file = locs->filename;
	cparse_line = locs->line_number;
	l = locs->next;
	free(locs);
	locs = l;
      }
      return;
    }

    /* We're going to push a new location */
    l = (Locator *) malloc(sizeof(Locator));
    l->filename = cparse_file;
    l->line_number = cparse_line;
    l->next = locs;
    locs = l;

    /* Now, parse the new location out of the locator string */
    {
      String *fn = NewStringEmpty();
      /*      Putc(c, fn); */
      
      while ((c = Getc(loc)) != EOF) {
	if ((c == '@') || (c == ','))
	  break;
	Putc(c, fn);
      }
      cparse_file = Swig_copy_string(Char(fn));
      Clear(fn);
      cparse_line = 1;
      /* Get the line number */
      while ((c = Getc(loc)) != EOF) {
	if ((c == '@') || (c == ','))
	  break;
	Putc(c, fn);
      }
      cparse_line = atoi(Char(fn));
      Clear(fn);
      
      /* Get the rest of it */
      while ((c = Getc(loc)) != EOF) {
	if (c == '@')
	  break;
	Putc(c, fn);
      }
      /*  Swig_diagnostic(cparse_file, cparse_line, "Scanner_set_location\n"); */
      Scanner_set_location(s, cparse_file, cparse_line);
      Delete(fn);
    }
  }
}
Example #25
0
static String *Swig_cmethod_call(const_String_or_char_ptr name, ParmList *parms, const_String_or_char_ptr self, String *explicit_qualifier, SwigType *director_type) {
    String *func, *nname;
    int i = 0;
    Parm *p = parms;
    SwigType *pt;
    int comma = 0;

    func = NewStringEmpty();
    if (!p)
        return func;

    if (!self)
        self = (char *) "(this)->";
    Append(func, self);

    if (SwigType_istemplate(name) && (strncmp(Char(name), "operator ", 9) == 0)) {
        /* fix for template + operators and compilers like gcc 3.3.5 */
        String *tprefix = SwigType_templateprefix(name);
        nname = tprefix;
    } else {
        nname = SwigType_namestr(name);
    }

    if (director_type) {
        const char *pname = "darg";
        String *rcaststr = SwigType_rcaststr(director_type, pname);
        Replaceall(func, "this", rcaststr);
        Delete(rcaststr);
    } else {
        pt = Getattr(p, "type");

        /* If the method is invoked through a dereferenced pointer, we don't add any casts
           (needed for smart pointers).  Otherwise, we cast to the appropriate type */

        if (Strstr(func, "*this")) {
            String *pname = Swig_cparm_name(p, 0);
            Replaceall(func, "this", pname);
            Delete(pname);
        } else {
            String *pname = Swig_cparm_name(p, 0);
            String *rcaststr = SwigType_rcaststr(pt, pname);
            Replaceall(func, "this", rcaststr);
            Delete(rcaststr);
            Delete(pname);
        }

        /*
           SWIGTEMPLATEDESIMBUAGATOR is compiler dependent (swiglabels.swg),
           - SUN Studio 9 requires 'template',
           - gcc-3.4 forbids the use of 'template' (correctly implementing the ISO C++ standard)
           the others don't seem to care,
         */
        if (SwigType_istemplate(name))
            Printf(func, "SWIGTEMPLATEDISAMBIGUATOR ");

        if (explicit_qualifier) {
            Printv(func, explicit_qualifier, "::", NIL);
        }
    }

    Printf(func, "%s(", nname);

    i++;
    p = nextSibling(p);
    while (p) {
        pt = Getattr(p, "type");
        if ((SwigType_type(pt) != T_VOID)) {
            String *pname = Swig_cparm_name(p, i);
            String *rcaststr = SwigType_rcaststr(pt, pname);
            if (comma)
                Append(func, ",");
            Append(func, rcaststr);
            Delete(rcaststr);
            Delete(pname);
            comma = 1;
            i++;
        }
        p = nextSibling(p);
    }
    Append(func, ")");
    Delete(nname);
    return func;
}
Example #26
0
int Preprocessor_expr(DOH *s, int *error) {
  int token = 0;
  int op = 0;

  sp = 0;
  assert(s);
  assert(scan);

  Seek(s, 0, SEEK_SET);
  /* Printf(stdout,"evaluating : '%s'\n", s); */
  *error = 0;
  Scanner_clear(scan);
  Scanner_push(scan, s);

  /* Put initial state onto the stack */
  stack[sp].op = EXPR_TOP;
  stack[sp].value = 0;

  while (1) {
    /* Look at the top of the stack */
    switch (stack[sp].op) {
    case EXPR_TOP:
      /* An expression.   Can be a number or another expression enclosed in parens */
      token = expr_token(scan);
      if (!token) {
	errmsg = "Expected an expression";
	*error = 1;
	return 0;
      }
      if ((token == SWIG_TOKEN_INT) || (token == SWIG_TOKEN_UINT) || (token == SWIG_TOKEN_LONG) || (token == SWIG_TOKEN_ULONG)) {
	/* A number.  Reduce EXPR_TOP to an EXPR_VALUE */
	char *c = Char(Scanner_text(scan));
	stack[sp].value = (long) strtol(c, 0, 0);
	stack[sp].svalue = 0;
	/*        stack[sp].value = (long) atol(Char(Scanner_text(scan))); */
	stack[sp].op = EXPR_VALUE;
      } else if (token == SWIG_TOKEN_PLUS) {
      } else if ((token == SWIG_TOKEN_MINUS) || (token == SWIG_TOKEN_LNOT) || (token == SWIG_TOKEN_NOT)) {
	if (token == SWIG_TOKEN_MINUS)
	  token = EXPR_UMINUS;
	stack[sp].value = token;
	stack[sp++].op = EXPR_OP;
	stack[sp].op = EXPR_TOP;
	stack[sp].svalue = 0;
      } else if ((token == SWIG_TOKEN_LPAREN)) {
	stack[sp++].op = EXPR_GROUP;
	stack[sp].op = EXPR_TOP;
	stack[sp].value = 0;
	stack[sp].svalue = 0;
      } else if (token == SWIG_TOKEN_ENDLINE) {
      } else if ((token == SWIG_TOKEN_STRING)) {
	stack[sp].svalue = NewString(Scanner_text(scan));
	stack[sp].op = EXPR_VALUE;
      } else if ((token == SWIG_TOKEN_ID)) {
	stack[sp].value = 0;
	stack[sp].svalue = 0;
	stack[sp].op = EXPR_VALUE;
      } else
	goto syntax_error;
      break;
    case EXPR_VALUE:
      /* A value is on the stack.   We may reduce or evaluate depending on what the next token is */
      token = expr_token(scan);
      if (!token) {
	/* End of input. Might have to reduce if an operator is on stack */
	while (sp > 0) {
	  if (stack[sp - 1].op == EXPR_OP) {
	    if (!reduce_op())
	      goto reduce_error;
	  } else if (stack[sp - 1].op == EXPR_GROUP) {
	    errmsg = "Missing \')\'";
	    *error = 1;
	    return 0;
	  } else
	    goto syntax_error;
	}
	return stack[sp].value;
      }
      /* Token must be an operator */
      switch (token) {
      case SWIG_TOKEN_STAR:
      case SWIG_TOKEN_EQUALTO:
      case SWIG_TOKEN_NOTEQUAL:
      case SWIG_TOKEN_PLUS:
      case SWIG_TOKEN_MINUS:
      case SWIG_TOKEN_AND:
      case SWIG_TOKEN_LAND:
      case SWIG_TOKEN_OR:
      case SWIG_TOKEN_LOR:
      case SWIG_TOKEN_XOR:
      case SWIG_TOKEN_LESSTHAN:
      case SWIG_TOKEN_GREATERTHAN:
      case SWIG_TOKEN_LTEQUAL:
      case SWIG_TOKEN_GTEQUAL:
      case SWIG_TOKEN_SLASH:
      case SWIG_TOKEN_PERCENT:
      case SWIG_TOKEN_LSHIFT:
      case SWIG_TOKEN_RSHIFT:
	if ((sp == 0) || (stack[sp - 1].op == EXPR_GROUP)) {
	  /* No possibility of reduce. Push operator and expression */
	  sp++;
	  stack[sp].op = EXPR_OP;
	  stack[sp].value = token;
	  sp++;
	  stack[sp].op = EXPR_TOP;
	  stack[sp].value = 0;
	} else {
	  if (stack[sp - 1].op != EXPR_OP)
	    goto syntax_error_expected_operator;
	  op = stack[sp - 1].value;	/* Previous operator */

	  /* Now, depending on the precedence relationship between the last operator and the current
	     we will reduce or push */

	  if (prec[op] <= prec[token]) {
	    /* Reduce the previous operator */
	    if (!reduce_op())
	      goto reduce_error;
	  }
	  sp++;
	  stack[sp].op = EXPR_OP;
	  stack[sp].value = token;
	  sp++;
	  stack[sp].op = EXPR_TOP;
	  stack[sp].value = 0;
	}
	break;
      case SWIG_TOKEN_RPAREN:
	if (sp == 0)
	  goto extra_rparen;

	/* Might have to reduce operators first */
	while ((sp > 0) && (stack[sp - 1].op == EXPR_OP)) {
	  if (!reduce_op())
	    goto reduce_error;
	}
	if ((sp == 0) || (stack[sp - 1].op != EXPR_GROUP))
	  goto extra_rparen;
	stack[sp - 1].op = EXPR_VALUE;
	stack[sp - 1].value = stack[sp].value;
	sp--;
	break;
      default:
	goto syntax_error_expected_operator;
	break;
      }
      break;

    default:
      fprintf(stderr, "Internal error in expression evaluator.\n");
      abort();
    }
  }

syntax_error:
  errmsg = "Syntax error";
  *error = 1;
  return 0;

syntax_error_expected_operator:
  errmsg = "Syntax error: expected operator";
  *error = 1;
  return 0;

reduce_error:
  /*  errmsg has been set by reduce_op */
  *error = 1;
  return 0;

extra_rparen:
  errmsg = "Extra \')\'";
  *error = 1;
  return 0;
}
Example #27
0
void Lex::Next()
{
	grounding = false;
	while((byte)*ptr <= ' ') {
		if(*ptr == '\2')
			grounding = true;
		if(*ptr == '\0') return;
		ptr++;
	}
	pos = ptr;
	int c = (byte)*ptr++;
	if(c == '\0') return;
	switch(c) {
	case_id: {
			String x;
			x.Reserve(12);
			x.Cat(c);
			while(iscid(*ptr))
				x.Cat(*ptr++);
			int q = id.FindAdd(x);
			if(q == tk_rval_ - 256) { // simple hack for transitionary macro
				AddCode('&');
				AddCode('&');
			}
			else
				AddCode(q + 256);
			break;
		}
	case ':': AddCode(Char(':') ? t_dblcolon : ':'); break;
	case '*': AssOp('*', t_mulass); break;
	case '/': AssOp('/', t_divass); break;
	case '%': AssOp('%', t_modass); break;
	case '^': AssOp('^', t_xorass); break;
	case '!': AssOp('!', t_neq); break;
	case '.':
		if(Char('*')) AddCode(t_dot_asteriks);
		else
		if(*ptr == '.' && ptr[1] == '.') {
			AddCode(t_elipsis);
			ptr += 2;
		}
		else
			AddCode('.');
		break;
	case '+':
		if(Char('+')) AddCode(t_inc);
		else
			AssOp('+', t_addass);
		return;
	case '-':
		if(Char('-')) AddCode(t_dec);
		else
		if(Char('>'))
			AddCode(Char('*') ? t_arrow_asteriks : t_arrow);
		else
			AssOp('-', t_subass);
		break;
	case '&':
		if(Char('&'))
			AddCode(t_and);
		else
			AssOp('&', t_andass);
		break;
	case '|':
		if(Char('|'))
			AddCode(t_or);
		else
			AssOp('|', t_orass);
		break;
	case '=':
		AssOp('=', t_eq);
		break;
	case '<':
		if(Char('<'))
			AssOp(t_shl, t_shlass);
		else
			AssOp('<', t_le);
		break;
	case '>':
		if(Char('>'))
			AssOp(t_shr, t_shrass);
		else
			AssOp('>', t_ge);
		break;
	case '0': {
			dword w = 0;
			if(Char('x') || Char('X')) {
				for(;;) {
					int d;
					if(*ptr >= '0' && *ptr <= '9')
						d = *ptr - '0';
					else
					if(*ptr >= 'A' && *ptr <= 'F')
						d = *ptr - 'A' + 10;
					else
					if(*ptr >= 'a' && *ptr <= 'f')
						d = *ptr - 'a' + 10;
					else
						break;
					if(w >= 0x8000000u - d) {
						AddCode(te_integeroverflow);
						return;
					}
					w = w * 16 + d - '0';
					ptr++;
				}
			}
			else
				while(*ptr >= '0' && *ptr <= '7') {
					int d = *ptr++ - '0';
					if(w >= 0x1000000u - d) {
						AddCode(te_integeroverflow);
						return;
					}
					w = w * 8 + d - '0';
				}
			Term& tm = term.AddTail();
			tm.code = t_integer;
			tm.ptr = pos;
			tm.number = w;
		}
		break;
	case_nonzero_digit: {
			double w = c - '0';
			bool fp = false;
			while(*ptr >= '0' && *ptr <= '9')
				w = w * 10 + *ptr++ - '0';
			if(*ptr == '.') { //TODO TO BE Completed !!!
				fp = true;
				ptr++;
				double x = 0.1;
				while(*ptr >= '0' && *ptr <= '9') {
					w += x * (*ptr++ - '0');
					x /= 10;
				}
			}
			Term& tm = term.AddTail();
			if(fp || w < INT_MIN || w > INT_MAX)
				tm.code = t_double;
			else
				tm.code = t_integer;
			tm.ptr = pos;
			tm.number = w;
		}
		break;
	case '\'': {
			Term& tm = term.AddTail();
			tm.code = t_character;
			tm.ptr = pos;
			tm.text = String(GetCharacter(), 1);
			if(*ptr == '\'')
				ptr++;
			else
				tm.code = te_badcharacter;
		}
		break;
	case '\"': {
			Term& tm = term.AddTail();
			tm.code = t_string;
			tm.ptr = pos;
			for(;;) {
				while(*ptr != '\"') {
					if((byte)*ptr < ' ' && *ptr != 9) {
						tm.code = te_badstring;
						return;
					}
					tm.text.Cat(GetCharacter());
				}
				ptr++;
				while(*ptr && (byte)*ptr <= ' ') ptr++;
				if(*ptr != '\"') break;
				ptr++;
			}
		}
		break;
	default:
		AddCode(c);
		return;
	}
}
Example #28
0
void Wrapper_pretty_print(String *str, File *f) {
  String *ts;
  int level = 0;
  int c, i;
  int empty = 1;
  int indent = 2;
  int plevel = 0;
  int label = 0;

  ts = NewStringEmpty();
  Seek(str, 0, SEEK_SET);
  while ((c = Getc(str)) != EOF) {
    if (c == '\"') {
      Putc(c, ts);
      while ((c = Getc(str)) != EOF) {
	if (c == '\\') {
	  Putc(c, ts);
	  c = Getc(str);
	}
	Putc(c, ts);
	if (c == '\"')
	  break;
      }
      empty = 0;
    } else if (c == '\'') {
      Putc(c, ts);
      while ((c = Getc(str)) != EOF) {
	if (c == '\\') {
	  Putc(c, ts);
	  c = Getc(str);
	}
	Putc(c, ts);
	if (c == '\'')
	  break;
      }
      empty = 0;
    } else if (c == ':') {
      Putc(c, ts);
      if ((c = Getc(str)) == '\n') {
	if (!empty && !strchr(Char(ts), '?'))
	  label = 1;
      }
      Ungetc(c, str);
    } else if (c == '(') {
      Putc(c, ts);
      plevel += indent;
      empty = 0;
    } else if (c == ')') {
      Putc(c, ts);
      plevel -= indent;
      empty = 0;
    } else if (c == '{') {
      Putc(c, ts);
      Putc('\n', ts);
      for (i = 0; i < level; i++)
	Putc(' ', f);
      Printf(f, "%s", ts);
      Clear(ts);
      level += indent;
      while ((c = Getc(str)) != EOF) {
	if (!isspace(c)) {
	  Ungetc(c, str);
	  break;
	}
      }
      empty = 0;
    } else if (c == '}') {
      if (!empty) {
	Putc('\n', ts);
	for (i = 0; i < level; i++)
	  Putc(' ', f);
	Printf(f, "%s", ts);
	Clear(ts);
      }
      level -= indent;
      Putc(c, ts);
      empty = 0;
    } else if (c == '\n') {
      Putc(c, ts);
      empty = 0;
      if (!empty) {
	int slevel = level;
	if (label && (slevel >= indent))
	  slevel -= indent;
	if ((Char(ts))[0] != '#') {
	  for (i = 0; i < slevel; i++)
	    Putc(' ', f);
	}
	Printf(f, "%s", ts);
	for (i = 0; i < plevel; i++)
	  Putc(' ', f);
      }
      Clear(ts);
      label = 0;
      empty = 1;
    } else if (c == '/') {
      empty = 0;
      Putc(c, ts);
      c = Getc(str);
      if (c != EOF) {
	Putc(c, ts);
	if (c == '/') {		/* C++ comment */
	  while ((c = Getc(str)) != EOF) {
	    if (c == '\n') {
	      Ungetc(c, str);
	      break;
	    }
	    Putc(c, ts);
	  }
	} else if (c == '*') {	/* C comment */
	  int endstar = 0;
	  while ((c = Getc(str)) != EOF) {
	    if (endstar && c == '/') {	/* end of C comment */
	      Putc(c, ts);
	      break;
	    }
	    endstar = (c == '*');
	    Putc(c, ts);
	    if (c == '\n') {	/* multi-line C comment. Could be improved slightly. */
	      for (i = 0; i < level; i++)
		Putc(' ', ts);
	    }
	  }
	}
      }
    } else {
      if (!empty || !isspace(c)) {
	Putc(c, ts);
	empty = 0;
      }
    }
  }
  if (!empty)
    Printf(f, "%s", ts);
  Delete(ts);
  Printf(f, "\n");
}
Example #29
0
void TTFFont::addChar(uint32 c) {
	std::map<uint32, Char>::iterator cC = _chars.find(c);
	if (cC != _chars.end())
		return;

	if (!_ttf->hasChar(c))
		return;

	try {

		uint32 cWidth = _ttf->getCharWidth(c);
		if (cWidth > kPageWidth)
			return;

		if (_pages.empty())
			_pages.push_back(new Page);

		if (_pages.back()->widthLeft < cWidth) {
			// The current character doesn't fit into the current line

			if (_pages.back()->heightLeft >= _height) {
				// Create a new line

				_pages.back()->curX  = 0;
				_pages.back()->curY += _height;

				_pages.back()->heightLeft -= _height;
				_pages.back()->widthLeft   = kPageWidth;

			} else {
				// Create a new page

				_pages.push_back(new Page);
				_pages.back()->heightLeft -= _height;
			}

		}

		_ttf->drawCharacter(c, *_pages.back()->surface, _pages.back()->curX, _pages.back()->curY);

		std::pair<std::map<uint32, Char>::iterator, bool> result;

		result = _chars.insert(std::make_pair(c, Char()));

		cC = result.first;

		Char &ch   = cC->second;
		Page &page = *_pages.back();

		ch.width = cWidth;
		ch.page  = _pages.size() - 1;

		ch.vX[0] = 0.00;   ch.vY[0] = 0.00;
		ch.vX[1] = cWidth; ch.vY[1] = 0.00;
		ch.vX[2] = cWidth; ch.vY[2] = _height;
		ch.vX[3] = 0.00;   ch.vY[3] = _height;

		const float tX = (float) page.curX / (float) kPageWidth;
		const float tY = (float) page.curY / (float) kPageHeight;
		const float tW = (float) cWidth    / (float) kPageWidth;
		const float tH = (float) _height   / (float) kPageHeight;

		ch.tX[0] = tX;      ch.tY[0] = tY + tH;
		ch.tX[1] = tX + tW; ch.tY[1] = tY + tH;
		ch.tX[2] = tX + tW; ch.tY[2] = tY;
		ch.tX[3] = tX;      ch.tY[3] = tY;

		_pages.back()->widthLeft  -= cWidth;
		_pages.back()->curX       += cWidth;
		_pages.back()->needRebuild = true;

	} catch (Common::Exception &e) {
		if (cC != _chars.end())
			_chars.erase(cC);

		Common::printException(e);
	}
}
Example #30
0
ReSyntaxExprNode* ReSyntaxTreeBuilder::Factor()
{
	ReSyntaxExprNode* res;
	if (tokenizer.Match(__R('(')))
	{
		if ((tokenizer.Match(__R('<'), 1)
			|| tokenizer.Match(__R('?'), 1))
			&& (tokenizer.Match(__R('='), 2)
			|| tokenizer.Match(__R('!'), 2))
			)
		{
			res =  LookAround();
		}
		else if (tokenizer.Match(__R('<'), 1)
			&& (tokenizer.IsPosDigital(2)
			|| tokenizer.Match(__R('$'), 2)))
		{
			res = BackTracedGroup();
			Quantifier(res);
		}
		else if (tokenizer.Match(__R('<'), 1)
			&& (tokenizer.IsPosDigital(2)
			|| tokenizer.Match(__R('#'), 2)))
		{
			res = BackReference();
			Quantifier(res);
		}
		else //只能通过左括号判断捕获列表
		{
			res = CapturedGroup();
			Quantifier(res);
		}
	}
	else if (tokenizer.Match(__R('[')))
	{
		if (tokenizer.Match(__R('^'), 1))
		{
			res = NoSelection();
			Quantifier(res);
		}
		else
		{
			res = Selection();
			Quantifier(res);
		}

	}
	else if (tokenizer.Finish())
	{
		return nullptr;
	}
	else if (!tokenizer.IsPosSpecial())
	{
		ReCharExprNode* tmp = nullptr;
		Char(tmp);
		res = tmp;
		Quantifier(res);
	}
	else
	{
		return nullptr;
	}
	return res;
}