示例#1
0
int Scanner::scan()
{
    char *cursor = cur;
    uint depth;

scan:
    tchar = cursor - pos;
    tline = cline;
    tok = cursor;
	if (iscfg == 1)
	{
		goto config;
	}
	else if (iscfg == 2)
	{
   		goto value;
    }

#line 281 "<stdout>"
{
	YYCTYPE yych;
	unsigned int yyaccept = 0;
	if ((YYLIMIT - YYCURSOR) < 5) YYFILL(5);
	yych = *YYCURSOR;
	switch (yych) {
	case '\t':
	case ' ':	goto yy50;
	case '\n':	goto yy52;
	case '\r':	goto yy54;
	case '"':	goto yy37;
	case '\'':	goto yy39;
	case '(':
	case ')':
	case ';':
	case '=':
	case '\\':
	case '|':	goto yy43;
	case '*':	goto yy35;
	case '+':
	case '?':	goto yy44;
	case '.':	goto yy48;
	case '/':	goto yy33;
	case 'A':
	case 'B':
	case 'C':
	case 'D':
	case 'E':
	case 'F':
	case 'G':
	case 'H':
	case 'I':
	case 'J':
	case 'K':
	case 'L':
	case 'M':
	case 'N':
	case 'O':
	case 'P':
	case 'Q':
	case 'R':
	case 'S':
	case 'T':
	case 'U':
	case 'V':
	case 'W':
	case 'X':
	case 'Y':
	case 'Z':
	case 'a':
	case 'b':
	case 'c':
	case 'd':
	case 'e':
	case 'f':
	case 'g':
	case 'h':
	case 'i':
	case 'j':
	case 'k':
	case 'l':
	case 'm':
	case 'n':
	case 'o':
	case 'p':
	case 'q':
	case 's':
	case 't':
	case 'u':
	case 'v':
	case 'w':
	case 'x':
	case 'y':
	case 'z':	goto yy47;
	case '[':	goto yy41;
	case 'r':	goto yy45;
	case '{':	goto yy31;
	default:	goto yy56;
	}
yy31:
	yyaccept = 0;
	yych = *(YYMARKER = ++YYCURSOR);
	switch (yych) {
	case ',':	goto yy97;
	case '0':	goto yy94;
	case '1':
	case '2':
	case '3':
	case '4':
	case '5':
	case '6':
	case '7':
	case '8':
	case '9':	goto yy95;
	default:	goto yy32;
	}
yy32:
#line 166 "scanner.re"
	{ depth = 1;
				  goto code;
				}
#line 383 "<stdout>"
yy33:
	++YYCURSOR;
	switch ((yych = *YYCURSOR)) {
	case '*':	goto yy92;
	default:	goto yy34;
	}
yy34:
#line 196 "scanner.re"
	{ RETURN(*tok); }
#line 393 "<stdout>"
yy35:
	++YYCURSOR;
	switch ((yych = *YYCURSOR)) {
	case '/':	goto yy90;
	default:	goto yy36;
	}
yy36:
#line 198 "scanner.re"
	{ yylval.op = *tok;
				  RETURN(CLOSE); }
#line 404 "<stdout>"
yy37:
	yyaccept = 1;
	yych = *(YYMARKER = ++YYCURSOR);
	switch (yych) {
	case '\n':	goto yy38;
	default:	goto yy86;
	}
yy38:
#line 183 "scanner.re"
	{ fatal("unterminated string constant (missing \")"); }
#line 415 "<stdout>"
yy39:
	yyaccept = 2;
	yych = *(YYMARKER = ++YYCURSOR);
	switch (yych) {
	case '\n':	goto yy40;
	default:	goto yy81;
	}
yy40:
#line 184 "scanner.re"
	{ fatal("unterminated string constant (missing ')"); }
#line 426 "<stdout>"
yy41:
	yyaccept = 3;
	yych = *(YYMARKER = ++YYCURSOR);
	switch (yych) {
	case '\n':	goto yy42;
	case '^':	goto yy72;
	default:	goto yy71;
	}
yy42:
#line 194 "scanner.re"
	{ fatal("unterminated range (missing ])"); }
#line 438 "<stdout>"
yy43:
	yych = *++YYCURSOR;
	goto yy34;
yy44:
	yych = *++YYCURSOR;
	goto yy36;
yy45:
	++YYCURSOR;
	switch ((yych = *YYCURSOR)) {
	case 'e':	goto yy62;
	default:	goto yy61;
	}
yy46:
#line 225 "scanner.re"
	{ cur = cursor;
				  yylval.symbol = Symbol::find(token());
				  return ID; }
#line 456 "<stdout>"
yy47:
	yych = *++YYCURSOR;
	goto yy61;
yy48:
	++YYCURSOR;
#line 229 "scanner.re"
	{ cur = cursor;
				  yylval.regexp = mkDot();
				  return RANGE;
				}
#line 467 "<stdout>"
yy50:
	++YYCURSOR;
	yych = *YYCURSOR;
	goto yy59;
yy51:
#line 234 "scanner.re"
	{ goto scan; }
#line 475 "<stdout>"
yy52:
	++YYCURSOR;
yy53:
#line 236 "scanner.re"
	{ if(cursor == eof) RETURN(0);
				  pos = cursor; cline++;
				  goto scan;
	    			}
#line 484 "<stdout>"
yy54:
	++YYCURSOR;
	switch ((yych = *YYCURSOR)) {
	case '\n':	goto yy57;
	default:	goto yy55;
	}
yy55:
#line 241 "scanner.re"
	{ std::ostringstream msg;
				  msg << "unexpected character: ";
				  prtChOrHex(msg, *tok);
				  fatal(msg.str().c_str());
				  goto scan;
				}
#line 499 "<stdout>"
yy56:
	yych = *++YYCURSOR;
	goto yy55;
yy57:
	yych = *++YYCURSOR;
	goto yy53;
yy58:
	++YYCURSOR;
	if (YYLIMIT <= YYCURSOR) YYFILL(1);
	yych = *YYCURSOR;
yy59:
	switch (yych) {
	case '\t':
	case ' ':	goto yy58;
	default:	goto yy51;
	}
yy60:
	++YYCURSOR;
	if (YYLIMIT <= YYCURSOR) YYFILL(1);
	yych = *YYCURSOR;
yy61:
	switch (yych) {
	case '0':
	case '1':
	case '2':
	case '3':
	case '4':
	case '5':
	case '6':
	case '7':
	case '8':
	case '9':
	case 'A':
	case 'B':
	case 'C':
	case 'D':
	case 'E':
	case 'F':
	case 'G':
	case 'H':
	case 'I':
	case 'J':
	case 'K':
	case 'L':
	case 'M':
	case 'N':
	case 'O':
	case 'P':
	case 'Q':
	case 'R':
	case 'S':
	case 'T':
	case 'U':
	case 'V':
	case 'W':
	case 'X':
	case 'Y':
	case 'Z':
	case 'a':
	case 'b':
	case 'c':
	case 'd':
	case 'e':
	case 'f':
	case 'g':
	case 'h':
	case 'i':
	case 'j':
	case 'k':
	case 'l':
	case 'm':
	case 'n':
	case 'o':
	case 'p':
	case 'q':
	case 'r':
	case 's':
	case 't':
	case 'u':
	case 'v':
	case 'w':
	case 'x':
	case 'y':
	case 'z':	goto yy60;
	default:	goto yy46;
	}
yy62:
	yych = *++YYCURSOR;
	switch (yych) {
	case '2':	goto yy63;
	default:	goto yy61;
	}
yy63:
	yych = *++YYCURSOR;
	switch (yych) {
	case 'c':	goto yy64;
	default:	goto yy61;
	}
yy64:
	yyaccept = 4;
	yych = *(YYMARKER = ++YYCURSOR);
	switch (yych) {
	case ':':	goto yy65;
	default:	goto yy61;
	}
yy65:
	++YYCURSOR;
	if (YYLIMIT <= YYCURSOR) YYFILL(1);
	yych = *YYCURSOR;
	switch (yych) {
	case 'A':
	case 'B':
	case 'C':
	case 'D':
	case 'E':
	case 'F':
	case 'G':
	case 'H':
	case 'I':
	case 'J':
	case 'K':
	case 'L':
	case 'M':
	case 'N':
	case 'O':
	case 'P':
	case 'Q':
	case 'R':
	case 'S':
	case 'T':
	case 'U':
	case 'V':
	case 'W':
	case 'X':
	case 'Y':
	case 'Z':
	case 'a':
	case 'b':
	case 'c':
	case 'd':
	case 'e':
	case 'f':
	case 'g':
	case 'h':
	case 'i':
	case 'j':
	case 'k':
	case 'l':
	case 'm':
	case 'n':
	case 'o':
	case 'p':
	case 'q':
	case 'r':
	case 's':
	case 't':
	case 'u':
	case 'v':
	case 'w':
	case 'x':
	case 'y':
	case 'z':	goto yy67;
	default:	goto yy66;
	}
yy66:
	YYCURSOR = YYMARKER;
	switch (yyaccept) {
	case 0: 	goto yy32;
	case 1: 	goto yy38;
	case 2: 	goto yy40;
	case 3: 	goto yy42;
	case 4: 	goto yy46;
	case 5: 	goto yy69;
	default:	goto yy98;
	}
yy67:
	yyaccept = 5;
	YYMARKER = ++YYCURSOR;
	if (YYLIMIT <= YYCURSOR) YYFILL(1);
	yych = *YYCURSOR;
	switch (yych) {
	case '0':
	case '1':
	case '2':
	case '3':
	case '4':
	case '5':
	case '6':
	case '7':
	case '8':
	case '9':
	case 'A':
	case 'B':
	case 'C':
	case 'D':
	case 'E':
	case 'F':
	case 'G':
	case 'H':
	case 'I':
	case 'J':
	case 'K':
	case 'L':
	case 'M':
	case 'N':
	case 'O':
	case 'P':
	case 'Q':
	case 'R':
	case 'S':
	case 'T':
	case 'U':
	case 'V':
	case 'W':
	case 'X':
	case 'Y':
	case 'Z':
	case '_':
	case 'a':
	case 'b':
	case 'c':
	case 'd':
	case 'e':
	case 'f':
	case 'g':
	case 'h':
	case 'i':
	case 'j':
	case 'k':
	case 'l':
	case 'm':
	case 'n':
	case 'o':
	case 'p':
	case 'q':
	case 'r':
	case 's':
	case 't':
	case 'u':
	case 'v':
	case 'w':
	case 'x':
	case 'y':
	case 'z':	goto yy67;
	case ':':	goto yy65;
	default:	goto yy69;
	}
yy69:
#line 218 "scanner.re"
	{ cur = cursor;
				  tok+= 5; /* skip "re2j:" */
				  iscfg = 1;
				  yylval.str = new Str(token());
				  return CONFIG;
				}
#line 755 "<stdout>"
yy70:
	++YYCURSOR;
	if (YYLIMIT <= YYCURSOR) YYFILL(1);
	yych = *YYCURSOR;
yy71:
	switch (yych) {
	case '\n':	goto yy66;
	case '\\':	goto yy74;
	case ']':	goto yy75;
	default:	goto yy70;
	}
yy72:
	++YYCURSOR;
	if (YYLIMIT <= YYCURSOR) YYFILL(1);
	yych = *YYCURSOR;
	switch (yych) {
	case '\n':	goto yy66;
	case '\\':	goto yy77;
	case ']':	goto yy78;
	default:	goto yy72;
	}
yy74:
	++YYCURSOR;
	if (YYLIMIT <= YYCURSOR) YYFILL(1);
	yych = *YYCURSOR;
	switch (yych) {
	case '\n':	goto yy66;
	default:	goto yy70;
	}
yy75:
	++YYCURSOR;
#line 190 "scanner.re"
	{ cur = cursor;
				  yylval.regexp = ranToRE(token());
				  return RANGE; }
#line 791 "<stdout>"
yy77:
	++YYCURSOR;
	if (YYLIMIT <= YYCURSOR) YYFILL(1);
	yych = *YYCURSOR;
	switch (yych) {
	case '\n':	goto yy66;
	default:	goto yy72;
	}
yy78:
	++YYCURSOR;
#line 186 "scanner.re"
	{ cur = cursor;
				  yylval.regexp = invToRE(token());
				  return RANGE; }
#line 806 "<stdout>"
yy80:
	++YYCURSOR;
	if (YYLIMIT <= YYCURSOR) YYFILL(1);
	yych = *YYCURSOR;
yy81:
	switch (yych) {
	case '\n':	goto yy66;
	case '\'':	goto yy83;
	case '\\':	goto yy82;
	default:	goto yy80;
	}
yy82:
	++YYCURSOR;
	if (YYLIMIT <= YYCURSOR) YYFILL(1);
	yych = *YYCURSOR;
	switch (yych) {
	case '\n':	goto yy66;
	default:	goto yy80;
	}
yy83:
	++YYCURSOR;
#line 179 "scanner.re"
	{ cur = cursor;
				  yylval.regexp = strToCaseInsensitiveRE(token());
				  return STRING; }
#line 832 "<stdout>"
yy85:
	++YYCURSOR;
	if (YYLIMIT <= YYCURSOR) YYFILL(1);
	yych = *YYCURSOR;
yy86:
	switch (yych) {
	case '\n':	goto yy66;
	case '"':	goto yy88;
	case '\\':	goto yy87;
	default:	goto yy85;
	}
yy87:
	++YYCURSOR;
	if (YYLIMIT <= YYCURSOR) YYFILL(1);
	yych = *YYCURSOR;
	switch (yych) {
	case '\n':	goto yy66;
	default:	goto yy85;
	}
yy88:
	++YYCURSOR;
#line 175 "scanner.re"
	{ cur = cursor;
				  yylval.regexp = strToRE(token());
				  return STRING; }
#line 858 "<stdout>"
yy90:
	++YYCURSOR;
#line 172 "scanner.re"
	{ tok = cursor;
				  RETURN(0); }
#line 864 "<stdout>"
yy92:
	++YYCURSOR;
#line 169 "scanner.re"
	{ depth = 1;
				  goto comment; }
#line 870 "<stdout>"
yy94:
	yych = *++YYCURSOR;
	switch (yych) {
	case ',':	goto yy108;
	default:	goto yy96;
	}
yy95:
	++YYCURSOR;
	if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
	yych = *YYCURSOR;
yy96:
	switch (yych) {
	case ',':	goto yy101;
	case '0':
	case '1':
	case '2':
	case '3':
	case '4':
	case '5':
	case '6':
	case '7':
	case '8':
	case '9':	goto yy95;
	case '}':	goto yy99;
	default:	goto yy66;
	}
yy97:
	++YYCURSOR;
yy98:
#line 216 "scanner.re"
	{ fatal("illegal closure form, use '{n}', '{n,}', '{n,m}' where n and m are numbers"); }
#line 902 "<stdout>"
yy99:
	++YYCURSOR;
#line 204 "scanner.re"
	{ yylval.extop.minsize = atoi((char *)tok+1);
				  yylval.extop.maxsize = atoi((char *)tok+1);
				  RETURN(CLOSESIZE); }
#line 909 "<stdout>"
yy101:
	yyaccept = 6;
	yych = *(YYMARKER = ++YYCURSOR);
	switch (yych) {
	case '0':
	case '1':
	case '2':
	case '3':
	case '4':
	case '5':
	case '6':
	case '7':
	case '8':
	case '9':	goto yy104;
	case '}':	goto yy102;
	default:	goto yy98;
	}
yy102:
	++YYCURSOR;
#line 212 "scanner.re"
	{ yylval.extop.minsize = atoi((char *)tok+1);
				  yylval.extop.maxsize = -1;
				  RETURN(CLOSESIZE); }
#line 933 "<stdout>"
yy104:
	++YYCURSOR;
	if (YYLIMIT <= YYCURSOR) YYFILL(1);
	yych = *YYCURSOR;
	switch (yych) {
	case '0':
	case '1':
	case '2':
	case '3':
	case '4':
	case '5':
	case '6':
	case '7':
	case '8':
	case '9':	goto yy104;
	case '}':	goto yy106;
	default:	goto yy66;
	}
yy106:
	++YYCURSOR;
#line 208 "scanner.re"
	{ yylval.extop.minsize = atoi((char *)tok+1);
				  yylval.extop.maxsize = MAX(yylval.extop.minsize,atoi(strchr((char *)tok, ',')+1));
				  RETURN(CLOSESIZE); }
#line 958 "<stdout>"
yy108:
	yyaccept = 6;
	yych = *(YYMARKER = ++YYCURSOR);
	switch (yych) {
	case '0':
	case '1':
	case '2':
	case '3':
	case '4':
	case '5':
	case '6':
	case '7':
	case '8':
	case '9':	goto yy104;
	case '}':	goto yy109;
	default:	goto yy98;
	}
yy109:
	++YYCURSOR;
#line 201 "scanner.re"
	{ yylval.op = '*';
				  RETURN(CLOSE); }
#line 981 "<stdout>"
}
#line 247 "scanner.re"


code:

#line 988 "<stdout>"
{
	YYCTYPE yych;
	if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
	yych = *YYCURSOR;
	switch (yych) {
	case '\n':	goto yy117;
	case '"':	goto yy121;
	case '\'':	goto yy122;
	case '{':	goto yy115;
	case '}':	goto yy113;
	default:	goto yy119;
	}
yy113:
	++YYCURSOR;
#line 251 "scanner.re"
	{ if(--depth == 0){
					cur = cursor;
					yylval.token = new Token(token(), tline);
					return CODE;
				  }
				  goto code; }
#line 1010 "<stdout>"
yy115:
	++YYCURSOR;
#line 257 "scanner.re"
	{ ++depth;
				  goto code; }
#line 1016 "<stdout>"
yy117:
	++YYCURSOR;
#line 259 "scanner.re"
	{ if(cursor == eof) fatal("missing '}'");
				  pos = cursor; cline++;
				  goto code;
				}
#line 1024 "<stdout>"
yy119:
	++YYCURSOR;
yy120:
#line 263 "scanner.re"
	{ goto code; }
#line 1030 "<stdout>"
yy121:
	yych = *(YYMARKER = ++YYCURSOR);
	switch (yych) {
	case '\n':	goto yy120;
	default:	goto yy128;
	}
yy122:
	yych = *(YYMARKER = ++YYCURSOR);
	switch (yych) {
	case '\n':	goto yy120;
	default:	goto yy124;
	}
yy123:
	++YYCURSOR;
	if (YYLIMIT <= YYCURSOR) YYFILL(1);
	yych = *YYCURSOR;
yy124:
	switch (yych) {
	case '\n':	goto yy125;
	case '\'':	goto yy119;
	case '\\':	goto yy126;
	default:	goto yy123;
	}
yy125:
	YYCURSOR = YYMARKER;
	goto yy120;
yy126:
	++YYCURSOR;
	if (YYLIMIT <= YYCURSOR) YYFILL(1);
	yych = *YYCURSOR;
	switch (yych) {
	case '\n':	goto yy125;
	default:	goto yy123;
	}
yy127:
	++YYCURSOR;
	if (YYLIMIT <= YYCURSOR) YYFILL(1);
	yych = *YYCURSOR;
yy128:
	switch (yych) {
	case '\n':	goto yy125;
	case '"':	goto yy119;
	case '\\':	goto yy129;
	default:	goto yy127;
	}
yy129:
	++YYCURSOR;
	if (YYLIMIT <= YYCURSOR) YYFILL(1);
	yych = *YYCURSOR;
	switch (yych) {
	case '\n':	goto yy125;
	default:	goto yy127;
	}
}
#line 264 "scanner.re"


comment:

#line 1090 "<stdout>"
{
	YYCTYPE yych;
	if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
	yych = *YYCURSOR;
	switch (yych) {
	case '\n':	goto yy135;
	case '*':	goto yy132;
	case '/':	goto yy134;
	default:	goto yy137;
	}
yy132:
	++YYCURSOR;
	switch ((yych = *YYCURSOR)) {
	case '/':	goto yy140;
	default:	goto yy133;
	}
yy133:
#line 279 "scanner.re"
	{ if(cursor == eof) RETURN(0);
				  goto comment; }
#line 1111 "<stdout>"
yy134:
	yych = *++YYCURSOR;
	switch (yych) {
	case '*':	goto yy138;
	default:	goto yy133;
	}
yy135:
	++YYCURSOR;
#line 275 "scanner.re"
	{ if(cursor == eof) RETURN(0);
				  tok = pos = cursor; cline++;
				  goto comment;
				}
#line 1125 "<stdout>"
yy137:
	yych = *++YYCURSOR;
	goto yy133;
yy138:
	++YYCURSOR;
#line 272 "scanner.re"
	{ ++depth;
				  fatal("ambiguous /* found");
				  goto comment; }
#line 1135 "<stdout>"
yy140:
	++YYCURSOR;
#line 268 "scanner.re"
	{ if(--depth == 0)
					goto scan;
				    else
					goto comment; }
#line 1143 "<stdout>"
}
#line 281 "scanner.re"


config:

#line 1150 "<stdout>"
{
	YYCTYPE yych;
	if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
	yych = *YYCURSOR;
	switch (yych) {
	case '\t':
	case ' ':	goto yy144;
	case '=':	goto yy146;
	default:	goto yy148;
	}
yy144:
	++YYCURSOR;
	yych = *YYCURSOR;
	goto yy153;
yy145:
#line 285 "scanner.re"
	{ goto config; }
#line 1168 "<stdout>"
yy146:
	++YYCURSOR;
	yych = *YYCURSOR;
	goto yy151;
yy147:
#line 286 "scanner.re"
	{ iscfg = 2;
				  cur = cursor;
				  RETURN('='); 
				}
#line 1179 "<stdout>"
yy148:
	++YYCURSOR;
#line 290 "scanner.re"
	{ fatal("missing '='"); }
#line 1184 "<stdout>"
yy150:
	++YYCURSOR;
	if (YYLIMIT <= YYCURSOR) YYFILL(1);
	yych = *YYCURSOR;
yy151:
	switch (yych) {
	case '\t':
	case ' ':	goto yy150;
	default:	goto yy147;
	}
yy152:
	++YYCURSOR;
	if (YYLIMIT <= YYCURSOR) YYFILL(1);
	yych = *YYCURSOR;
yy153:
	switch (yych) {
	case '\t':
	case ' ':	goto yy152;
	default:	goto yy145;
	}
}
#line 291 "scanner.re"


value:

#line 1211 "<stdout>"
{
	YYCTYPE yych;
	if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
	yych = *YYCURSOR;
	switch (yych) {
	case '\t':
	case '\n':
	case '\r':
	case ' ':
	case ';':	goto yy156;
	case '"':	goto yy164;
	case '\'':	goto yy166;
	case '-':	goto yy159;
	case '0':	goto yy157;
	case '1':
	case '2':
	case '3':
	case '4':
	case '5':
	case '6':
	case '7':
	case '8':
	case '9':	goto yy160;
	default:	goto yy162;
	}
yy156:
#line 300 "scanner.re"
	{ cur = cursor;
				  yylval.str = new Str(token());
				  iscfg = 0;
				  return VALUE;
				}
#line 1244 "<stdout>"
yy157:
	++YYCURSOR;
	switch ((yych = *YYCURSOR)) {
	case '\t':
	case '\n':
	case '\r':
	case ' ':
	case ';':	goto yy158;
	default:	goto yy162;
	}
yy158:
#line 295 "scanner.re"
	{ cur = cursor;
				  yylval.number = atoi(token().to_string().c_str());
				  iscfg = 0;
				  return NUMBER;
				}
#line 1262 "<stdout>"
yy159:
	yych = *++YYCURSOR;
	switch (yych) {
	case '1':
	case '2':
	case '3':
	case '4':
	case '5':
	case '6':
	case '7':
	case '8':
	case '9':	goto yy160;
	default:	goto yy163;
	}
yy160:
	++YYCURSOR;
	if (YYLIMIT <= YYCURSOR) YYFILL(1);
	yych = *YYCURSOR;
	switch (yych) {
	case '\t':
	case '\n':
	case '\r':
	case ' ':
	case ';':	goto yy158;
	case '0':
	case '1':
	case '2':
	case '3':
	case '4':
	case '5':
	case '6':
	case '7':
	case '8':
	case '9':	goto yy160;
	default:	goto yy162;
	}
yy162:
	++YYCURSOR;
	if (YYLIMIT <= YYCURSOR) YYFILL(1);
	yych = *YYCURSOR;
yy163:
	switch (yych) {
	case '\t':
	case '\n':
	case '\r':
	case ' ':
	case ';':	goto yy156;
	default:	goto yy162;
	}
yy164:
	YYMARKER = ++YYCURSOR;
	if (YYLIMIT <= YYCURSOR) YYFILL(1);
	yych = *YYCURSOR;
	switch (yych) {
	case '\t':
	case '\r':
	case ' ':
	case ';':	goto yy174;
	case '\n':	goto yy156;
	case '"':	goto yy162;
	case '\\':	goto yy176;
	default:	goto yy164;
	}
yy166:
	YYMARKER = ++YYCURSOR;
	if (YYLIMIT <= YYCURSOR) YYFILL(1);
	yych = *YYCURSOR;
	switch (yych) {
	case '\t':
	case '\r':
	case ' ':
	case ';':	goto yy168;
	case '\n':	goto yy156;
	case '\'':	goto yy162;
	case '\\':	goto yy171;
	default:	goto yy166;
	}
yy168:
	++YYCURSOR;
	if (YYLIMIT <= YYCURSOR) YYFILL(1);
	yych = *YYCURSOR;
	switch (yych) {
	case '\n':	goto yy170;
	case '\'':	goto yy172;
	case '\\':	goto yy173;
	default:	goto yy168;
	}
yy170:
	YYCURSOR = YYMARKER;
	goto yy156;
yy171:
	YYMARKER = ++YYCURSOR;
	if (YYLIMIT <= YYCURSOR) YYFILL(1);
	yych = *YYCURSOR;
	switch (yych) {
	case '\t':
	case '\r':
	case ' ':
	case ';':	goto yy168;
	case '\n':	goto yy156;
	default:	goto yy166;
	}
yy172:
	yych = *++YYCURSOR;
	goto yy156;
yy173:
	++YYCURSOR;
	if (YYLIMIT <= YYCURSOR) YYFILL(1);
	yych = *YYCURSOR;
	switch (yych) {
	case '\n':	goto yy170;
	default:	goto yy168;
	}
yy174:
	++YYCURSOR;
	if (YYLIMIT <= YYCURSOR) YYFILL(1);
	yych = *YYCURSOR;
	switch (yych) {
	case '\n':	goto yy170;
	case '"':	goto yy172;
	case '\\':	goto yy177;
	default:	goto yy174;
	}
yy176:
	YYMARKER = ++YYCURSOR;
	if (YYLIMIT <= YYCURSOR) YYFILL(1);
	yych = *YYCURSOR;
	switch (yych) {
	case '\t':
	case '\r':
	case ' ':
	case ';':	goto yy174;
	case '\n':	goto yy156;
	default:	goto yy164;
	}
yy177:
	++YYCURSOR;
	if (YYLIMIT <= YYCURSOR) YYFILL(1);
	yych = *YYCURSOR;
	switch (yych) {
	case '\n':	goto yy170;
	default:	goto yy174;
	}
}
#line 305 "scanner.re"

}
示例#2
0
// Turns LLL tree into tree of code fragments
programData opcodeify(Node node,
                      programAux aux=Aux(),
                      programVerticalAux vaux=verticalAux()) {
    std::string symb = "_"+mkUniqueToken();
    Metadata m = node.metadata;
    // Numbers
    if (node.type == TOKEN) {
        return pd(aux, nodeToNumeric(node), 1);
    }
    else if (node.val == "ref" || node.val == "get" || node.val == "set") {
        std::string varname = node.args[0].val;
        // Determine reference to variable
        if (!aux.vars.count(node.args[0].val)) {
            aux.vars[node.args[0].val] = utd(aux.nextVarMem);
            aux.nextVarMem += 32;
        }
        Node varNode = tkn(aux.vars[varname], m);
        //std::cerr << varname << " " << printSimple(varNode) << "\n";
        // Set variable
        if (node.val == "set") {
            programData sub = opcodeify(node.args[1], aux, vaux);
            if (!sub.outs)
                err("Value to set variable must have nonzero arity!", m);
            // What if we are setting a stack variable?
            if (vaux.dupvars.count(node.args[0].val)) {
                int h = vaux.height - vaux.dupvars[node.args[0].val];
                if (h > 16) err("Too deep for stack variable (max 16)", m);
                Node nodelist[] = {
                    sub.code,
                    token("SWAP"+unsignedToDecimal(h), m),
                    token("POP", m)
                };
                return pd(sub.aux, multiToken(nodelist, 3, m), 0);                   
            }
            // Setting a memory variable
            else {
                Node nodelist[] = {
                    sub.code,
                    varNode,
                    token("MSTORE", m),
                };
                return pd(sub.aux, multiToken(nodelist, 3, m), 0);                   
            }
        }
        // Get variable
        else if (node.val == "get") {
            // Getting a stack variable
            if (vaux.dupvars.count(node.args[0].val)) {
                 int h = vaux.height - vaux.dupvars[node.args[0].val];
                if (h > 16) err("Too deep for stack variable (max 16)", m);
                return pd(aux, token("DUP"+unsignedToDecimal(h)), 1);                   
            }
            // Getting a memory variable
            else {
                Node nodelist[] = 
                     { varNode, token("MLOAD", m) };
                return pd(aux, multiToken(nodelist, 2, m), 1);
            }
        }
        // Refer variable
        else if (node.val == "ref") {
            if (vaux.dupvars.count(node.args[0].val))
                err("Cannot ref stack variable!", m);
            return pd(aux, varNode, 1);
        }
    }
    // Comments do nothing
    else if (node.val == "comment") {
        return pd(aux, astnode("_", m), 0);
    }
    // Custom operation sequence
    // eg. (ops bytez id msize swap1 msize add 0 swap1 mstore) == alloc
    if (node.val == "ops") {
        std::vector<Node>  subs2;
        int depth = 0;
        for (unsigned i = 0; i < node.args.size(); i++) {
            std::string op = upperCase(node.args[i].val);
            if (node.args[i].type == ASTNODE || opinputs(op) == -1) {
                programVerticalAux vaux2 = vaux;
                vaux2.height = vaux.height - i - 1 + node.args.size();
                programData sub = opcodeify(node.args[i], aux, vaux2);
                aux = sub.aux;
                depth += sub.outs;
                subs2.push_back(sub.code);
            }
            else {
                subs2.push_back(token(op, m));
                depth += opoutputs(op) - opinputs(op);
            }
        }
        if (depth < 0 || depth > 1) err("Stack depth mismatch", m);
        return pd(aux, astnode("_", subs2, m), 0);
    }
    // Code blocks
    if (node.val == "lll" && node.args.size() == 2) {
        if (node.args[1].val != "0") aux.allocUsed = true;
        std::vector<Node> o;
        o.push_back(finalize(opcodeify(node.args[0])));
        programData sub = opcodeify(node.args[1], aux, vaux);
        Node code = astnode("____CODE", o, m);
        Node nodelist[] = {
            token("$begincode"+symb+".endcode"+symb, m), token("DUP1", m),
            token("$begincode"+symb, m), sub.code, token("CODECOPY", m),
            token("$endcode"+symb, m), token("JUMP", m),
            token("~begincode"+symb, m), code, 
            token("~endcode"+symb, m), token("JUMPDEST", m)
        };
        return pd(sub.aux, multiToken(nodelist, 11, m), 1);
    }
    // Stack variables
    if (node.val == "with") {
        programData initial = opcodeify(node.args[1], aux, vaux);
        programVerticalAux vaux2 = vaux;
        vaux2.dupvars[node.args[0].val] = vaux.height;
        vaux2.height += 1;
        if (!initial.outs)
            err("Initial variable value must have nonzero arity!", m);
        programData sub = opcodeify(node.args[2], initial.aux, vaux2);
        Node nodelist[] = {
            initial.code,
            sub.code
        };
        programData o = pd(sub.aux, multiToken(nodelist, 2, m), sub.outs);
        if (sub.outs)
            o.code.args.push_back(token("SWAP1", m));
        o.code.args.push_back(token("POP", m));
        return o;
    }
    // Seq of multiple statements
    if (node.val == "seq") {
        std::vector<Node> children;
        int lastOut = 0;
        for (unsigned i = 0; i < node.args.size(); i++) {
            programData sub = opcodeify(node.args[i], aux, vaux);
            aux = sub.aux;
            if (sub.outs == 1) {
                if (i < node.args.size() - 1) sub.code = popwrap(sub.code);
                else lastOut = 1;
            }
            children.push_back(sub.code);
        }
        return pd(aux, astnode("_", children, m), lastOut);
    }
    // 2-part conditional (if gets rewritten to unless in rewrites)
    else if (node.val == "unless" && node.args.size() == 2) {
        programData cond = opcodeify(node.args[0], aux, vaux);
        programData action = opcodeify(node.args[1], cond.aux, vaux);
        aux = action.aux;
        if (!cond.outs) err("Condition of if/unless statement has arity 0", m);
        if (action.outs) action.code = popwrap(action.code);
        Node nodelist[] = {
            cond.code,
            token("$endif"+symb, m), token("JUMPI", m),
            action.code,
            token("~endif"+symb, m), token("JUMPDEST", m)
        };
        return pd(aux, multiToken(nodelist, 6, m), 0);
    }
    // 3-part conditional
    else if (node.val == "if" && node.args.size() == 3) {
        programData ifd = opcodeify(node.args[0], aux, vaux);
        programData thend = opcodeify(node.args[1], ifd.aux, vaux);
        programData elsed = opcodeify(node.args[2], thend.aux, vaux);
        aux = elsed.aux;
        if (!ifd.outs)
            err("Condition of if/unless statement has arity 0", m);
        // Handle cases where one conditional outputs something
        // and the other does not
        int outs = (thend.outs && elsed.outs) ? 1 : 0;
        if (thend.outs > outs) thend.code = popwrap(thend.code);
        if (elsed.outs > outs) elsed.code = popwrap(elsed.code);
        Node nodelist[] = {
            ifd.code,
            token("ISZERO", m),
            token("$else"+symb, m), token("JUMPI", m),
            thend.code,
            token("$endif"+symb, m), token("JUMP", m),
            token("~else"+symb, m), token("JUMPDEST", m),
            elsed.code,
            token("~endif"+symb, m), token("JUMPDEST", m)
        };
        return pd(aux, multiToken(nodelist, 12, m), outs);
    }
    // While (rewritten to this in rewrites)
    else if (node.val == "until") {
        programData cond = opcodeify(node.args[0], aux, vaux);
        programData action = opcodeify(node.args[1], cond.aux, vaux);
        aux = action.aux;
        if (!cond.outs)
            err("Condition of while/until loop has arity 0", m);
        if (action.outs) action.code = popwrap(action.code);
        Node nodelist[] = {
            token("~beg"+symb, m), token("JUMPDEST", m),
            cond.code,
            token("$end"+symb, m), token("JUMPI", m),
            action.code,
            token("$beg"+symb, m), token("JUMP", m),
            token("~end"+symb, m), token("JUMPDEST", m),
        };
        return pd(aux, multiToken(nodelist, 10, m));
    }
    // Memory allocations
    else if (node.val == "alloc") {
        programData bytez = opcodeify(node.args[0], aux, vaux);
        aux = bytez.aux;
        if (!bytez.outs)
            err("Alloc input has arity 0", m);
        aux.allocUsed = true;
        Node nodelist[] = {
            bytez.code,
            token("MSIZE", m), token("SWAP1", m), token("MSIZE", m),
            token("ADD", m), 
            token("0", m), token("SWAP1", m), token("MSTORE", m)
        };
        return pd(aux, multiToken(nodelist, 8, m), 1);
    }
    // All other functions/operators
    else {
        std::vector<Node>  subs2;
        int depth = opinputs(upperCase(node.val));
        if (depth == -1)
            err("Not a function or opcode: "+node.val, m);
        if ((int)node.args.size() != depth)
            err("Invalid arity for "+node.val, m);
        for (int i = node.args.size() - 1; i >= 0; i--) {
            programVerticalAux vaux2 = vaux;
            vaux2.height = vaux.height - i - 1 + node.args.size();
            programData sub = opcodeify(node.args[i], aux, vaux2);
            aux = sub.aux;
            if (!sub.outs)
                err("Input "+unsignedToDecimal(i)+" has arity 0", sub.code.metadata);
            subs2.push_back(sub.code);
        }
        subs2.push_back(token(upperCase(node.val), m));
        int outdepth = opoutputs(upperCase(node.val));
        return pd(aux, astnode("_", subs2, m), outdepth);
    }
}
示例#3
0
static struct test *read_tests(void) {
    char *fname = NULL;
    FILE *fp;
    char line[BUFSIZ];
    struct test *result = NULL, *t = NULL;
    int lc = 0;
    bool append_cmd = true;

    if (asprintf(&fname, "%s/tests/run.tests", abs_top_srcdir) < 0)
        die("asprintf fname");

    if ((fp = fopen(fname, "r")) == NULL)
        die("fopen run.tests");

    while (fgets(line, BUFSIZ, fp) != NULL) {
        lc += 1;
        char *s = skipws(line);
        if (*s == '#' || *s == '\0')
            continue;
        if (*s == ':')
            s += 1;
        char *eos = s + strlen(s) - 2;
        if (eos >= s && *eos == ':') {
            *eos++ = '\n';
            *eos = '\0';
        }

        if (looking_at(s, KW_TEST)) {
            if (ALLOC(t) < 0)
                die_oom();
            list_append(result, t);
            append_cmd = true;
            s = token(s + strlen(KW_TEST), &(t->name));
            s = inttok(s, &t->result);
            s = errtok(s, &t->errcode);
        } else if (looking_at(s, KW_PRINTS)) {
            s = skipws(s + strlen(KW_PRINTS));
            t->out_present = looking_at(s, KW_SOMETHING);
            append_cmd = false;
        } else if (looking_at(s, KW_USE)) {
            if (t->module !=NULL)
                die("Can use at most one module in a test");
            s = token(s + strlen(KW_USE), &(t->module));
        } else {
            char **buf = append_cmd ? &(t->cmd) : &(t->out);
            if (*buf == NULL) {
                *buf = strdup(s);
                if (*buf == NULL)
                    die_oom();
            } else {
                if (REALLOC_N(*buf, strlen(*buf) + strlen(s) + 1) < 0)
                    die_oom();
                strcat(*buf, s);
            }
        }
        if (t->out != NULL)
            t->out_present = true;
    }
    free(fname);
    return result;
}
示例#4
0
void QtHistoTfuncPixmap::loadfile(QString fn)
{
	if(fn.isEmpty()) return;

	//temp storage for param parsing
	string label;
	int i;
	int size;
	Vector v;

	//clear our BSs
	funceditor.bs.clear();

	//input file for reading in parameter ranges
	ifstream input_file; 
	input_file.open(fn.latin1());

	//tokenize our input file
	Tokenizer token(input_file);

	//until oef is reached step through each token
	while(!input_file.eof()){
		if(token.ttype()==TT_WORD)
		{
			//get the first string lable
			label = token.sval();
			
			if(label=="THRESHOLD_LEVELS")
			{		
				token.nextToken();
				if(token.ttype()==TT_NUMBER) minthr = token.nval();
				token.nextToken();
				if(token.ttype()==TT_NUMBER) maxthr = token.nval();
				token.nextToken();
			}			
			else if(label=="TF_CONTROL_POINTS")
			{		
				token.nextToken();
				if(token.ttype()==TT_NUMBER) size = token.nval();
				
				for(i=0; i<size; i++)
				{
					token.nextToken();
					if(token.ttype()==TT_NUMBER) v.x = token.nval();
					token.nextToken();
					if(token.ttype()==TT_NUMBER) v.y = token.nval();
					token.nextToken();
					if(token.ttype()==TT_NUMBER) v.z = token.nval();

					funceditor.bs.control_points.push_back(v);
				}
			}				
			//else if we dont know what it is, go to next label
			else
			{
				//f<<"WARNING: Unrecognized Label..."<<endl;
				token.nextToken();
			}
		}
		else token.nextToken();
	}

	input_file.close();

	//compute our BS curve from our loaded control points
	funceditor.bs.compute();
}
示例#5
0
int main(int argc, char* argv[])
{
	std::string url = "http://127.0.0.1:8080";
	std::string username;
	std::string password;
	int c=0;
	while ((c = getopt (argc, argv, "hu:p:")) != -1)
	{
		switch (c)
		{
			case 'u':	username = optarg; break;
			case 'p':	password = optarg; break;
			case 'h':
				std::cout << argv[0] << " [-u username] [-p password] url" << std::endl;
				exit(0);
			break;
		}
	}
	if (optind<argc)
	{
		url = argv[optind];
	}		
	
	std::cout << "Connecting to " << url << std::endl;

	
	// create connection to devicemgmt.wsdl server
        DeviceBindingProxy deviceProxy(url.c_str());
	
	// call Device::GetDeviceInformation
	std::cout << "=>Device::GetDeviceInformation" << std::endl;	
	_tds__GetDeviceInformation         tds__GetDeviceInformation;
	_tds__GetDeviceInformationResponse tds__GetDeviceInformationResponse;
	addSecurity(deviceProxy.soap, username, password);	
	if (deviceProxy.GetDeviceInformation(&tds__GetDeviceInformation, &tds__GetDeviceInformationResponse) == SOAP_OK)
	{
		std::cout << "\tManufacturer:" << tds__GetDeviceInformationResponse.Manufacturer << std::endl;
	}
	else
	{
		deviceProxy.soap_stream_fault(std::cerr);
	}

	// call Device::GetHostname
	std::cout << "=>Device::GetHostname" << std::endl;	
	_tds__GetHostname         tds__GetHostname;
	_tds__GetHostnameResponse tds__GetHostnameResponse;
	addSecurity(deviceProxy.soap, username, password);	
	if (deviceProxy.GetHostname(&tds__GetHostname, &tds__GetHostnameResponse) == SOAP_OK)
	{
		std::cout << "\tHostname:" << tds__GetHostnameResponse.HostnameInformation->Name->c_str() << std::endl;
	}
	else
	{
		deviceProxy.soap_stream_fault(std::cerr);
	}

	// call Device::GetNetworkInterfaces
	std::cout << "=>Device::GetNetworkInterfaces" << std::endl;	
	_tds__GetNetworkInterfaces         tds__GetNetworkInterfaces;
	_tds__GetNetworkInterfacesResponse tds__GetNetworkInterfacesResponse;
	addSecurity(deviceProxy.soap, username, password);	
	if (deviceProxy.GetNetworkInterfaces(&tds__GetNetworkInterfaces, &tds__GetNetworkInterfacesResponse) == SOAP_OK)
	{
		for (auto iface : tds__GetNetworkInterfacesResponse.NetworkInterfaces)
		{
			if (iface->Info != NULL)
			{
				std::cout << "\t" << iface->Info->Name->c_str() <<  " " << iface->Info->HwAddress << std::endl;			
			}
			if ( (iface->IPv4 != NULL) && (iface->IPv4->Config != NULL) )
			{
				for (auto addr : iface->IPv4->Config->Manual)
				{
					std::cout << "\tIP:" << addr->Address  << "/" << addr->PrefixLength << std::endl;					
				}
			}
		}
	}
	else
	{
		deviceProxy.soap_stream_fault(std::cerr);
	}
	
	// call Device::GetServices
	std::cout << "=>Device::GetServices" << std::endl;		
	_tds__GetServices         tds__GetServices;
	tds__GetServices.IncludeCapability = true;
	_tds__GetServicesResponse tds__GetServicesResponse;
	addSecurity(deviceProxy.soap, username, password);	
	if (deviceProxy.GetServices(&tds__GetServices, &tds__GetServicesResponse) == SOAP_OK)
	{
		for (auto service : tds__GetServicesResponse.Service)
		{
			std::cout << "\tns:" << service->Namespace << " " << service->XAddr << " Version:" << service->Version->Major << "." << service->Version->Minor << std::endl;
			if (service->Capabilities)
			{
				std::cout << "\t" << service->Capabilities->__any << std::endl;
			}
		}
	}
	
	// call Device::GetCapabilities
	std::cout << "=>Device::GetCapabilities" << std::endl;		
	_tds__GetCapabilities         tds__GetCapabilities;
	_tds__GetCapabilitiesResponse tds__GetCapabilitiesResponse;
	addSecurity(deviceProxy.soap, username, password);	
	if (deviceProxy.GetCapabilities(&tds__GetCapabilities, &tds__GetCapabilitiesResponse) == SOAP_OK)
	{
		std::unique_ptr<ImagingBindingProxy> imagingProxy;
		if ( (tds__GetCapabilitiesResponse.Capabilities->Extension != NULL) && (tds__GetCapabilitiesResponse.Capabilities->Imaging != NULL) )
		{
			std::cout << "\tImaging Url:" << tds__GetCapabilitiesResponse.Capabilities->Imaging->XAddr << std::endl;			
			imagingProxy.reset(new ImagingBindingProxy(tds__GetCapabilitiesResponse.Capabilities->Imaging->XAddr.c_str()));
		}
		std::unique_ptr<ReplayBindingProxy> replayProxy;
		if ( (tds__GetCapabilitiesResponse.Capabilities->Extension != NULL) && (tds__GetCapabilitiesResponse.Capabilities->Extension->Replay != NULL) )
		{
			std::cout << "\tReplay Url:" << tds__GetCapabilitiesResponse.Capabilities->Extension->Replay->XAddr << std::endl;			
			replayProxy.reset(new ReplayBindingProxy(tds__GetCapabilitiesResponse.Capabilities->Extension->Replay->XAddr.c_str()));
		}
		std::unique_ptr<MediaBindingProxy> mediaProxy;
		if (tds__GetCapabilitiesResponse.Capabilities->Media != NULL)
		{
			std::cout << "\tMedia Url:" << tds__GetCapabilitiesResponse.Capabilities->Media->XAddr << std::endl;			
			mediaProxy.reset(new MediaBindingProxy(tds__GetCapabilitiesResponse.Capabilities->Media->XAddr.c_str()));
		}
		std::unique_ptr<ReceiverBindingProxy> receiverProxy;
		if ( (tds__GetCapabilitiesResponse.Capabilities->Extension != NULL) && (tds__GetCapabilitiesResponse.Capabilities->Extension->Receiver != NULL) )
		{
			std::cout << "\tReceiver Url:" << tds__GetCapabilitiesResponse.Capabilities->Extension->Receiver->XAddr << std::endl;			
			receiverProxy.reset(new ReceiverBindingProxy(tds__GetCapabilitiesResponse.Capabilities->Extension->Receiver->XAddr.c_str()));
		}
		std::unique_ptr<RecordingBindingProxy> recordingProxy;
		if ( (tds__GetCapabilitiesResponse.Capabilities->Extension != NULL) && (tds__GetCapabilitiesResponse.Capabilities->Extension->Recording != NULL) )
		{
			std::cout << "\tRecording Url:" << tds__GetCapabilitiesResponse.Capabilities->Extension->Recording->XAddr << std::endl;			
			recordingProxy.reset(new RecordingBindingProxy(tds__GetCapabilitiesResponse.Capabilities->Extension->Recording->XAddr.c_str()));
		}		
		std::unique_ptr<SearchBindingProxy> searchProxy;
		if ( (tds__GetCapabilitiesResponse.Capabilities->Extension != NULL) && (tds__GetCapabilitiesResponse.Capabilities->Extension->Search != NULL) )
		{
			std::cout << "\tSearch Url:" << tds__GetCapabilitiesResponse.Capabilities->Extension->Search->XAddr << std::endl;			
			searchProxy.reset (new SearchBindingProxy(tds__GetCapabilitiesResponse.Capabilities->Extension->Search->XAddr.c_str()));
		}
		std::unique_ptr<EventBindingProxy> eventProxy;
		if (tds__GetCapabilitiesResponse.Capabilities->Events != NULL)
		{
			std::cout << "\tEvent Url:" << tds__GetCapabilitiesResponse.Capabilities->Events->XAddr << std::endl;			
			eventProxy.reset(new EventBindingProxy(tds__GetCapabilitiesResponse.Capabilities->Events->XAddr.c_str()));
		}
		
		
		if (mediaProxy.get() != NULL)
		{
			// call Media::GetVideoSources
			std::cout << "=>Media::GetVideoSources" << std::endl;				
			_trt__GetVideoSources         trt__GetVideoSources;
			_trt__GetVideoSourcesResponse trt__GetVideoSourcesResponse;			
			addSecurity(mediaProxy->soap, username, password);	
			if (mediaProxy->GetVideoSources(&trt__GetVideoSources, &trt__GetVideoSourcesResponse) == SOAP_OK)
			{		
				for (auto source : trt__GetVideoSourcesResponse.VideoSources)
				{
					std::cout << "\t" << source->token;
					if (source->Resolution)
					{
						std::cout << " " << source->Resolution->Width << "x" << source->Resolution->Height;
					}
					std::cout << std::endl;
					
					_trt__GetVideoEncoderConfiguration         trt__GetVideoEncoderConfiguration;
					trt__GetVideoEncoderConfiguration.ConfigurationToken = source->token;
					_trt__GetVideoEncoderConfigurationResponse trt__GetVideoEncoderConfigurationResponse;
					addSecurity(mediaProxy->soap, username, password);						
					if (mediaProxy->GetVideoEncoderConfiguration(&trt__GetVideoEncoderConfiguration, &trt__GetVideoEncoderConfigurationResponse) == SOAP_OK)
					{		
						std::cout << "\tEncoding:" << trt__GetVideoEncoderConfigurationResponse.Configuration->Encoding << std::endl;
						if (trt__GetVideoEncoderConfigurationResponse.Configuration->H264)
						{
							std::cout << "\tH264Profile:" << trt__GetVideoEncoderConfigurationResponse.Configuration->H264->H264Profile << std::endl;
						}
						if (trt__GetVideoEncoderConfigurationResponse.Configuration->Resolution)
						{
							std::cout << "\tResolution:" << trt__GetVideoEncoderConfigurationResponse.Configuration->Resolution->Width << "x" << trt__GetVideoEncoderConfigurationResponse.Configuration->Resolution->Height << std::endl;
						}
					}

					_trt__GetVideoEncoderConfigurationOptions         trt__GetVideoEncoderConfigurationOptions;
					trt__GetVideoEncoderConfigurationOptions.ConfigurationToken = soap_new_std__string(mediaProxy->soap);
					trt__GetVideoEncoderConfigurationOptions.ConfigurationToken->assign(source->token);
					_trt__GetVideoEncoderConfigurationOptionsResponse trt__GetVideoEncoderConfigurationOptionsResponse;
					addSecurity(mediaProxy->soap, username, password);						
					if (mediaProxy->GetVideoEncoderConfigurationOptions(&trt__GetVideoEncoderConfigurationOptions, &trt__GetVideoEncoderConfigurationOptionsResponse) == SOAP_OK)
					{	
						if (trt__GetVideoEncoderConfigurationOptionsResponse.Options->H264)
						{
							for (auto res : trt__GetVideoEncoderConfigurationOptionsResponse.Options->H264->ResolutionsAvailable)
							{
								std::cout << "\tResolution:" << res->Width << "x" << res->Height << std::endl;
							}
						}
					}
					
					if (imagingProxy.get() != NULL)
					{
						_timg__GetImagingSettings timg__GetImagingSettings;
						timg__GetImagingSettings.VideoSourceToken = source->token;
						_timg__GetImagingSettingsResponse timg__GetImagingSettingsResponse;
						addSecurity(imagingProxy->soap, username, password);						
						if (imagingProxy->GetImagingSettings(&timg__GetImagingSettings, &timg__GetImagingSettingsResponse) == SOAP_OK)
						{
							std::cout << "\tBrightness  :" << printPtr (timg__GetImagingSettingsResponse.ImagingSettings->Brightness)            << std::endl;
							std::cout << "\tContrast    :" << printPtr (timg__GetImagingSettingsResponse.ImagingSettings->Contrast)              << std::endl;
							std::cout << "\tSaturation  :" << printPtr (timg__GetImagingSettingsResponse.ImagingSettings->ColorSaturation)       << std::endl;
							std::cout << "\tSharpness   :" << printPtr (timg__GetImagingSettingsResponse.ImagingSettings->Sharpness)             << std::endl;
							std::cout << "\tBacklight   :" << printMode(timg__GetImagingSettingsResponse.ImagingSettings->BacklightCompensation) << std::endl;
							std::cout << "\tWideDynamic :" << printMode(timg__GetImagingSettingsResponse.ImagingSettings->WideDynamicRange) << std::endl;
							std::cout << "\tExposure    :" << printMode(timg__GetImagingSettingsResponse.ImagingSettings->Exposure)              << std::endl;
							if (timg__GetImagingSettingsResponse.ImagingSettings->Exposure)
								std::cout << "\t\tExposureTime :" << printPtr(timg__GetImagingSettingsResponse.ImagingSettings->Exposure->ExposureTime)          << std::endl;
							std::cout << "\tWhiteBalance:" << printMode(timg__GetImagingSettingsResponse.ImagingSettings->WhiteBalance)          << std::endl;
							
						}
						
						_timg__GetOptions timg__GetOptions;
						timg__GetOptions.VideoSourceToken = source->token;
						_timg__GetOptionsResponse timg__GetOptionsResponse;
						addSecurity(imagingProxy->soap, username, password);						
						if (imagingProxy->GetOptions(&timg__GetOptions, &timg__GetOptionsResponse) == SOAP_OK)
						{
							std::cout << "\tBrightness: " << printRangePtr(timg__GetOptionsResponse.ImagingOptions->Brightness)      << std::endl;
							std::cout << "\tContrast  : " << printRangePtr(timg__GetOptionsResponse.ImagingOptions->Contrast)        << std::endl;
							std::cout << "\tSaturation: " << printRangePtr(timg__GetOptionsResponse.ImagingOptions->ColorSaturation) << std::endl;
							std::cout << "\tSharpness : " << printRangePtr(timg__GetOptionsResponse.ImagingOptions->Sharpness)       << std::endl;
						}
						
					}
				}
			}
			
			std::cout << "=>Media::GetProfiles" << std::endl;					
			_trt__GetProfiles         trt__GetProfiles;
			_trt__GetProfilesResponse trt__GetProfilesResponse;
			addSecurity(mediaProxy->soap, username, password);								
			if (mediaProxy->GetProfiles(&trt__GetProfiles, &trt__GetProfilesResponse) == SOAP_OK)
			{		
				for (auto profile : trt__GetProfilesResponse.Profiles)
				{
					std::string token(profile->token);
					std::cout << "\tMediaProfile:" << token << std::endl;
					
					_trt__GetStreamUri         trt__GetStreamUri;
					_trt__GetStreamUriResponse trt__GetStreamUriResponse;
					trt__GetStreamUri.ProfileToken = token;
					trt__GetStreamUri.StreamSetup = soap_new_tt__StreamSetup(mediaProxy->soap);
					trt__GetStreamUri.StreamSetup->Transport = soap_new_tt__Transport(mediaProxy->soap);
					trt__GetStreamUri.StreamSetup->Transport->Protocol = tt__TransportProtocol__RTSP;
					addSecurity(mediaProxy->soap, username, password);						
					if (mediaProxy->GetStreamUri(&trt__GetStreamUri, &trt__GetStreamUriResponse) == SOAP_OK)
					{
						std::cout << "\tMediaUri:" << trt__GetStreamUriResponse.MediaUri->Uri << std::endl;
					}
				}
			}
		}	
		
		if (recordingProxy.get() != NULL)
		{
			std::cout << "=>Recording::GetRecordings" << std::endl;											
			_trc__GetRecordings         trc__GetRecordings;
			_trc__GetRecordingsResponse trc__GetRecordingsResponse;
			addSecurity(recordingProxy->soap, username, password);						
			if (recordingProxy->GetRecordings(&trc__GetRecordings, &trc__GetRecordingsResponse) == SOAP_OK)
			{
				for (auto recording : trc__GetRecordingsResponse.RecordingItem)
				{
					std::string token(recording->RecordingToken);
					std::cout << "\tRecording:" << token << std::endl;
					
					if (replayProxy.get() != NULL)
					{
						_trp__GetReplayUri         trp__GetReplayUri;
						_trp__GetReplayUriResponse trp__GetReplayUriResponse;
						trp__GetReplayUri.RecordingToken = token;
						addSecurity(replayProxy->soap, username, password);						
						if (replayProxy->GetReplayUri(&trp__GetReplayUri, &trp__GetReplayUriResponse) == SOAP_OK)
						{
							std::cout << "\tReplay Uri:" << trp__GetReplayUriResponse.Uri << std::endl;
						}
					}
				}
			}
			
			std::cout << "=>Recording::GetRecordingJobs" << std::endl;											
			_trc__GetRecordingJobs         trc__GetRecordingJobs;
			_trc__GetRecordingJobsResponse trc__GetRecordingJobsResponse;
			addSecurity(recordingProxy->soap, username, password);						
			if (recordingProxy->GetRecordingJobs(&trc__GetRecordingJobs, &trc__GetRecordingJobsResponse) == SOAP_OK)
			{
				for (auto job : trc__GetRecordingJobsResponse.JobItem)
				{
					std::string token(job->JobToken);
					std::cout << "\tRecordingJob:" << token << std::endl;
					
					if (job->JobConfiguration)
					{
						std::cout << "\tRecordingToken:" << job->JobConfiguration->RecordingToken << std::endl;						
						for (auto src : job->JobConfiguration->Source)
						{
							if (src->SourceToken)
							{
								std::cout << "\tSourceToken:" << src->SourceToken->Token << std::endl;						
								std::cout << "\tSourceType:" << src->SourceToken->Type << std::endl;						
							}
						}
					}
				}
			}
		}
		
		if (receiverProxy.get() != NULL)
		{
			std::cout << "=>Receiver::GetReceivers" << std::endl;								
			_trv__GetReceivers         trv__GetReceivers;
			_trv__GetReceiversResponse trv__GetReceiversResponse;
			addSecurity(receiverProxy->soap, username, password);									
			if (receiverProxy->GetReceivers(&trv__GetReceivers, &trv__GetReceiversResponse) == SOAP_OK)
			{
				for (auto receiver : trv__GetReceiversResponse.Receivers)
				{
					std::string token(receiver->Token);
					std::cout << "\tReceiver:" << token << std::endl;	

					if (receiver->Configuration)
					{
						std::cout << "\tReceiver mode:" << receiver->Configuration->Mode << " uri:" << receiver->Configuration->MediaUri << std::endl;	
					}
				}
			}
		}
		
		if (eventProxy.get() != NULL)
		{
			std::cout << "=>Event::CreatePullPoint" << std::endl;								
			_tev__CreatePullPointSubscription         tev__CreatePullPointSubscription;
			_tev__CreatePullPointSubscriptionResponse tev__CreatePullPointSubscriptionResponse;
			addSecurity(eventProxy->soap, username, password);						
			if (eventProxy->CreatePullPointSubscription(&tev__CreatePullPointSubscription, &tev__CreatePullPointSubscriptionResponse) == SOAP_OK)
			{
				std::cout << "\tPullpoint Url:" << tev__CreatePullPointSubscriptionResponse.SubscriptionReference.Address << std::endl;
				
				// pull
				PullPointSubscriptionBindingProxy pullpoint(tev__CreatePullPointSubscriptionResponse.SubscriptionReference.Address);
				soap_wsse_add_Security(pullpoint.soap);
				
				_tev__PullMessages         tev__PullMessages;
				tev__PullMessages.Timeout = "PT10S";
				tev__PullMessages.MessageLimit = 100;
				_tev__PullMessagesResponse tev__PullMessagesResponse;
				if (pullpoint.PullMessages(&tev__PullMessages, &tev__PullMessagesResponse) == SOAP_OK)
				{
					for (auto msg : tev__PullMessagesResponse.wsnt__NotificationMessage)
					{
						std::cout << "\tMessage:" << msg->Message.__any << std::endl;
					}
				}
				
				// subscribe
				NotificationConsumerBindingService consumer;
				consumer.soap->accept_timeout=5;
				consumer.bind(NULL,9090,10);
				std::thread th(&NotificationConsumerBindingService::run, &consumer, 0);
				
				NotificationProducerBindingProxy producer(tev__CreatePullPointSubscriptionResponse.SubscriptionReference.Address);
				soap_wsse_add_Security(producer.soap);
				
				_wsnt__Subscribe         wsnt__Subscribe;
				std::string url("http://127.0.0.1:9090");
				wsnt__Subscribe.ConsumerReference.Address = strcpy((char*)soap_malloc(producer.soap, url.size()+1), url.c_str());
				_wsnt__SubscribeResponse wsnt__SubscribeResponse;
				if (producer.Subscribe(&wsnt__Subscribe, &wsnt__SubscribeResponse) == SOAP_OK)
				{
				}	
				th.join();
			}
		}
	}
	
        return 0;
}
示例#6
0
bool Parser::Impl::parseTestList()
{
    // test-list := "(" test *("," test) ")"

    if(!obtainToken() || atEnd())
        return false;

    if(token() != Lexer::Special || tokenValue() != "(")
        return false;
    if(scriptBuilder())
        scriptBuilder()->testListStart();
    consumeToken();

    // generic while/switch construct for comma-separated lists. See
    // parseStringList() for another one. Any fix here is like to apply there, too.
    bool lastWasComma = true;
    while(!atEnd())
    {
        if(!obtainToken())
            return false;

        switch(token())
        {
            case Lexer::None:
                break;
            case Lexer::Special:
                assert(tokenValue().length() == 1);
                assert(tokenValue()[0].latin1());
                switch(tokenValue()[0].latin1())
                {
                    case ')':
                        consumeToken();
                        if(lastWasComma)
                        {
                            makeError(Error::ConsecutiveCommasInTestList);
                            return false;
                        }
                        if(scriptBuilder())
                            scriptBuilder()->testListEnd();
                        return true;
                    case ',':
                        consumeToken();
                        if(lastWasComma)
                        {
                            makeError(Error::ConsecutiveCommasInTestList);
                            return false;
                        }
                        lastWasComma = true;
                        break;
                    default:
                        makeError(Error::NonStringInStringList);
                        return false;
                }
                break;

            case Lexer::Identifier:
                if(!lastWasComma)
                {
                    makeError(Error::MissingCommaInTestList);
                    return false;
                }
                else
                {
                    lastWasComma = false;
                    if(!parseTest())
                    {
                        assert(error());
                        return false;
                    }
                }
                break;

            default:
                makeUnexpectedTokenError(Error::NonTestInTestList);
                return false;
        }
    }

    makeError(Error::PrematureEndOfTestList);
    return false;
}
示例#7
0
bool Parser::Impl::parseStringList()
{
    // string-list := "[" string *("," string) "]" / string
    //  ;; if there is only a single string, the brackets are optional
    //
    // However, since strings are already handled separately from
    // string lists in parseArgument(), our ABNF is modified to:
    // string-list := "[" string *("," string) "]"

    if(!obtainToken() || atEnd())
        return false;

    if(token() != Lexer::Special || tokenValue() != "[")
        return false;

    if(scriptBuilder())
        scriptBuilder()->stringListArgumentStart();
    consumeToken();

    // generic while/switch construct for comma-separated lists. See
    // parseTestList() for another one. Any fix here is like to apply there, too.
    bool lastWasComma = true;
    while(!atEnd())
    {
        if(!obtainToken())
            return false;

        switch(token())
        {
            case Lexer::None:
                break;
            case Lexer::Special:
                assert(tokenValue().length() == 1);
                switch(tokenValue()[0].latin1())
                {
                    case ']':
                        consumeToken();
                        if(lastWasComma)
                        {
                            makeError(Error::ConsecutiveCommasInStringList);
                            return false;
                        }
                        if(scriptBuilder())
                            scriptBuilder()->stringListArgumentEnd();
                        return true;
                    case ',':
                        consumeToken();
                        if(lastWasComma)
                        {
                            makeError(Error::ConsecutiveCommasInStringList);
                            return false;
                        }
                        lastWasComma = true;
                        break;
                    default:
                        makeError(Error::NonStringInStringList);
                        return false;
                }
                break;

            case Lexer::QuotedString:
            case Lexer::MultiLineString:
                if(!lastWasComma)
                {
                    makeError(Error::MissingCommaInStringList);
                    return false;
                }
                lastWasComma = false;
                if(scriptBuilder())
                    scriptBuilder()->stringListEntry(tokenValue(), token() == Lexer::MultiLineString, QString::null);
                consumeToken();
                break;

            default:
                makeError(Error::NonStringInStringList);
                return false;
        }
    }

    makeError(Error::PrematureEndOfStringList);
    return false;
}
示例#8
0
bool CBotVar::RestoreState(FILE* pf, CBotVar* &pVar)
{
    unsigned short        w, wi, prv, st;
    float        ww;
    CBotString    name, s;

    delete pVar;

                pVar    = NULL;
    CBotVar*    pNew    = NULL;
    CBotVar*    pPrev    = NULL;

    while ( true )            // retrieves a list
    {
        if (!ReadWord(pf, w)) return false;                        // private or type?
        if ( w == 0 ) return true;

        CBotString defnum;
        if ( w == 200 )
        {
            if (!ReadString(pf, defnum)) return false;            // number with identifier
            if (!ReadWord(pf, w)) return false;                    // type
        }

        prv = 100; st = 0;
        if ( w >= 100 )
        {
            prv = w;
            if (!ReadWord(pf, st)) return false;                // static
            if (!ReadWord(pf, w)) return false;                    // type
        }

        if ( w == CBotTypClass ) w = CBotTypIntrinsic;            // necessarily intrinsic

        if (!ReadWord(pf, wi)) return false;                    // init ?

        if (!ReadString(pf, name)) return false;                // variable name

        CBotToken token(name, CBotString());

        switch (w)
        {
        case CBotTypInt:
        case CBotTypBoolean:
            pNew = CBotVar::Create(&token, w);                        // creates a variable
            if (!ReadWord(pf, w)) return false;
            pNew->SetValInt(static_cast<short>(w), defnum);
            break;
        case CBotTypFloat:
            pNew = CBotVar::Create(&token, w);                        // creates a variable
            if (!ReadFloat(pf, ww)) return false;
            pNew->SetValFloat(ww);
            break;
        case CBotTypString:
            pNew = CBotVar::Create(&token, w);                        // creates a variable
            if (!ReadString(pf, s)) return false;
            pNew->SetValString(s);
            break;

        // returns an intrinsic object or element of an array
        case CBotTypIntrinsic:
        case CBotTypArrayBody:
            {
                CBotTypResult    r;
                long            id;
                if (!ReadType(pf, r))  return false;                // complete type
                if (!ReadLong(pf, id) ) return false;

//                if (!ReadString(pf, s)) return false;
                {
                    CBotVar* p = NULL;
                    if ( id ) p = CBotVarClass::Find(id) ;

                    pNew = new CBotVarClass(&token, r);                // directly creates an instance
                                                                    // attention cptuse = 0
                    if ( !RestoreState(pf, (static_cast<CBotVarClass*>(pNew))->m_pVar)) return false;
                    pNew->SetIdent(id);

                    if ( p != NULL )
                    {
                        delete pNew;
                        pNew = p;            // resume known element 
                    }
                }
            }
            break;

        case CBotTypPointer:
        case CBotTypNullPointer:
            if (!ReadString(pf, s)) return false;
            {
                pNew = CBotVar::Create(&token, CBotTypResult(w, s));// creates a variable
//                CBotVarClass* p = NULL;
                long id;
                ReadLong(pf, id);
//                if ( id ) p = CBotVarClass::Find(id);        // found the instance (made by RestoreInstance)

                // returns a copy of the original instance
                CBotVar* pInstance = NULL;
                if ( !CBotVar::RestoreState( pf, pInstance ) ) return false;
                (static_cast<CBotVarPointer*>(pNew))->SetPointer( pInstance );            // and point over

//                if ( p != NULL ) (static_cast<CBotVarPointer*>(pNew))->SetPointer( p );    // rather this one

            }
            break;

        case CBotTypArrayPointer:
            {
                CBotTypResult    r;
                if (!ReadType(pf, r))  return false;

                pNew = CBotVar::Create(&token, r);                        // creates a variable

                // returns a copy of the original instance
                CBotVar* pInstance = NULL;
                if ( !CBotVar::RestoreState( pf, pInstance ) ) return false;
                (static_cast<CBotVarPointer*>(pNew))->SetPointer( pInstance );            // and point over
            }
            break;
        default:
            ASM_TRAP();
        }

        if ( pPrev != NULL ) pPrev->m_next = pNew;
        if ( pVar == NULL  ) pVar = pNew;

        pNew->m_binit = wi;        //        pNew->SetInit(wi);
        pNew->SetStatic(st);
        pNew->SetPrivate(prv-100);
        pPrev = pNew;
    }
    return true;
}
示例#9
0
static void lineparse()
{
  char* tokn, *env, *envName, *tmp1, *tmp2;
  long l, in_template;
  varname[0] = '\0';
  objname[0] = '\0';
  if (!strcmp(tok1,"end")) {strcpy(curstruct,"--"); in_template = 0;}
  if (!strcmp(tok1,"structure")) {strcpy(curstruct,tok2);}
  if (!strcmp(tok1,"database")) ;
  if (!strcmp(tok1,"incname")) ;
  if (!strcmp(tok1,"index")) ;
  if (!strcmp(tok1,"provide")) ;
  if (!strcmp(tok1,"parent")) ;
  if (!strcmp(tok1,"child")) ;
  if (!strcmp(tok1,"dimension")) ;
  if (!strcmp(tok1,"template")) {in_template = 1; strcpy(curstruct,tok2);
    n_instance = 0;}
  if (!strcmp(tok1,"command")) {in_template = 1; strcpy(curstruct,tok2);}
  if (!strcmp(tok1,"include")) {  /* switch input to specified file */
 /*
 ** Commented out, we use absolute path name in the includes. 
 ** This allows us to go to more than one directory..
 */
/*    strcpy(filename,dbpath); */ 
/*    strcat(filename,tok2); */
/*
** We now implement translation of environmental variable
**
*/
      if (tok2[0] == '$') {
         tmp1 = strchr(&tok2[1], '/');
         if (tmp1 == NULL) {
              fprintf(stderr, "DBin error, Unkonw path %s\n", tok2);
              return;
         }
         envName = (char *) malloc(sizeof(char) * (strlen(tok2)+1));
         strcpy(envName, &tok2[1]);
         tmp2 = strchr(envName, '/'); *tmp2 = '\0';
         env = getenv(envName);
         free(envName);
         
         if (env == NULL) { 
              fprintf(stderr, "DBin error, Unkonw path %s\n", tok2);
              return;
         }
         strcpy(filename,env); l = strlen(env); filename[l] = '/'; l++;
         strcpy(&filename[l], tmp1);
            
      } else  strcpy(filename, tok2);
    inc_depth++;
  } 
  if (!strcmp(tok1,"make")) {
    n_instance++;
    strcpy(varname,"TEMPLATE_");
    strcat(varname,stlower(tok2));
  }
  if (!strcmp(tok1,"define")) {
      /* get first token (name) from values list */
    tokn = token(&values," \t");
    strcpy(varname,"TEMPLATE_");
    strcat(varname,tok2);
    strcpy(objname,tok2);
    strcat(objname,"_");
    strcat(objname,tokn);
  }
  if (!strcmp(tok1,"call")) {
      /* get first token (name) from values list */
    tokn = token(&values," \t");
    strcpy(varname,"COMMAND_");
    strcat(varname,tok2);
  }
  if (!strncmp(tok1,"int",3) || !strcmp(tok1,"real") || !strcmp(tok1,"double") ||
      !strncmp(tok1,"char",4) || !strcmp(tok1,"material") ) {
    if ((! strncmp(curstruct,"--",2)) && (in_template == 0)) {
      fprintf(stdout,"dbin: Parameter \"%s\" not in structure; ignored:\n",
              tok2);
      fprintf(stdout,"      %s\n",line);
    } else {
        /* parse values */
      strcpy(varname,curstruct);
      strcat(varname,".");
      strcat(varname,tok2);
      getvalues();
    }
  }
}
示例#10
0
// primaryExpr ::= NUMBER
//               | STRING
//               | variable
//               | function '(' exprList ')'
//               | '(' expr ')'
std::unique_ptr<Expr> FlowParser::primaryExpr()
{
	FNTRACE();

	static struct {
		const char* ident;
		long long nominator;
		long long denominator;
	} units[] = {
		{ "byte", 1, 1 },
		{ "kbyte", 1024llu, 1 },
		{ "mbyte", 1024llu * 1024, 1 },
		{ "gbyte", 1024llu * 1024 * 1024, 1 },
		{ "tbyte", 1024llu * 1024 * 1024 * 1024, 1 },
		{ "bit", 1, 8 },
		{ "kbit", 1024llu, 8 },
		{ "mbit", 1024llu * 1024, 8 },
		{ "gbit", 1024llu * 1024 * 1024, 8 },
		{ "tbit", 1024llu * 1024 * 1024 * 1024, 8 },
		{ "sec", 1, 1 },
		{ "min", 60llu, 1 },
		{ "hour", 60llu * 60, 1 },
		{ "day", 60llu * 60 * 24, 1 },
		{ "week", 60llu * 60 * 24 * 7, 1 },
		{ "month", 60llu * 60 * 24 * 30, 1 },
		{ "year", 60llu * 60 * 24 * 365, 1 },
		{ nullptr, 1, 1 }
	};

	FlowLocation loc(location());

	switch (token()) {
		case FlowToken::Ident: {
			std::string name = stringValue();
			nextToken();

			Symbol* symbol = scope()->lookup(name, Lookup::All);
			if (!symbol) {
                // XXX assume that given symbol is a auto forward-declared handler.
                Handler* href = (Handler*) globalScope()->appendSymbol(std::make_unique<Handler>(name, loc));
				return std::make_unique<HandlerRefExpr>(href, loc);
			}

			if (auto variable = dynamic_cast<Variable*>(symbol))
				return std::make_unique<VariableExpr>(variable, loc);

			if (auto handler = dynamic_cast<Handler*>(symbol))
				return std::make_unique<HandlerRefExpr>(handler, loc);

			if (symbol->type() == Symbol::BuiltinFunction) {
				if (token() != FlowToken::RndOpen)
					return std::make_unique<FunctionCallExpr>((BuiltinFunction*) symbol, ExprList()/*args*/, loc);

				nextToken();
                ExprList args;
				bool rv = listExpr(args);
				consume(FlowToken::RndClose);
				if (!rv) return nullptr;
				return std::make_unique<FunctionCallExpr>((BuiltinFunction*) symbol, std::move(args), loc);
			}

			reportError("Unsupported symbol type of '%s' in expression.", name.c_str());
			return nullptr;
		}
		case FlowToken::Boolean: {
			std::unique_ptr<BoolExpr> e = std::make_unique<BoolExpr>(booleanValue(), loc);
			nextToken();
			return std::move(e);
		}
		case FlowToken::RegExp: {
			std::unique_ptr<RegExpExpr> e = std::make_unique<RegExpExpr>(RegExp(stringValue()), loc);
			nextToken();
			return std::move(e);
		}
		case FlowToken::InterpolatedStringFragment:
			return interpolatedStr();
		case FlowToken::String:
		case FlowToken::RawString: {
			std::unique_ptr<StringExpr> e = std::make_unique<StringExpr>(stringValue(), loc);
			nextToken();
			return std::move(e);
		}
		case FlowToken::Number: { // NUMBER [UNIT]
			auto number = numberValue();
			nextToken();

			if (token() == FlowToken::Ident) {
				std::string sv(stringValue());
				for (size_t i = 0; units[i].ident; ++i) {
					if (sv == units[i].ident
						|| (sv[sv.size() - 1] == 's' && sv.substr(0, sv.size() - 1) == units[i].ident))
					{
						nextToken(); // UNIT
						number = number * units[i].nominator / units[i].denominator;
						loc.update(end());
						break;
					}
				}
			}
			return std::make_unique<NumberExpr>(number, loc);
		}
		case FlowToken::IP: {
			std::unique_ptr<IPAddressExpr> e = std::make_unique<IPAddressExpr>(lexer_->ipValue(), loc);
			nextToken();
			return std::move(e);
		}
		case FlowToken::Cidr: {
			std::unique_ptr<CidrExpr> e = std::make_unique<CidrExpr>(lexer_->cidr(), loc);
			nextToken();
			return std::move(e);
		}
		case FlowToken::StringType:
		case FlowToken::NumberType:
		case FlowToken::BoolType:
			return castExpr();
		case FlowToken::Begin: { // lambda-like inline function ref
			char name[64];
			static unsigned long i = 0;
            ++i;
			snprintf(name, sizeof(name), "__lambda_%lu", i);

			FlowLocation loc = location();
			auto st = std::make_unique<SymbolTable>(scope(), name);
			enter(st.get());
			std::unique_ptr<Stmt> body = compoundStmt();
			leave();

			if (!body)
				return nullptr;

			loc.update(body->location().end);

			Handler* handler = new Handler(name, std::move(st), std::move(body), loc);
			// TODO (memory leak): add handler to unit's global scope, i.e. via:
			//       - scope()->rootScope()->insert(handler);
			//       - unit_->scope()->insert(handler);
			//       to get free'd
			return std::make_unique<HandlerRefExpr>(handler, loc);
		}
		case FlowToken::RndOpen: {
			nextToken();
			std::unique_ptr<Expr> e = expr();
			consume(FlowToken::RndClose);
			e->setLocation(loc.update(end()));
			return e;
		}
		default:
			TRACE(1, "Expected primary expression. Got something... else.");
			reportUnexpectedToken();
			return nullptr;
	}
}
示例#11
0
bool CDropbox::HasAccessToken()
{
	ptrA token(db_get_sa(NULL, MODULE, "TokenSecret"));
	return token != NULL;
}
示例#12
0
// }}}
// {{{ error mgnt
void FlowParser::reportUnexpectedToken()
{
	reportError("Unexpected token '%s'", token().c_str());
}
示例#13
0
std::unique_ptr<Stmt> FlowParser::callStmt()
{
	// callStmt ::= NAME ['(' exprList ')' | exprList] (';' | LF)
	// 			 | NAME '=' expr [';' | LF]
	// NAME may be a builtin-function, builtin-handler, handler-name, or variable.

	FNTRACE();

	FlowLocation loc(location());
	std::string name = stringValue();
	nextToken(); // IDENT

	std::unique_ptr<Stmt> stmt;
	Symbol* callee = scope()->lookup(name, Lookup::All);
	if (!callee) {
        // XXX assume that given symbol is a auto forward-declared handler.
        callee = (Handler*) globalScope()->appendSymbol(std::make_unique<Handler>(name, loc));
	}

	bool callArgs = false;
	switch (callee->type()) {
		case Symbol::Variable: { // var '=' expr (';' | LF)
			if (!consume(FlowToken::Assign))
				return nullptr;

			std::unique_ptr<Expr> value = expr();
			if (!value)
				return nullptr;

			stmt = std::make_unique<AssignStmt>(static_cast<Variable*>(callee), std::move(value), loc.update(end()));
			break;
		}
		case Symbol::BuiltinHandler:
		case Symbol::BuiltinFunction:
			stmt = std::make_unique<CallStmt>(loc, (Callable*) callee);
			callArgs = true;
			break;
		case Symbol::Handler:
			stmt = std::make_unique<CallStmt>(loc, (Callable*) callee);
            break;
		default:
			break;
	}

	if (callArgs) {
		CallStmt* callStmt = static_cast<CallStmt*>(stmt.get());

		if (token() == FlowToken::RndOpen) {
			nextToken();
            ExprList args;
			bool rv = listExpr(args);
			consume(FlowToken::RndClose);
			if (!rv) return nullptr;
			callStmt->setArgs(std::move(args));
		}
		else if (lexer_->line() == loc.begin.line) {
            ExprList args;
			if (!listExpr(args))
                return nullptr;
			callStmt->setArgs(std::move(args));
		}

        // match call parameters
        FlowVM::Signature sig;
        sig.setName(name);
        sig.setReturnType(callStmt->callee()->signature().returnType()); // XXX cheetah
        std::vector<FlowType> argTypes;
        for (const auto& arg: callStmt->args()) {
            argTypes.push_back(arg->getType());
        }
        sig.setArgs(argTypes);
        if (sig != callStmt->callee()->signature()) {
            reportError("Callee parameter type signature mismatch: %s passed, but %s expected.\n", 
                    sig.to_s().c_str(), callStmt->callee()->signature().to_s().c_str());
            return nullptr;
        }
	}

	switch (token()) {
		case FlowToken::If:
		case FlowToken::Unless:
			return postscriptStmt(std::move(stmt));
		case FlowToken::Semicolon:
			// stmt ';'
			nextToken();
			stmt->location().update(end());
			return stmt;
		default:
			if (stmt->location().end.line != lexer_->line())
				return stmt;

			reportUnexpectedToken();
			return nullptr;
	}
}
示例#14
0
NitLexer::Token NitLexer::lex()
{
	int tk;

	while (_ch != CHAR_EOS)
	{
		whitespace();

		switch (_ch)
		{
		case CHAR_EOS:
			return token(TK_EOS);

		case '/':
			next();
			switch (_ch)
			{
			case '*': next(); blockComment(); continue;
			case '/': lineComment(); continue;
			case '=': next(); return token(TK_DIVEQ);
			default:  return token('/');
			}
			break;

		case '=':
			next();
			if (_ch == '>') { next(); return token(TK_LAMBDA); }
			if (_ch == '=') { next(); return token(TK_EQ); }
			return token('=');

		case '<':
			next();
			if (_ch == '<') { next(); return token(TK_SHIFTL); }
			if (_ch != '=') return token('<');
			next();
			if (_ch == '>') { next(); return token(TK_THREEWAYSCMP); }
			return token(TK_LE);

		case '>':
			next();
			if (_ch == '=') { next(); return token(TK_GE); }
			if (_ch != '>') return token('>');
			next();
			if (_ch == '>') { next(); return token(TK_USHIFTR); }
			return token(TK_SHIFTR);

		case '!':
			next();
			if (_ch == '=') { next(); return token(TK_NE); }
			return token('!');

		case '@':
			next();
			if (_ch != '"' && _ch != '\'') return token('@');
			if ((tk = readString(_ch, '@')) != -1) return token(tk);
			return error("error parsing verbatim string");

		case '"':
		case '\'':
			if (readString(_ch) != -1) return token(TK_STRING_VALUE);
			return error("error parsing the string");

		case '{': case '}': case '(': case ')': case '[': case ']':
		case ';': case ',': case '?': case '^': case '~': case '$':
			return token(next());

		case '.':
			next();
			if (_ch != '.') return token('.');
			next();
			if (_ch != '.') return error("invalid token '..'");
			next();
			return token(TK_VARPARAMS);

		case '&':
			next();
			if (_ch == '&') { next(); return token(TK_AND); }
			return token('&');

		case '|':
			next();
			if (_ch == '|') { next(); return token(TK_OR); }
			return token('|');

		case ':':
			next();
			if (_ch == '=') { next(); return token(TK_NEWSLOT); }
			if (_ch == '>') { next(); return token(TK_WITHREF); }
			if (_ch == ':') { next(); return token(TK_DOUBLE_COLON); }
			return token(':');

		case '*':
			next();
			if (_ch == '=') { next(); return token(TK_MULEQ); }
			return token('*');

		case '%':
			next();
			if (_ch == '=') { next(); return token(TK_MODEQ); }
			return token('%');

		case '-':
			next();
			if (_ch == '=') { next(); return token(TK_MINUSEQ); }
			if (_ch == '-') { next(); return token(TK_MINUSMINUS); }
			return token('-');

		case '+':
			next();
			if (_ch == '=') { next(); return token(TK_PLUSEQ); }
			if (_ch == '+') { next(); return token(TK_PLUSPLUS); }
			return token('+');

		default:
			if (isdigit(_ch))
				return token(readNumber());
			else if (isId(_ch))
				return token(readId());
			else
				return error("unexpected character '%c'", _ch);
		}		
	}

	return token(TK_EOS);
}
示例#15
0
bool Parser::Impl::isStringToken() const
{
    return token() == Lexer::QuotedString ||
           token() == Lexer::MultiLineString ;
}
示例#16
0
/*FUNCTION*-------------------------------------------------------------
*
*  Function Name  : _usb_ehci_add_interrupt_xfer_to_periodic_list
*  Returned Value : None
*  Comments       :
*        Queue the transfer in the EHCI hardware Periodic schedule list
*END*-----------------------------------------------------------------*/
uint_32 _usb_ehci_add_interrupt_xfer_to_periodic_list
   (
      /* [IN] the USB Host state structure */
      _usb_host_handle                 handle,

      /* The pipe descriptor to queue */            
      PIPE_DESCRIPTOR_STRUCT_PTR       pipe_descr_ptr,
      
      /* [IN] the transfer parameters struct */
      PIPE_TR_STRUCT_PTR               pipe_tr_ptr
   )
{ /* Body */
   USB_HOST_STATE_STRUCT_PTR                    usb_host_ptr;
   VUSB20_REG_STRUCT_PTR                        dev_ptr;
   ACTIVE_QH_MGMT_STRUCT_PTR                    active_list_member_ptr, temp_list_ptr;

   EHCI_QH_STRUCT_PTR                           QH_ptr = NULL;
   EHCI_QH_STRUCT_PTR                           prev_QH_ptr = NULL;
   EHCI_QTD_STRUCT_PTR                          first_QTD_ptr, temp_QTD_ptr;
   PIPE_DESCRIPTOR_STRUCT_PTR                   pipe_for_queue = NULL;
   uint_32                                      cmd_val,sts_val;
   uint_32                                      H_bit = 1;
   uint_32                                      interrupt_sched_mask = 1;
   boolean                                      init_periodic_list = FALSE;
   boolean                                      found_existing_q_head = FALSE;

   /* QH initialization fields */
   uint_32                       control_ep_flag = 0;
   uint_32                       split_completion_mask = 1;
   uint_32                       data_toggle_control = 0, item_type = 0;
   uint_8                        mult = 0, period = 0;
   uint_32_ptr                   temp_frame_list_ptr = NULL;


   usb_host_ptr = (USB_HOST_STATE_STRUCT_PTR)handle;
   dev_ptr = (VUSB20_REG_STRUCT_PTR)usb_host_ptr->DEV_PTR;

   /****************************************************************************
   QTD MAKING    
   ****************************************************************************/

   /* Initialize the QTDs for the Queue Head */
   first_QTD_ptr = (EHCI_QTD_STRUCT_PTR)_usb_ehci_init_Q_element(
                                          handle,pipe_descr_ptr, pipe_tr_ptr
                                          );

#ifdef DEBUG_INFO
      {
         uint_32 token = EHCI_MEM_READ(first_QTD_ptr->TOKEN);
         
         printf("QTD queued Top QTD Token=%x\n"
            "   Status=%x,PID code=%x,error code=%x,page=%x,IOC=%x,Bytes=%x,Toggle=%x\n",
          token
          (token&0xFF),
          (token >> 8)&0x3,
          (token >> 10) &0x3,
          (token >> 12)&0x7,
          (token >> 15)&0x1,
          (token >> 16)&0x7FFF,
          (token&EHCI_QTD_DATA_TOGGLE) >>31);
      }
#endif


   /****************************************************************************
   Obtain the QH for this pipe
   ****************************************************************************/
   QH_ptr = (EHCI_QH_STRUCT_PTR) pipe_descr_ptr->QH_FOR_THIS_PIPE;
   

   /****************************************************************************
   Ensure that this QH is in the list of active QHs for interrupt pipe
   ****************************************************************************/

   /******************************************************************
   If active list does not exist, we make a new list and this is the
   first member of the list. Otherwise we append the list at the end.
   *******************************************************************/
   if(usb_host_ptr->ACTIVE_INTERRUPT_PERIODIC_LIST_PTR == NULL)
   {

      active_list_member_ptr = (ACTIVE_QH_MGMT_STRUCT_PTR)USB_mem_alloc_zero(sizeof(ACTIVE_QH_MGMT_STRUCT));

      if (!active_list_member_ptr) 
      {
         return USB_log_error(__FILE__,__LINE__,USBERR_ALLOC);
      }

      usb_host_ptr->ACTIVE_INTERRUPT_PERIODIC_LIST_PTR = active_list_member_ptr;

      /****************************************************************
      Connect the QH with the active list
      ****************************************************************/
      active_list_member_ptr->QH_PTR = (EHCI_QH_STRUCT_PTR)QH_ptr;
      active_list_member_ptr->FIRST_QTD_PTR = (EHCI_QTD_STRUCT_PTR)first_QTD_ptr;

      /****************************************************************
      Connect the QH with the QTD
      ****************************************************************/
      EHCI_MEM_WRITE(QH_ptr->ALT_NEXT_QTD_LINK_PTR,EHCI_QTD_T_BIT);
      EHCI_MEM_WRITE(QH_ptr->NEXT_QTD_LINK_PTR,(uint_32)first_QTD_ptr);

   }
   else
   {

      /****************************************************************
      search the list to find if this QH aleady exists in the list. If
      not, allocate a new list member and add to the list or else move
      on with no action.
      ****************************************************************/
      
      temp_list_ptr = (ACTIVE_QH_MGMT_STRUCT_PTR) \
                        usb_host_ptr->ACTIVE_INTERRUPT_PERIODIC_LIST_PTR;
                        

       while (temp_list_ptr!=NULL) {
         if(temp_list_ptr->QH_PTR == QH_ptr) 
         {
            found_existing_q_head = TRUE;
            break;
         }
         if (temp_list_ptr->NEXT_ACTIVE_QH_MGMT_STRUCT_PTR == NULL)
            break;
         
         temp_list_ptr = (ACTIVE_QH_MGMT_STRUCT_PTR) temp_list_ptr->NEXT_ACTIVE_QH_MGMT_STRUCT_PTR;
      }

      if (temp_list_ptr==NULL) {
         return USB_log_error(__FILE__,__LINE__,USBERR_ERROR);
      }
   

      /****************************************************************
      If no QH not found a new list memeber or connect QTDs to the existing one
      ****************************************************************/

         
      if(!found_existing_q_head)
      {
   
         active_list_member_ptr = (ACTIVE_QH_MGMT_STRUCT_PTR)USB_mem_alloc_zero(sizeof(ACTIVE_QH_MGMT_STRUCT));

         if (!active_list_member_ptr) 
         {
            return USB_log_error(__FILE__,__LINE__,USBERR_ALLOC);
         }

         temp_list_ptr->NEXT_ACTIVE_QH_MGMT_STRUCT_PTR = active_list_member_ptr; 

         /****************************************************************
         Connect the QH with the active list
         ****************************************************************/
         active_list_member_ptr->QH_PTR = (EHCI_QH_STRUCT_PTR)QH_ptr;
         active_list_member_ptr->FIRST_QTD_PTR = (EHCI_QTD_STRUCT_PTR)first_QTD_ptr;

         /****************************************************************
         Connect the QH with the QTD
         ****************************************************************/
         EHCI_MEM_WRITE(QH_ptr->ALT_NEXT_QTD_LINK_PTR,EHCI_QTD_T_BIT);
         EHCI_MEM_WRITE(QH_ptr->NEXT_QTD_LINK_PTR,(uint_32)first_QTD_ptr);

      }
      else
      {
         /****************************************************************
         update the active interrupt list now.
         ****************************************************************/
         temp_QTD_ptr = (EHCI_QTD_STRUCT_PTR)temp_list_ptr->FIRST_QTD_PTR;
      
         if (( ((uint_32)temp_QTD_ptr) & EHCI_QTD_T_BIT) || (temp_QTD_ptr == NULL)) {
            temp_list_ptr->FIRST_QTD_PTR = (EHCI_QTD_STRUCT_PTR)first_QTD_ptr;
         } else {
            while (!(EHCI_MEM_READ(temp_QTD_ptr->NEXT_QTD_PTR) & EHCI_QTD_T_BIT)) {
               temp_QTD_ptr = (EHCI_QTD_STRUCT_PTR)EHCI_MEM_READ(temp_QTD_ptr->NEXT_QTD_PTR);
            }

            EHCI_MEM_WRITE(temp_QTD_ptr->NEXT_QTD_PTR,(uint_32)first_QTD_ptr);

         } /*else*/

         /****************************************************************
         This case is arrived when the QH is active and there is a 
         possibility that it may also have active QTDs.
         ****************************************************************/
         if (EHCI_MEM_READ(QH_ptr->NEXT_QTD_LINK_PTR) & EHCI_QTD_T_BIT) {
            EHCI_MEM_WRITE(QH_ptr->ALT_NEXT_QTD_LINK_PTR,EHCI_QTD_T_BIT);
            EHCI_MEM_WRITE(QH_ptr->NEXT_QTD_LINK_PTR,(uint_32)first_QTD_ptr);
          }
          
         
       
      }/*else*/
   
   } /*else */

#ifdef DEBUG_INFO
   { 
      uint_32 token = EHCI_MEM_READ(first_QTD_ptr->TOKEN);
      printf("_usb_ehci_add_interrupt_xfer_to_periodic_list: QH =%x\n"
             "  Status=%x,PID code=%x,error code=%x,page=%x,IOC=%x,Bytes=%x,Toggle=%x\n",
             token,
             (token&0xFF),
             (token >> 8)&0x3,
             (token >> 10) &0x3,
             (token >> 12)&0x7,
             (token >> 15)&0x1,
             (token>> 16)&0x7FFF,
             (token)&EHCI_QTD_DATA_TOGGLE) >>31);
   }
#endif


   /****************************************************************************
   if periodic schedule is not already enabled, enable it.
   ****************************************************************************/
   sts_val = EHCI_REG_READ(dev_ptr->REGISTERS.OPERATIONAL_HOST_REGISTERS.USB_STS);

   if(!(sts_val & EHCI_STS_PERIODIC_SCHEDULE))
   {

         cmd_val = EHCI_REG_READ(dev_ptr->REGISTERS.OPERATIONAL_HOST_REGISTERS.USB_CMD);

      /****************************************************************************
      write the address of the periodic list in to the periodic base register
      ****************************************************************************/
         EHCI_REG_WRITE(dev_ptr->REGISTERS.OPERATIONAL_HOST_REGISTERS.PERIODIC_LIST_BASE_ADDR, 
                        (uint_32) usb_host_ptr->ALIGNED_PERIODIC_LIST_BASE_ADDR);

      /****************************************************************************
      wait until we can enable  the periodic schedule.
      ****************************************************************************/
         while ((cmd_val & EHCI_USBCMD_PERIODIC_SCHED_ENABLE) !=
                (EHCI_REG_READ(dev_ptr->REGISTERS.OPERATIONAL_HOST_REGISTERS.USB_STS) & EHCI_STS_PERIODIC_SCHEDULE)) {
      }
         

      /****************************************************************************
      enable the schedule now.
      ****************************************************************************/
            
      EHCI_REG_WRITE(dev_ptr->REGISTERS.OPERATIONAL_HOST_REGISTERS.USB_CMD,(cmd_val | EHCI_USBCMD_PERIODIC_SCHED_ENABLE)); 
   }
   return USB_OK;

} /* EndBody */
示例#17
0
bool Parser::Impl::parseCommand()
{
    // command   := identifier arguments ( ";" / block )
    // arguments := *argument [ test / test-list ]
    // block     := "{" *command "}"
    // our ABNF:
    // block     := "{" [ command-list ] "}"

    if(atEnd())
        return false;

    //
    // identifier
    //

    if(!obtainToken() || token() != Lexer::Identifier)
        return false;

    if(scriptBuilder())
        scriptBuilder()->commandStart(tokenValue());
    consumeToken();

    //
    // *argument
    //

    if(!obtainToken())
        return false;

    if(atEnd())
    {
        makeError(Error::MissingSemicolonOrBlock);
        return false;
    }

    if(isArgumentToken() && !parseArgumentList())
    {
        assert(error());
        return false;
    }

    //
    // test / test-list
    //

    if(!obtainToken())
        return false;

    if(atEnd())
    {
        makeError(Error::MissingSemicolonOrBlock);
        return false;
    }

    if(token() == Lexer::Special && tokenValue() == "(")      // test-list
    {
        if(!parseTestList())
        {
            assert(error());
            return false;
        }
    }
    else if(token() == Lexer::Identifier)        // should be test:
    {
        if(!parseTest())
        {
            assert(error());
            return false;
        }
    }

    //
    // ";" / block
    //

    if(!obtainToken())
        return false;

    if(atEnd())
    {
        makeError(Error::MissingSemicolonOrBlock);
        return false;
    }

    if(token() != Lexer::Special)
    {
        makeUnexpectedTokenError(Error::ExpectedBlockOrSemicolon);
        return false;
    }

    if(tokenValue() == ";")
        consumeToken();
    else if(tokenValue() == "{")      // block
    {
        if(!parseBlock())
            return false; // it's an error since we saw '{'
    }
    else
    {
        makeError(Error::MissingSemicolonOrBlock);
        return false;
    }

    if(scriptBuilder())
        scriptBuilder()->commandEnd();
    return true;
}
示例#18
0
文件: ruserpass.c 项目: ella13/nmh
void
ruserpass(char *host, char **aname, char **apass)
{
    char *hdir, buf[BUFSIZ];
    int t, usedefault = 0;
    struct stat stb;

    hdir = getenv("HOME");
    if (hdir == NULL)
	hdir = ".";
    snprintf(buf, sizeof(buf), "%s/.netrc", hdir);
    cfile = fopen(buf, "r");
    if (cfile == NULL) {
	if (errno != ENOENT)
	    perror(buf);
	goto done;
    }

    while ((t = token())) {
	switch(t) {
	case DEFAULT:
	    usedefault = 1;
	    /* FALL THROUGH */

	case MACH:
	    if (!usedefault) {
		if (token() != ID)
		    continue;
		/*
		 * Allow match either for user's host name.
		 */
		if (mh_strcasecmp(host, tokval) == 0)
		    goto match;
		continue;
	    }
match:
	    while ((t = token()) && t != MACH && t != DEFAULT) {
		switch(t) {
		case LOGIN:
		    if (token() && *aname == 0) {
			*aname = mh_xmalloc((size_t) strlen(tokval) + 1);
			strcpy(*aname, tokval);
		    }
		    break;
		case PASSWD:
		    if (fstat(fileno(cfile), &stb) >= 0 &&
			(stb.st_mode & 077) != 0) {
			/* We make this a fatal error to force the user to correct it */
			advise(NULL, "Error - ~/.netrc file must not be world or group readable.");
			adios(NULL, "Remove password or correct file permissions.");
		    }
		    if (token() && *apass == 0) {
			*apass = mh_xmalloc((size_t) strlen(tokval) + 1);
			strcpy(*apass, tokval);
		    }
		    break;
		case ACCOUNT:
		    break;

		case MACDEF:
		    goto done_close;
		    break;
		default:
		    fprintf(stderr, "Unknown .netrc keyword %s\n", tokval);
		    break;
		}
	    }
	    goto done;
	}
    }

done_close:
    fclose(cfile);

done:
    if (!*aname) {
	char tmp[80];
	char *myname;

	if ((myname = getlogin()) == NULL) {
	    struct passwd *pp;

	    if ((pp = getpwuid (getuid())) != NULL)
		myname = pp->pw_name;
	}
	printf("Name (%s:%s): ", host, myname);

	fgets(tmp, sizeof(tmp) - 1, stdin);
	tmp[strlen(tmp) - 1] = '\0';
	if (*tmp != '\0') {
	    myname = tmp;
	}

	*aname = mh_xmalloc((size_t) strlen(myname) + 1);
	strcpy (*aname, myname);
    }

    if (!*apass) {
	char prompt[256];
	char *mypass;

	snprintf(prompt, sizeof(prompt), "Password (%s:%s): ", host, *aname);
	mypass = nmh_getpass(prompt);
	
	if (*mypass == '\0') {
	    mypass = *aname;
	}

	*apass = mh_xmalloc((size_t) strlen(mypass) + 1);
	strcpy (*apass, mypass);
    }

}
示例#19
0
bool Parser::Impl::parseTest()
{
    // test := identifier arguments
    // arguments := *argument [ test / test-list ]

    //
    // identifier
    //

    if(!obtainToken() || atEnd())
        return false;

    if(token() != Lexer::Identifier)
        return false;

    if(scriptBuilder())
        scriptBuilder()->testStart(tokenValue());
    consumeToken();

    //
    // *argument
    //

    if(!obtainToken())
        return false;

    if(atEnd())    // a test w/o args
        goto TestEnd;

    if(isArgumentToken() && !parseArgumentList())
    {
        assert(error());
        return false;
    }

    //
    // test / test-list
    //

    if(!obtainToken())
        return false;

    if(atEnd())    // a test w/o nested tests
        goto TestEnd;

    if(token() == Lexer::Special && tokenValue() == "(")      // test-list
    {
        if(!parseTestList())
        {
            assert(error());
            return false;
        }
    }
    else if(token() == Lexer::Identifier)        // should be test:
    {
        if(!parseTest())
        {
            assert(error());
            return false;
        }
    }

TestEnd:
    if(scriptBuilder())
        scriptBuilder()->testEnd();
    return true;
}
示例#20
0
bool WintermuteEngine::getGameInfo(const Common::FSList &fslist, Common::String &name, Common::String &caption) {
	bool retVal = false;
	caption = name = "(invalid)";
	Common::SeekableReadStream *stream = nullptr;
	// Quick-fix, instead of possibly breaking the persistence-system, let's just roll with it
	BaseFileManager *fileMan = new BaseFileManager(Common::UNK_LANG, true);
	fileMan->registerPackages(fslist);
	stream = fileMan->openFile("startup.settings", false, false);

	// The process is as follows: Check the "GAME=" tag in startup.settings, to decide where the
	// game-settings are (usually "default.game"), then look into the game-settings to find
	// the NAME = and CAPTION = tags, to use them to generate a gameid and extras-field

	Common::String settingsGameFile = "default.game";
	// If the stream-open failed, lets at least attempt to open the default game file afterwards
	// so, we don't call it a failure yet.
	if (stream) {
		while (!stream->eos() && !stream->err()) {
			Common::String line = stream->readLine();
			line.trim(); // Get rid of indentation
			// Expect "SETTINGS {" or comment, or empty line
			if (line.size() == 0 || line[0] == ';' || (line.contains("{"))) {
				continue;
			} else {
				// We are looking for "GAME ="
				Common::StringTokenizer token(line, "=");
				Common::String key = token.nextToken();
				Common::String value = token.nextToken();
				if (value.size() == 0) {
					continue;
				}
				if (value[0] == '\"') {
					value.deleteChar(0);
				} else {
					continue;
				}
				if (value.lastChar() == '\"') {
					value.deleteLastChar();
				}
				if (key == "GAME") {
					settingsGameFile = value;
					break;
				}
			}
		}
	}

	delete stream;
	stream = fileMan->openFile(settingsGameFile, false, false);
	if (stream) {
		// We do some manual parsing here, as the engine needs gfx to be initalized to do that.
		while (!stream->eos() && !stream->err()) {
			Common::String line = stream->readLine();
			line.trim(); // Get rid of indentation
			// Expect "GAME {" or comment, or empty line
			if (line.size() == 0 || line[0] == ';' || (line.contains("{"))) {
				continue;
			} else {
				Common::StringTokenizer token(line, "=");
				Common::String key = token.nextToken();
				Common::String value = token.nextToken();
				if (value.size() == 0) {
					continue;
				}
				if (value[0] == '\"') {
					value.deleteChar(0);
				} else {
					continue;    // not a string
				}
				if (value.lastChar() == '\"') {
					value.deleteLastChar();
				}
				if (key == "NAME") {
					retVal = true;
					name = value;
				} else if (key == "CAPTION") {
					retVal = true;
					// Remove any translation tags, if they are included in the game description.
					// This can potentially remove parts of a string that has translation tags
					// and contains a "/" in its description (e.g. /tag/Name start / name end will
					// result in "name end"), but it's a very rare case, and this code is just used
					// for fallback anyway.
					if (value.hasPrefix("/")) {
						value.deleteChar(0);
						while (value.contains("/")) {
							value.deleteChar(0);
						}
					}
					caption = value;
				}
			}
		}
		delete stream;
	}
	delete fileMan;
	BaseEngine::destroy();
	return retVal;
}
示例#21
0
int
ruserpass (const char *host, const char **aname, const char **apass)
{
	char *hdir, *buf, *tmp;
	char myname[1024], *mydomain;
	int t, usedefault = 0;
	struct stat64 stb;

	hdir = __libc_secure_getenv("HOME");
	if (hdir == NULL) {
		/* If we can't get HOME, fail instead of trying ".",
		   which is no improvement. This really should call
		   getpwuid(getuid()).  */
		/*hdir = ".";*/
		return -1;
	}

	buf = alloca (strlen (hdir) + 8);

	__stpcpy (__stpcpy (buf, hdir), "/.netrc");
	cfile = fopen(buf, "rce");
	if (cfile == NULL) {
		if (errno != ENOENT)
			warn("%s", buf);
		return (0);
	}
	/* No threads use this stream.  */
	__fsetlocking (cfile, FSETLOCKING_BYCALLER);
	if (__gethostname(myname, sizeof(myname)) < 0)
		myname[0] = '\0';
	mydomain = __strchrnul(myname, '.');
next:
	while ((t = token())) switch(t) {

	case DEFAULT:
		usedefault = 1;
		/* FALL THROUGH */

	case MACHINE:
		if (!usedefault) {
			if (token() != ID)
				continue;
			/*
			 * Allow match either for user's input host name
			 * or official hostname.  Also allow match of
			 * incompletely-specified host in local domain.
			 */
			if (__strcasecmp(host, tokval) == 0)
				goto match;
/*			if (__strcasecmp(hostname, tokval) == 0)
				goto match;
			if ((tmp = strchr(hostname, '.')) != NULL &&
			    __strcasecmp(tmp, mydomain) == 0 &&
			    __strncasecmp(hostname, tokval, tmp-hostname) == 0 &&
			    tokval[tmp - hostname] == '\0')
				goto match; */
			if ((tmp = strchr(host, '.')) != NULL &&
			    __strcasecmp(tmp, mydomain) == 0 &&
			    __strncasecmp(host, tokval, tmp - host) == 0 &&
			    tokval[tmp - host] == '\0')
				goto match;
			continue;
		}
	match:
		while ((t = token()) && t != MACHINE && t != DEFAULT) switch(t) {

		case LOGIN:
			if (token()) {
				if (*aname == 0) {
				  char *newp;
				  newp = malloc((unsigned) strlen(tokval) + 1);
				  if (newp == NULL)
				    {
				      warnx(_("out of memory"));
				      goto bad;
				    }
				  *aname = strcpy(newp, tokval);
				} else {
					if (strcmp(*aname, tokval))
						goto next;
				}
			}
			break;
		case PASSWD:
			if (strcmp(*aname, "anonymous") &&
			    fstat64(fileno(cfile), &stb) >= 0 &&
			    (stb.st_mode & 077) != 0) {
	warnx(_("Error: .netrc file is readable by others."));
	warnx(_("Remove password or make file unreadable by others."));
				goto bad;
			}
			if (token() && *apass == 0) {
				char *newp;
				newp = malloc((unsigned) strlen(tokval) + 1);
				if (newp == NULL)
				  {
				    warnx(_("out of memory"));
				    goto bad;
				  }
				*apass = strcpy(newp, tokval);
			}
			break;
		case ACCOUNT:
			break;
		case MACDEF:
			break;
		default:
			warnx(_("Unknown .netrc keyword %s"), tokval);
			break;
		}
		goto done;
	}
done:
	(void) fclose(cfile);
	return (0);
bad:
	(void) fclose(cfile);
	return (-1);
}
示例#22
0
void *index_memory(void *p)
{
  pos_lists_t *Z0 = new pos_lists_t;

  uint32_t used_buffer_size = 0;

  thread_arg_t *arg = (thread_arg_t *) p;
  int id = arg->id;
  double t1 = gettimeofday_sec();
  std::cout << "index_memory starts for Z0-" << id << std::endl;

  MeCab::Tagger *tagger = MeCab::createTagger(0, NULL);

  uint32_t doc_id = 1;
  std::string line;
  while (1) {
    pthread_mutex_lock(&fin_mutex);
    if (!getline(fin, line)) {
      pthread_mutex_unlock(&fin_mutex);
      break;
    }
    pthread_mutex_unlock(&fin_mutex);

    std::vector<std::string> items;
    boost::split(items, line, boost::is_any_of(""));

    /*
    if (items.size() != 6) { continue; }
    line = items[4] + " " + items[5];
    */
    if (items.size() != 3) { continue; }
    line = items[1] + " " + items[2];

    unsigned int offset = 0;
    pos_lists_tmp_t Ztmp;
    const MeCab::Node *node_ = tagger->parseToNode(line.c_str());
    for (; node_; node_ = node_->next) {
      if (node_->stat == MECAB_BOS_NODE ||
        node_->stat == MECAB_EOS_NODE) {
        continue; 
      }   
      std::string token(node_->surface, node_->length);
      unsigned int length = get_length_of((const unsigned char *) token.c_str());
      // mecab ignores spaces in default 
      // but they must be counted as offset from the beginning
      int head_space_len =  node_->rlength - node_->length;
      offset += head_space_len > 0 ? head_space_len : 0;

      pos_lists_tmp_t::iterator itr = Ztmp.find(token);
      if (itr != Ztmp.end()) {
        itr->second.push_back(offset);
        ++(itr->second.at(1));
      } else {
        pos_list_t p;
        p.push_back(doc_id);
        p.push_back(1);
        p.push_back(offset);
        std::pair<std::string, pos_list_t> pos;
        pos.first = token;
        pos.second = p;
        Ztmp.insert(pos);
      }
      //tokens_.push_back(Term(token, length, offset));
      offset += length;
    }

    pos_lists_tmp_t::iterator itr_end = Ztmp.end();
    for (pos_lists_tmp_t::iterator itr = Ztmp.begin();
         itr != itr_end; ++itr) {

      std::pair<std::string, pos_list_t> pos = *itr;
      LMergeAddToken(indexes, *Z0, pos, used_buffer_size);
    }
    //std::cout << "doc: " << doc_id << std::endl;
    ++doc_id;
    Ztmp.clear();
    pos_lists_tmp_t().swap(Ztmp);

    if (used_buffer_size > FLUSH_THRESHOLD) {
      pthread_mutex_lock(&flush_buffer_queue_mutex);
      ++flush_buffer_queue_size;
      push_or_merge(Z0);
      //flush_buffer_queue.push_back(Z0);
      if (flush_buffer_queue_size == NUM_FLUSH_BUFFER) {
        // flushing (Z0 is cleard inside Z0_flush)
        Z0_flush(indexes);
        flush_buffer_queue_size = 0;
      }
      Z0 = new pos_lists_t;
      pthread_mutex_unlock(&flush_buffer_queue_mutex);
      used_buffer_size = 0;
      // [TODO] clear doc_id
    }
  }
  if (used_buffer_size > 0) {
    pthread_mutex_lock(&flush_buffer_queue_mutex);
    //flush_buffer_queue.push_back(Z0);
    ++flush_buffer_queue_size;
    push_or_merge(Z0);
    if (flush_buffer_queue_size == NUM_FLUSH_BUFFER) {
      Z0_flush(indexes);
    }
    pthread_mutex_unlock(&flush_buffer_queue_mutex);
  }
  delete tagger;
  double t2 = gettimeofday_sec();
  std::cout << "index_memory ends for Z0-" << id << " - time: " << t2 -t1 << std::endl;

  return NULL;
}
int ONVIF::AudioEncoderConfiguration::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = QObject::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    if (_c == QMetaObject::InvokeMetaMethod) {
        if (_id < 13)
            qt_static_metacall(this, _c, _id, _a);
        _id -= 13;
    } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
        if (_id < 13)
            *reinterpret_cast<int*>(_a[0]) = -1;
        _id -= 13;
    }
#ifndef QT_NO_PROPERTIES
      else if (_c == QMetaObject::ReadProperty) {
        void *_v = _a[0];
        switch (_id) {
        case 0: *reinterpret_cast< QString*>(_v) = token(); break;
        case 1: *reinterpret_cast< QString*>(_v) = name(); break;
        case 2: *reinterpret_cast< int*>(_v) = useCount(); break;
        case 3: *reinterpret_cast< QString*>(_v) = encoding(); break;
        case 4: *reinterpret_cast< int*>(_v) = bitrate(); break;
        case 5: *reinterpret_cast< int*>(_v) = sampleRate(); break;
        case 6: *reinterpret_cast< QString*>(_v) = type(); break;
        case 7: *reinterpret_cast< QString*>(_v) = ipv4Address(); break;
        case 8: *reinterpret_cast< QString*>(_v) = ipv6Address(); break;
        case 9: *reinterpret_cast< int*>(_v) = port(); break;
        case 10: *reinterpret_cast< int*>(_v) = ttl(); break;
        case 11: *reinterpret_cast< bool*>(_v) = autoStart(); break;
        case 12: *reinterpret_cast< QString*>(_v) = sessionTimeout(); break;
        }
        _id -= 13;
    } else if (_c == QMetaObject::WriteProperty) {
        void *_v = _a[0];
        switch (_id) {
        case 0: setToken(*reinterpret_cast< QString*>(_v)); break;
        case 1: setName(*reinterpret_cast< QString*>(_v)); break;
        case 2: setUseCount(*reinterpret_cast< int*>(_v)); break;
        case 3: setEncoding(*reinterpret_cast< QString*>(_v)); break;
        case 4: setBitrate(*reinterpret_cast< int*>(_v)); break;
        case 5: setSampleRate(*reinterpret_cast< int*>(_v)); break;
        case 6: setType(*reinterpret_cast< QString*>(_v)); break;
        case 7: setIpv4Address(*reinterpret_cast< QString*>(_v)); break;
        case 8: setIpv6Address(*reinterpret_cast< QString*>(_v)); break;
        case 9: setPort(*reinterpret_cast< int*>(_v)); break;
        case 10: setTtl(*reinterpret_cast< int*>(_v)); break;
        case 11: setAutoStart(*reinterpret_cast< bool*>(_v)); break;
        case 12: setSessionTimeout(*reinterpret_cast< QString*>(_v)); break;
        }
        _id -= 13;
    } else if (_c == QMetaObject::ResetProperty) {
        _id -= 13;
    } else if (_c == QMetaObject::QueryPropertyDesignable) {
        _id -= 13;
    } else if (_c == QMetaObject::QueryPropertyScriptable) {
        _id -= 13;
    } else if (_c == QMetaObject::QueryPropertyStored) {
        _id -= 13;
    } else if (_c == QMetaObject::QueryPropertyEditable) {
        _id -= 13;
    } else if (_c == QMetaObject::QueryPropertyUser) {
        _id -= 13;
    } else if (_c == QMetaObject::RegisterPropertyMetaType) {
        if (_id < 13)
            *reinterpret_cast<int*>(_a[0]) = -1;
        _id -= 13;
    }
#endif // QT_NO_PROPERTIES
    return _id;
}
示例#24
0
TCodParser::TCodAttr TCodParser::AttrName()
    {
    TCodAttr attr( ECodUnknownAttr );

    const TText* start = iCurP;
    while
        (
            iCurP < iEndP &&
            !IsControl() &&
            !IsSeparator() &&
            *iCurP != KCodCarriageRet &&
            *iCurP != KCodLineFeed
        )
        {
        iCurP++;
        }

    TPtrC token( start, iCurP - start );
    if ( !token.Length() )
        {
        Error( KErrCodInvalidDescriptor );
        }
    else if ( !token.Compare( KCodName ) )
        {
        attr = ECodName;
        }
    else if ( !token.Compare( KCodVendor ) )
        {
        attr = ECodVendor;
        }
    else if ( !token.Compare( KCodDescription ) )
        {
        attr = ECodDescription;
        }
    else if ( !token.Compare( KCodUrl ) )
        {
        attr = ECodUrl;
        }
    else if ( !token.Compare( KCodSize ) )
        {
        attr = ECodSize;
        }
    else if ( !token.Compare( KCodType ) )
        {
        attr = ECodType;
        }
    else if ( !token.Compare( KCodInstallNotify ) )
        {
        attr = ECodInstallNotify;
        }
    else if ( !token.Compare( KCodNextUrl ) )
        {
        attr = ECodNextUrl;
        }
    else if ( !token.Compare( KCodNextUrlAtError ) )
        {
        attr = ECodNextUrlAtError;
        }
    else if ( !token.Compare( KCodInfoUrl ) )
        {
        attr = ECodInfoUrl;
        }
    else if ( !token.Compare( KCodPrice ) )
        {
        attr = ECodPrice;
        }
    else if ( !token.Compare( KCodIcon ) )
        {
        attr = ECodIcon;
        }

    CLOG(( EParse, 4, _L("TCodParser::AttrName token<%S> attr(%d)"), \
        &token, attr ));
    return attr;
    }
示例#25
0
int AppSettings::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = QObject::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    if (_c == QMetaObject::InvokeMetaMethod) {
        if (_id < 13)
            qt_static_metacall(this, _c, _id, _a);
        _id -= 13;
    }
#ifndef QT_NO_PROPERTIES
    else if (_c == QMetaObject::ReadProperty) {
        void *_v = _a[0];
        switch (_id) {
        case 0:
            *reinterpret_cast< QString*>(_v) = token();
            break;
        case 1:
            *reinterpret_cast< QUrl*>(_v) = address();
            break;
        case 2:
            *reinterpret_cast< QString*>(_v) = email();
            break;
        case 3:
            *reinterpret_cast< QString*>(_v) = username();
            break;
        case 4:
            *reinterpret_cast< QString*>(_v) = password();
            break;
        case 5:
            *reinterpret_cast< QString*>(_v) = userid();
            break;
        }
        _id -= 6;
    } else if (_c == QMetaObject::WriteProperty) {
        void *_v = _a[0];
        switch (_id) {
        case 0:
            setToken(*reinterpret_cast< QString*>(_v));
            break;
        case 1:
            setAddress(*reinterpret_cast< QUrl*>(_v));
            break;
        case 2:
            setEmail(*reinterpret_cast< QString*>(_v));
            break;
        case 3:
            setUsername(*reinterpret_cast< QString*>(_v));
            break;
        case 4:
            setPassword(*reinterpret_cast< QString*>(_v));
            break;
        case 5:
            setUserid(*reinterpret_cast< QString*>(_v));
            break;
        }
        _id -= 6;
    } else if (_c == QMetaObject::ResetProperty) {
        _id -= 6;
    } else if (_c == QMetaObject::QueryPropertyDesignable) {
        _id -= 6;
    } else if (_c == QMetaObject::QueryPropertyScriptable) {
        _id -= 6;
    } else if (_c == QMetaObject::QueryPropertyStored) {
        _id -= 6;
    } else if (_c == QMetaObject::QueryPropertyEditable) {
        _id -= 6;
    } else if (_c == QMetaObject::QueryPropertyUser) {
        _id -= 6;
    }
#endif // QT_NO_PROPERTIES
    return _id;
}
示例#26
0
void Lexer::storeToken(Token::Kind kind) {
    Token token(kind);
    storeToken(token, location);
}
////////////////////////////////////////////////////////////////////////////////
///Parse function declaration after rl_cmd or rl_cmd_p
bool Class::parse( iglexer& lex, charstr& templarg_, const dynarray<charstr>& namespcs, dynarray<paste_block>* pasters, dynarray<MethodIG::Arg>& irefargs )
{
    templarg.swap(templarg_);
    namespaces = namespcs;

    namespaces.for_each([this](const charstr& v){ namespc << v << "::"; });
    if(namespc)
        ns.set_from_range(namespc.ptr(), namespc.ptre()-2);

    token t = templarg;
    if(!t.is_empty()) {
        templsub << char('<');
        for( int i=0; !t.is_empty(); ++i ) {
            token x = t.cut_left(' ');

            if(i)  templsub << ", ";
            templsub << t.cut_left(',');
        }
        templsub << char('>');
    }

    hash_map<charstr,uint,hash<token>> map_overloads;
    typedef hash_map<charstr,uint,hash<token>>::value_type t_val;

    int ncontinuable_errors = 0;

    if( !lex.matches(lex.IDENT, classname) )
        lex.set_err() << "expecting class name\n";
    else {
        const lexer::lextoken& tok = lex.last();

        noref = true;

        while( lex.next() != '{' ) {
            if( tok.end() ) {
                lex.set_err() << "unexpected end of file\n";
                return false;
            }
            if( tok == ';' )
                return false;

            noref = false;
        }

        //ignore nested blocks
        //lex.ignore(lex.CURLY, true);

        dynarray<charstr> commlist;

        int mt;
        while( 0 != (mt=lex.find_method(classname, commlist)) )
        {
            if(mt<0) {
                //interface definitions
                const lexer::lextoken& tok = lex.last();

                bool classifc = tok == lex.IFC_CLASS;
                bool classvar = tok == lex.IFC_CLASS_VAR;
                bool classvirtual = tok == lex.IFC_CLASS_VIRTUAL;
                bool extfn = tok == lex.IFC_FNX;
                bool extev = tok == lex.IFC_EVENTX;
                bool bimplicit = false;
                bool bdestroy = false;
                int8 binternal = 0;
                int8 bnocapture = 0;
                int8 bcapture = 0;

                charstr extname, implname;
                if(extev || extfn) {
                    //parse external name
                    lex.match('(');

                    if(extfn && lex.matches('~'))
                        bdestroy = true;
                    else {
                        while(int k = lex.matches_either('!', '-', '+'))
                            (&binternal)[k-1]++;

                        lex.matches(lex.IDENT, extname);

                        /*binternal = lex.matches('!');
                        bimplicit = lex.matches('@');
                        if(bimplicit) {
                            lex.match(lex.IDENT, implname);
                            lex.matches(lex.IDENT, extname);
                        }
                        else {
                            lex.matches(lex.IDENT, extname);
                            bimplicit = lex.matches('@');
                            if(bimplicit)
                                lex.match(lex.IDENT, implname);
                        }*/
                    }
                    lex.match(')');
                }

                if(classifc || classvar || classvirtual)
                {
                    if(iface.size() > 0)
                        iface.last()->check_interface(lex);

                    //parse interface declaration
                    Interface* ifc = iface.add();
                    ifc->nifc_methods = 0;
                    ifc->comments.takeover(commlist);
                    ifc->bvirtual = classvirtual;

                    lex.match('(');
                    ifc->bdefaultcapture = lex.matches_either('+', '-') == 1;
                    ifc->name = lex.match(lex.IDENT);

                    while(lex.matches("::")) {
                        ifc->nss.add()->swap(ifc->name);
                        ifc->name = lex.match(lex.IDENT);
                    }

                    if(lex.matches(':')) {
                        //a base class for the interface
                        ifc->baseclass = ifc->base = lex.match(lex.IDENT);
                        while(lex.matches("::")) {
                            ifc->base << "::";
                            token bc = lex.match(lex.IDENT);
                            ifc->base << bc;
                            ifc->baseclass.set(ifc->base.ptre()-bc.len(), ifc->base.ptre());
                        }
                    }

                    lex.match(',');
                    ifc->relpath = lex.match(lex.DQSTRING);

                    if(classvar) {
                        lex.match(',');
                        ifc->varname = lex.match(lex.IDENT);
                    }

                    lex.match(')');

                    ifc->parse_docs();

                    pasters->for_each( [ifc](paste_block& b){
                        if(b.cond.is_empty() || ifc->full_name_equals(b.cond))
                            *ifc->pasters.add() = b.block;
                    });
                    //ifc->pasters = pasters;
                }
                else if(extev || tok == lex.IFC_EVENT)
                {
                    //event declaration may be commented out if the method is a duplicate (with multiple interfaces)
                    bool slcom = lex.enable(lex.SLCOM, false);
                    bool mlcom = lex.ignore(lex.MLCOM, false);
                    int duplicate = lex.matches_either("//", "/*");
                    lex.enable(lex.SLCOM, slcom);

                    //parse event declaration
                    if(iface.size() == 0) {
                        out << (lex.prepare_exception() << "error: no preceding interface declared\n");
                        lex.clear_err();
                        ++ncontinuable_errors;
                    }
                    else if(iface.last()->varname.is_empty()) {
                        out << (lex.prepare_exception() << "error: events can be used only with bidirectional interfaces\n");
                        lex.clear_err();
                        ++ncontinuable_errors;
                    }

                    Interface* ifc = iface.last();
                    MethodIG* m = ifc->event.add();

                    m->comments.takeover(commlist);
                    m->binternal = binternal>0;
                    m->bimplicit = bimplicit;

                    if(bimplicit) {
                        lex.match(';', "error: implicit events must not be declared");

                        if(implname == "on_create") {
                            m->name = ifc->on_create_ev = extname ? token(extname) : "on_create";

                            m->ret.type = m->ret.basetype = m->ret.fulltype = "void";
                        }
                        else {
                            out << (lex.prepare_exception() << "error: unrecognized implicit event\n");
                            lex.clear_err();
                            ++ncontinuable_errors;
                        }
                    }
                    else {
                        if(!m->parse(lex, classname, namespc, irefargs))
                            ++ncontinuable_errors;

                        if(duplicate == 2) {
                            lex.match(';');
                            lex.match("*/");
                        }
                        lex.ignore(lex.MLCOM, mlcom);


                        if(extname) {
                            m->intname.takeover(m->name);
                            m->name.takeover(extname);
                        }
                        else
                            m->intname = m->name;

                        if(m->bstatic) {
                            out << (lex.prepare_exception() << "error: interface event cannot be static\n");
                            lex.clear_err();
                            ++ncontinuable_errors;
                        }
                    }
 
                    m->parse_docs();
                }
                else if(extfn || tok == lex.IFC_FN)
                {
                    //method declaration may be commented out if the method is a duplicate (with multiple interfaces)
                    bool slcom = lex.enable(lex.SLCOM, false);
                    bool mlcom = lex.ignore(lex.MLCOM, false);
                    int duplicate = lex.matches_either("//", "/*");
                    lex.enable(lex.SLCOM, slcom);


                    //parse function declaration
                    if(iface.size() == 0)
                        throw lex.set_err() << "error: no preceding interface declared\n";

                    Interface* ifc = iface.last();
                    MethodIG* m = ifc->method.add();

                    m->comments.takeover(commlist);
                    m->binternal = binternal>0;

                    if(!m->parse(lex, classname, namespc, irefargs))
                        ++ncontinuable_errors;

                    if(duplicate == 2) {
                        lex.match(';');
                        lex.match("*/");
                    }
                    lex.ignore(lex.MLCOM, mlcom);


                    m->parse_docs();

                    int capture = ifc->bdefaultcapture ? 1 : 0;
                    capture -= bnocapture;
                    capture += bcapture;

                    m->bcapture = capture>0 && !m->bconst && !m->bstatic;

                    if(bcapture>bnocapture && !m->bcapture) {
                        out << (lex.prepare_exception() << "warning: const and static methods aren't captured\n");
                        lex.clear_err();
                    }

                    if(extname) {
                        m->intname.takeover(m->name);
                        m->name.takeover(extname);
                    }
                    else
                        m->intname = m->name;

                    if(m->boperator) {
                        if(m->bconst && ifc->oper_get>=0) {
                            out << (lex.prepare_exception() << "error: property getter already defined\n");
                            lex.clear_err();
                            ++ncontinuable_errors;
                        }
                        if(!m->bconst && ifc->oper_set>=0) {
                            out << (lex.prepare_exception() << "error: property getter already defined\n");
                            lex.clear_err();
                            ++ncontinuable_errors;
                        }

                        if(m->bconst)
                            ifc->oper_get = int(ifc->method.size()-1);
                        else
                            ifc->oper_set = int(ifc->method.size()-1);
                    }

                    if(!m->bstatic)
                        ++iface.last()->nifc_methods;

                    if(m->bstatic && bdestroy) {
                        out << "error: method to call on interface release cannot be static\n";
                        lex.clear_err();
                        ++ncontinuable_errors;
                    }

                    if(bimplicit) {
                        if(m->name == "on_create") {
                            if(m->ret.type != "void" && m->args.size() != 0) {
                                out << (lex.prepare_exception() << "error: invalid format for an on_create method\n");
                                lex.clear_err();
                                ++ncontinuable_errors;
                            }
                            ifc->on_create = m->intname;
                        }

                        ifc->method.pop();
                    }

                    m->bdestroy = bdestroy;

                    if(bdestroy) {
                        //mark and move to the first pos
                        if(ifc->destroy.name) {
                            out << (lex.prepare_exception() << "error: interface release method already specified\n");
                            lex.clear_err();
                            ++ncontinuable_errors;
                        }

                        ifc->destroy = *m;
                        ifc->method.move(m-ifc->method.ptr(), 0, 1);
                    }

                    if(m->bstatic && m->args.size() == 0 && ifc->default_creator.name.is_empty())
                        ifc->default_creator = *m;
                }
                else {
                    //produce a warning for other misplaced keywords
                    out << (lex.prepare_exception() << "warning: misplaced keyword\n");
                    lex.clear_err();
                }
            }
            else {
                //rlcmd
                Method* m = method.add();
                m->parse(lex, mt);

                static token renderer = "renderer";
                if( classname == renderer )
                    m->bstatic = true;          //special handling for the renderer

                uint* v = const_cast<uint*>( map_overloads.find_value(m->name) );
                if(v)
                    m->overload << ++*v;
                else
                    map_overloads.insert_key_value(m->name, 0);
            }
        }

        if(iface.size() > 0)
            iface.last()->check_interface(lex);
    }

    return ncontinuable_errors ? false : lex.no_err();
}
示例#28
0
void Lexer::makeOperatorToken(const Location& startLocation) {
    Operator::Kind op;
    const char* tStart = startLocation.ptr;
    switch (*tStart) {
    case '=':
        if (isNextChar('=', tStart)) {
            op = Operator::Equal;
            location.stepColumn();
        } else {
            op = Operator::Assignment;
        }
        break;
    case '!':
        if (isNextChar('=', tStart)) {
            op = Operator::NotEqual;
            location.stepColumn();
        } else {
            op = Operator::LogicalNegation;
        }
        break;
    case ':':
        if (isNextChar('=', tStart)) {
            op = Operator::AssignmentExpression;
            location.stepColumn();
        } else {
            op = Operator::Colon;
        }
        break;
    case '>':
        if (isNextChar('=', tStart)) {
            op = Operator::GreaterOrEqual;
            location.stepColumn();
        } else if (isNextChar('>', tStart)) {
            op = Operator::RightShift;
            location.stepColumn();
        } else {
            op = Operator::Greater;
        }
        break;
    case '<':
        if (isNextChar('=', tStart)) {
            op = Operator::LessOrEqual;
            location.stepColumn();
        } else if (isNextChar('<', tStart)) {
            op = Operator::LeftShift;
            location.stepColumn();
        } else {
            op = Operator::Less;
        }
        break;
    case '&':
        if (isNextChar('&', tStart)) {
            op = Operator::LogicalAnd;
            location.stepColumn();
        } else {
            op = Operator::BitwiseAnd;
        }
        break;
    case '|':
        if (isNextChar('|', tStart)) {
            op = Operator::LogicalOr;
            location.stepColumn();
        } else {
            op = Operator::BitwiseOr;
        }
        break;
    case '+':
        if (isNextChar('+', tStart)) {
            op = Operator::Increment;
            location.stepColumn();
        } else if (isNextChar('=', tStart)) {
            op = Operator::AdditionAssignment;
            location.stepColumn();
        } else {
            op = Operator::Addition;
        }
        break;
    case '-':
        if (isNextChar('-', tStart)) {
            op = Operator::Decrement;
            location.stepColumn();
        } else if (isNextChar('=', tStart)) {
            op = Operator::SubtractionAssignment;
            location.stepColumn();
        } else if (isNextChar('>', tStart)) {
            op = Operator::Arrow;
            location.stepColumn();
        } else {
            op = Operator::Subtraction;
        }
        break;
    case '*':
        if (isNextChar('=', tStart)) {
            op = Operator::MultiplicationAssignment;
            location.stepColumn();
        } else {
            op = Operator::Multiplication;
        }
        break;
    case '/':
        if (isNextChar('=', tStart)) {
            op = Operator::DivisionAssignment;
            location.stepColumn();
        } else {
            op = Operator::Division;
        }
        break;
    case '.':
        if (isNextChar('.', tStart)) {
            if (isNextChar('.', tStart + 1)) {
                op = Operator::Range;
                location.stepColumn();
            } else {
                op = Operator::Wildcard;
            }
            location.stepColumn();
        } else {
            op = Operator::Dot;
        }
        break;
    case '%':
        op = Operator::Modulo;
        break;
    case ',':
        op = Operator::Comma;
        break;
    case '(':
        op = Operator::OpenParentheses;
        break;
    case ')':
        op = Operator::CloseParentheses;
        break;
    case '{':
        op = Operator::OpenBrace;
        break;
    case '}':
        op = Operator::CloseBrace;
        break;
    case '[':
        op = Operator::OpenBracket;
        break;
    case ']':
        op = Operator::CloseBracket;
        break;
    case ';':
        op = Operator::Semicolon;
        break;
    case '?':
        op = Operator::Question;
        break;
    case '_':
        op = Operator::Placeholder;
        break;
    case '^':
        op = Operator::BitwiseXor;
        break;
    case '~':
        op = Operator::BitwiseNot;
        break;
    default:
        break;
    }
    Token token(op);
    storeToken(token, startLocation);
}
void
testServiceRegistry::externalServiceTest()
{
   art::AssertHandler ah;

   {
      std::unique_ptr<DummyService> dummyPtr(new DummyService);
      dummyPtr->value_ = 2;
      art::ServiceToken token(art::ServiceRegistry::createContaining(dummyPtr));
      {
         art::ServiceRegistry::Operate operate(token);
         art::ServiceHandle<DummyService> dummy;
         CPPUNIT_ASSERT(dummy);
         CPPUNIT_ASSERT(dummy.isAvailable());
         CPPUNIT_ASSERT(dummy->value_ == 2);
      }
      {
         std::vector<fhicl::ParameterSet> pss;

         fhicl::ParameterSet ps;
         std::string typeName("DummyService");
         ps.addParameter("service_type", typeName);
         int value = 2;
         ps.addParameter("value", value);
         pss.push_back(ps);

         art::ServiceToken token(art::ServiceRegistry::createSet(pss));
         art::ServiceToken token2(art::ServiceRegistry::createContaining(dummyPtr,
                                                                         token,
                                                                         art::serviceregistry::kOverlapIsError));

         art::ServiceRegistry::Operate operate(token2);
         art::ServiceHandle<testserviceregistry::DummyService> dummy;
         CPPUNIT_ASSERT(dummy);
         CPPUNIT_ASSERT(dummy.isAvailable());
         CPPUNIT_ASSERT(dummy->value() == 2);
      }
   }

   {
      std::unique_ptr<DummyService> dummyPtr(new DummyService);
      std::shared_ptr<art::serviceregistry::ServiceWrapper<DummyService> >
          wrapper(new art::serviceregistry::ServiceWrapper<DummyService>(dummyPtr));
      art::ServiceToken token(art::ServiceRegistry::createContaining(wrapper));

      wrapper->get().value_ = 2;

      {
         art::ServiceRegistry::Operate operate(token);
         art::ServiceHandle<DummyService> dummy;
         CPPUNIT_ASSERT(dummy);
         CPPUNIT_ASSERT(dummy.isAvailable());
         CPPUNIT_ASSERT(dummy->value_ == 2);
      }
      {
         std::vector<fhicl::ParameterSet> pss;

         fhicl::ParameterSet ps;
         std::string typeName("DummyService");
         ps.addParameter("service_type", typeName);
         int value = 2;
         ps.addParameter("value", value);
         pss.push_back(ps);

         art::ServiceToken token(art::ServiceRegistry::createSet(pss));
         art::ServiceToken token2(art::ServiceRegistry::createContaining(dummyPtr,
                                                                         token,
                                                                         art::serviceregistry::kOverlapIsError));

         art::ServiceRegistry::Operate operate(token2);
         art::ServiceHandle<testserviceregistry::DummyService> dummy;
         CPPUNIT_ASSERT(dummy);
         CPPUNIT_ASSERT(dummy.isAvailable());
         CPPUNIT_ASSERT(dummy->value() == 2);
      }

   }
}
示例#30
0
// internal
int asCScriptFunction::ParseListPattern(asSListPatternNode *&target, const char *decl, asCScriptNode *listNodes)
{
	asSListPatternNode *node = target;

	listNodes = listNodes->firstChild;
	while( listNodes )
	{
		if( listNodes->nodeType == snIdentifier )
		{
			asCString token(&decl[listNodes->tokenPos], listNodes->tokenLength);
			if( token == "repeat" )
			{
				node->next = asNEW(asSListPatternNode)(asLPT_REPEAT);
				node = node->next;
			}
			else if( token == "repeat_same" )
			{
				// TODO: list: Should make sure this is a sub-list
				node->next = asNEW(asSListPatternNode)(asLPT_REPEAT_SAME);
				node = node->next;
			}
			else
			{
				// Shouldn't happen as the parser already reported the error
				asASSERT(false);
			}
		}
		else if( listNodes->nodeType == snDataType )
		{
			asCDataType dt;
			asCBuilder builder(engine, 0);
			asCScriptCode code;
			code.SetCode("", decl, 0, false);
			dt = builder.CreateDataTypeFromNode(listNodes, &code, engine->defaultNamespace, false, returnType.GetObjectType());

			node->next = asNEW(asSListPatternDataTypeNode)(dt);
			node = node->next;
		}
		else if( listNodes->nodeType == snListPattern )
		{
			node->next = asNEW(asSListPatternNode)(asLPT_START);
			node = node->next;

			// Recursively parse the child
			int r = ParseListPattern(node, decl, listNodes);
			if( r < 0 )
				return r;

			node->next = asNEW(asSListPatternNode)(asLPT_END);
			node = node->next;
		}
		else
		{
			// Unexpected token in the list, the parser shouldn't have allowed
			asASSERT( false );
			return -1;
		}

		listNodes = listNodes->next;
	}

	target = node;
	return 0;
}