static int parse_format (GLogItem * glog, const char *fmt, const char *date_format, char *str) { const char *p; double serve_secs; int special = 0; struct tm tm; unsigned long long bandw, serve_time; if (str == NULL || *str == '\0') return 1; memset (&tm, 0, sizeof (tm)); /* iterate over the log format */ for (p = fmt; *p; p++) { if (*p == '%') { special++; continue; } if (special && *p != '\0') { char *pch, *sEnd, *bEnd, *tkn = NULL, *end = NULL; errno = 0; bandw = 0; serve_time = 0; serve_secs = 0; switch (*p) { /* date */ case 'd': if (glog->date) return 1; /* parse date format including dates containing spaces, * i.e., syslog date format (Jul 15 20:10:56) */ tkn = parse_string (&str, p[1], count_matches (date_format, ' ') + 1); if (tkn == NULL) return 1; end = strptime (tkn, date_format, &tm); if (end == NULL || *end != '\0') { free (tkn); return 1; } glog->date = tkn; break; /* remote hostname (IP only) */ case 'h': if (glog->host) return 1; tkn = parse_string (&str, p[1], 1); if (tkn == NULL) return 1; if (invalid_ipaddr (tkn)) { free (tkn); return 1; } glog->host = tkn; break; /* request method */ case 'm': if (glog->method) return 1; tkn = parse_string (&str, p[1], 1); if (tkn == NULL) return 1; if (!extract_method (tkn)) { free (tkn); return 1; } glog->method = tkn; break; /* request not including method or protocol */ case 'U': if (glog->req) return 1; tkn = parse_string (&str, p[1], 1); if (tkn == NULL || *tkn == '\0') return 1; if ((glog->req = decode_url (tkn)) == NULL) return 1; free (tkn); break; /* request protocol */ case 'H': if (glog->protocol) return 1; tkn = parse_string (&str, p[1], 1); if (tkn == NULL) return 1; if (invalid_protocol (tkn)) { free (tkn); return 1; } glog->protocol = tkn; break; /* request, including method + protocol */ case 'r': if (glog->req) return 1; tkn = parse_string (&str, p[1], 1); if (tkn == NULL) return 1; glog->req = parse_req (tkn, &glog->method, &glog->protocol); free (tkn); break; /* Status Code */ case 's': if (glog->status) return 1; tkn = parse_string (&str, p[1], 1); if (tkn == NULL) return 1; strtol (tkn, &sEnd, 10); if (tkn == sEnd || *sEnd != '\0' || errno == ERANGE) { free (tkn); return 1; } glog->status = tkn; break; /* size of response in bytes - excluding HTTP headers */ case 'b': if (glog->resp_size) return 1; tkn = parse_string (&str, p[1], 1); if (tkn == NULL) return 1; bandw = strtol (tkn, &bEnd, 10); if (tkn == bEnd || *bEnd != '\0' || errno == ERANGE) bandw = 0; glog->resp_size = bandw; conf.bandwidth = 1; free (tkn); break; /* referrer */ case 'R': if (glog->ref) return 1; tkn = parse_string (&str, p[1], 1); if (tkn == NULL) tkn = alloc_string ("-"); if (tkn != NULL && *tkn == '\0') { free (tkn); tkn = alloc_string ("-"); } if (strcmp (tkn, "-") != 0) extract_referer_site (tkn, glog->site); glog->ref = tkn; break; /* user agent */ case 'u': if (glog->agent) return 1; tkn = parse_string (&str, p[1], 1); if (tkn != NULL && *tkn != '\0') { /* Make sure the user agent is decoded (i.e.: CloudFront) * and replace all '+' with ' ' (i.e.: w3c) */ glog->agent = char_replace (decode_url (tkn), '+', ' '); free (tkn); break; } else if (tkn != NULL && *tkn == '\0') { free (tkn); tkn = alloc_string ("-"); } /* must be null */ else { tkn = alloc_string ("-"); } glog->agent = tkn; break; /* time taken to serve the request, in seconds */ case 'T': if (glog->serve_time) return 1; /* ignore seconds if we have microseconds */ if (strstr (fmt, "%D") != NULL) break; tkn = parse_string (&str, p[1], 1); if (tkn == NULL) return 1; if (strchr (tkn, '.') != NULL) serve_secs = strtod (tkn, &bEnd); else serve_secs = strtoull (tkn, &bEnd, 10); if (tkn == bEnd || *bEnd != '\0' || errno == ERANGE) serve_secs = 0; /* convert it to microseconds */ if (serve_secs > 0) glog->serve_time = serve_secs * SECS; else glog->serve_time = 0; conf.serve_usecs = 1; free (tkn); break; /* time taken to serve the request, in microseconds */ case 'D': if (glog->serve_time) return 1; tkn = parse_string (&str, p[1], 1); if (tkn == NULL) return 1; serve_time = strtoull (tkn, &bEnd, 10); if (tkn == bEnd || *bEnd != '\0' || errno == ERANGE) serve_time = 0; glog->serve_time = serve_time; conf.serve_usecs = 1; free (tkn); break; /* everything else skip it */ default: if ((pch = strchr (str, p[1])) != NULL) str += pch - str; } if ((str == NULL) || (*str == '\0')) return 0; special = 0; } else if (special && isspace (p[0])) { return 1; } else str++; } return 0; }
char *test_multi_operator_method() { spec_describe("multi operator method chain: 1 + (n * 3) - 5"); FxP_ParserContext *context = parse_string("1 + (n * 3) - 5\n"); char *inspection = fxp_parser_inspect(context); char *expected = "{\n" " \"expressions\": [\n" " {\n" " \"method_call\": {\n" " \"receiver\": {\n" " \"literal\": {\n" " \"bit\": {\n" " \"INTEGER\": 1\n" " },\n" " \"class\": \"Integer\"\n" " }\n" " },\n" " \"message\": {\n" " \"lookup\": {\n" " \"type\": \"Identifier\",\n" " \"bit\": {\n" " \"STRING\": \"+\"\n" " }\n" " }\n" " },\n" " \"arguments\": [\n" " {\n" " \"method_call\": {\n" " \"receiver\": {\n" " \"grouped_expression\": {\n" " \"method_call\": {\n" " \"receiver\": {\n" " \"lookup\": {\n" " \"type\": \"Identifier\",\n" " \"bit\": {\n" " \"STRING\": \"n\"\n" " }\n" " }\n" " },\n" " \"message\": {\n" " \"lookup\": {\n" " \"type\": \"Identifier\",\n" " \"bit\": {\n" " \"STRING\": \"*\"\n" " }\n" " }\n" " },\n" " \"arguments\": [\n" " {\n" " \"literal\": {\n" " \"bit\": {\n" " \"INTEGER\": 3\n" " },\n" " \"class\": \"Integer\"\n" " }\n" " }\n" " ]\n" " }\n" " }\n" " },\n" " \"message\": {\n" " \"lookup\": {\n" " \"type\": \"Identifier\",\n" " \"bit\": {\n" " \"STRING\": \"-\"\n" " }\n" " }\n" " },\n" " \"arguments\": [\n" " {\n" " \"literal\": {\n" " \"bit\": {\n" " \"INTEGER\": 5\n" " },\n" " \"class\": \"Integer\"\n" " }\n" " }\n" " ]\n" " }\n" " }\n" " ]\n" " }\n" " }\n" " ]\n" "}"; assert_strings_equal(inspection, expected, "ast"); fxp_parser_context_free(context); free(inspection); return NULL; }
char *test_multi_line_method_call() { spec_describe("multiline method call: (n / 10)\n\t.truncate"); FxP_ParserContext *context = parse_string("(n / 10)\n\t.truncate\n"); char *inspection = fxp_parser_inspect(context); char *expected = "{\n" " \"expressions\": [\n" " {\n" " \"method_call\": {\n" " \"receiver\": {\n" " \"grouped_expression\": {\n" " \"method_call\": {\n" " \"receiver\": {\n" " \"lookup\": {\n" " \"type\": \"Identifier\",\n" " \"bit\": {\n" " \"STRING\": \"n\"\n" " }\n" " }\n" " },\n" " \"message\": {\n" " \"lookup\": {\n" " \"type\": \"Identifier\",\n" " \"bit\": {\n" " \"STRING\": \"/\"\n" " }\n" " }\n" " },\n" " \"arguments\": [\n" " {\n" " \"literal\": {\n" " \"bit\": {\n" " \"INTEGER\": 10\n" " },\n" " \"class\": \"Integer\"\n" " }\n" " }\n" " ]\n" " }\n" " }\n" " },\n" " \"message\": {\n" " \"lookup\": {\n" " \"type\": \"Identifier\",\n" " \"bit\": {\n" " \"STRING\": \"truncate\"\n" " }\n" " }\n" " }\n" " }\n" " }\n" " ]\n" "}"; assert_strings_equal(inspection, expected, "ast"); fxp_parser_context_free(context); free(inspection); spec_describe("multiline method call: (n / 10).\n\ttruncate"); context = parse_string("(n / 10).\n\ntruncate\n"); inspection = fxp_parser_inspect(context); assert_strings_equal(inspection, expected, "ast"); fxp_parser_context_free(context); free(inspection); return NULL; }
char *test_function_with_expression() { spec_describe("function one expression: -> {\n1 + 1\n}"); FxP_ParserContext *context = parse_string("-> {\n1 + 1\n}\n"); setup_json(); element = json_object_get( json_object_get(expression, "function_definition"), "expressions"); assert_ints_equal(json_array_size(element), 1, "expressions size correct"); element = json_object_get( json_object_get( json_object_get( json_object_get( json_object_get( json_array_get( json_object_get( json_object_get(expression, "function_definition"), "expressions"), 0), "method_call"), "receiver"), "literal"), "bit"), "INTEGER"); assert_ints_equal(json_integer_value(element), 1, "first expression receiver correct"); element = json_object_get( json_object_get( json_object_get( json_object_get( json_object_get( json_array_get( json_object_get( json_object_get(expression, "function_definition"), "expressions"), 0), "method_call"), "message"), "lookup"), "bit"), "STRING"); assert_strings_equal(json_string_value(element), "+", "first expression message correct"); element = json_object_get( json_object_get( json_object_get( json_array_get( json_object_get( json_object_get( json_array_get( json_object_get( json_object_get(expression, "function_definition"), "expressions"), 0), "method_call"), "arguments"), 0), "literal"), "bit"), "INTEGER"); assert_ints_equal(json_integer_value(element), 1, "first expression arguments correct"); cleanup(); return NULL; }
char *test_expression_function_with_expression_expression() { spec_describe("expression function sandwich: 1 + 1\n-> {\n print 'word'\n}\n2 * 2"); FxP_ParserContext *context = parse_string("1 + 1\n-> {\n print 'word'\n}\n2 * 2\n"); char *inspection = fxp_parser_inspect(context); char *expected = "{\n" " \"expressions\": [\n" " {\n" " \"method_call\": {\n" " \"receiver\": {\n" " \"literal\": {\n" " \"bit\": {\n" " \"INTEGER\": 1\n" " },\n" " \"class\": \"Integer\"\n" " }\n" " },\n" " \"message\": {\n" " \"lookup\": {\n" " \"type\": \"Identifier\",\n" " \"bit\": {\n" " \"STRING\": \"+\"\n" " }\n" " }\n" " },\n" " \"arguments\": [\n" " {\n" " \"literal\": {\n" " \"bit\": {\n" " \"INTEGER\": 1\n" " },\n" " \"class\": \"Integer\"\n" " }\n" " }\n" " ]\n" " }\n" " },\n" " {\n" " \"function_definition\": {\n" " \"expressions\": [\n" " {\n" " \"method_call\": {\n" " \"message\": {\n" " \"lookup\": {\n" " \"type\": \"Identifier\",\n" " \"bit\": {\n" " \"STRING\": \"print\"\n" " }\n" " }\n" " },\n" " \"arguments\": [\n" " {\n" " \"literal\": {\n" " \"bit\": {\n" " \"STRING\": \"word\"\n" " },\n" " \"class\": \"String\"\n" " }\n" " }\n" " ]\n" " }\n" " }\n" " ]\n" " }\n" " },\n" " {\n" " \"method_call\": {\n" " \"receiver\": {\n" " \"literal\": {\n" " \"bit\": {\n" " \"INTEGER\": 2\n" " },\n" " \"class\": \"Integer\"\n" " }\n" " },\n" " \"message\": {\n" " \"lookup\": {\n" " \"type\": \"Identifier\",\n" " \"bit\": {\n" " \"STRING\": \"*\"\n" " }\n" " }\n" " },\n" " \"arguments\": [\n" " {\n" " \"literal\": {\n" " \"bit\": {\n" " \"INTEGER\": 2\n" " },\n" " \"class\": \"Integer\"\n" " }\n" " }\n" " ]\n" " }\n" " }\n" " ]\n" "}"; assert_strings_equal(inspection, expected, "ast"); fxp_parser_context_free(context); free(inspection); return NULL; }
static blargg_err_t parse_info( byte const* in, long size, Sap_Emu::info_t* out ) { out->track_count = 1; out->author [0] = 0; out->name [0] = 0; out->copyright [0] = 0; out->length = 0; if ( size < 16 || memcmp( in, "SAP\x0D\x0A", 5 ) ) return gme_wrong_file_type; byte const* file_end = in + size - 5; in += 5; while ( in < file_end && (in [0] != 0xFF || in [1] != 0xFF) ) { byte const* line_end = in; while ( line_end < file_end && *line_end != 0x0D ) line_end++; char const* tag = (char const*) in; while ( in < line_end && *in > ' ' ) in++; int tag_len = (char const*) in - tag; while ( in < line_end && *in <= ' ' ) in++; if ( tag_len <= 0 ) { // skip line } else if ( !strncmp( "INIT", tag, tag_len ) ) { out->init_addr = from_hex( in ); if ( (unsigned long) out->init_addr > 0xFFFF ) return "Invalid init address"; } else if ( !strncmp( "PLAYER", tag, tag_len ) ) { out->play_addr = from_hex( in ); if ( (unsigned long) out->play_addr > 0xFFFF ) return "Invalid play address"; } else if ( !strncmp( "MUSIC", tag, tag_len ) ) { out->music_addr = from_hex( in ); if ( (unsigned long) out->music_addr > 0xFFFF ) return "Invalid music address"; } else if ( !strncmp( "SONGS", tag, tag_len ) ) { out->track_count = from_dec( in, line_end ); if ( out->track_count <= 0 ) return "Invalid track count"; } else if ( !strncmp( "TYPE", tag, tag_len ) ) { switch ( out->type = *in ) { case 'C': case 'B': break; case 'D': return "Digimusic not supported"; default: return "Unsupported player type"; } } else if ( !strncmp( "STEREO", tag, tag_len ) ) { out->stereo = true; } else if ( !strncmp( "FASTPLAY", tag, tag_len ) ) { out->fastplay = from_dec( in, line_end ); if ( out->fastplay <= 0 ) return "Invalid fastplay value"; } else if ( !strncmp( "AUTHOR", tag, tag_len ) ) { parse_string( in, line_end, sizeof out->author, out->author ); } else if ( !strncmp( "NAME", tag, tag_len ) ) { parse_string( in, line_end, sizeof out->name, out->name ); } else if ( !strncmp( "DATE", tag, tag_len ) ) { parse_string( in, line_end, sizeof out->copyright, out->copyright ); } else if ( !strncmp( "TIME", tag, tag_len ) ) { int mins = from_dec( in, in+2 ); int secs = from_dec( in+3, in+5 ) + mins * 60; out->length = secs * 1000; } in = line_end + 2; } if ( in [0] != 0xFF || in [1] != 0xFF ) return "ROM data missing"; out->rom_data = in + 2; return 0; }
static gmx_bool parse_entry(char **string, int natoms, t_atoms *atoms, t_blocka *block, char ***gn, atom_id *nr, atom_id *index, char *gname) { static char **names, *ostring; static gmx_bool bFirst = TRUE; int j, n_names, sel_nr1; atom_id i, nr1, *index1; char c; gmx_bool bRet, bCompl; if (bFirst) { bFirst = FALSE; snew(names, MAXNAMES); for (i = 0; i < MAXNAMES; i++) { snew(names[i], NAME_LEN+1); } } bRet = FALSE; sel_nr1 = NOTSET; while (*string[0] == ' ') { (*string)++; } if ((*string)[0] == '!') { bCompl = TRUE; (*string)++; while (*string[0] == ' ') { (*string)++; } } else { bCompl = FALSE; } ostring = *string; if (parse_int(string, &sel_nr1) || parse_string(string, &sel_nr1, block->nr, *gn)) { if ((sel_nr1 >= 0) && (sel_nr1 < block->nr)) { copy_group(sel_nr1, block, nr, index); strcpy(gname, (*gn)[sel_nr1]); printf("Copied index group %d '%s'\n", sel_nr1, (*gn)[sel_nr1]); bRet = TRUE; } else { printf("Group %d does not exist\n", sel_nr1); } } else if ((*string)[0] == 'a') { (*string)++; if (check_have_atoms(atoms, ostring)) { if (parse_int(string, &sel_nr1)) { bRet = select_atomnumbers(string, atoms, sel_nr1, nr, index, gname); } else if (parse_names(string, &n_names, names)) { bRet = select_atomnames(atoms, n_names, names, nr, index, FALSE); make_gname(n_names, names, gname); } } } else if ((*string)[0] == 't') { (*string)++; if (check_have_atoms(atoms, ostring) && parse_names(string, &n_names, names)) { if (atoms->atomtype == NULL) { printf("Need a run input file to select atom types\n"); } else { bRet = select_atomnames(atoms, n_names, names, nr, index, TRUE); make_gname(n_names, names, gname); } } } else if (strncmp(*string, "res", 3) == 0) { (*string) += 3; if (check_have_atoms(atoms, ostring) && parse_int(string, &sel_nr1) && (sel_nr1 >= 0) && (sel_nr1 < block->nr) ) { bRet = atoms_from_residuenumbers(atoms, sel_nr1, block, nr, index, (*gn)[sel_nr1]); sprintf(gname, "atom_%s", (*gn)[sel_nr1]); } } else if (strncmp(*string, "ri", 2) == 0) { (*string) += 2; if (check_have_atoms(atoms, ostring) && parse_int_char(string, &sel_nr1, &c)) { bRet = select_residueindices(string, atoms, sel_nr1, c, nr, index, gname); } } else if ((*string)[0] == 'r') { (*string)++; if (check_have_atoms(atoms, ostring)) { if (parse_int_char(string, &sel_nr1, &c)) { bRet = select_residuenumbers(string, atoms, sel_nr1, c, nr, index, gname); } else if (parse_names(string, &n_names, names)) { bRet = select_residuenames(atoms, n_names, names, nr, index); make_gname(n_names, names, gname); } } } else if (strncmp(*string, "chain", 5) == 0) { (*string) += 5; if (check_have_atoms(atoms, ostring) && parse_names(string, &n_names, names)) { bRet = select_chainnames(atoms, n_names, names, nr, index); sprintf(gname, "ch%s", names[0]); for (i = 1; i < n_names; i++) { strcat(gname, names[i]); } } } if (bRet && bCompl) { snew(index1, natoms-*nr); nr1 = 0; for (i = 0; i < natoms; i++) { j = 0; while ((j < *nr) && (index[j] != i)) { j++; } if (j == *nr) { if (nr1 >= natoms-*nr) { printf("There are double atoms in your index group\n"); break; } index1[nr1] = i; nr1++; } } *nr = nr1; for (i = 0; i < nr1; i++) { index[i] = index1[i]; } sfree(index1); for (i = strlen(gname)+1; i > 0; i--) { gname[i] = gname[i-1]; } gname[0] = '!'; printf("Complemented group: %d atoms\n", *nr); } return bRet; }
/** Evaluate the source code in a given string */ value_t eval_string(const char* cstr, const char* src_name) { ast_fun_t* unit_fun = parse_check_error(parse_string(cstr, src_name)); return eval_unit(unit_fun); }
static IteratorT parse_host(IteratorT begin, IteratorT end) { // For convenience we shortcut this parsing for now. return parse_string(parse_host_character, begin, end); }
void parser::parse_code( std::istream &in ) { precondition( in.get() == '%', "missing '%' to start code" ); // find the first word std::string word; while ( std::isspace( in.peek() ) ) in.get(); while ( std::isalpha( in.peek() ) ) word.push_back( static_cast<char>( in.get() ) ); while ( std::isspace( in.peek() ) ) in.get(); if ( word == "for" ) { _func.add( "for " ); } else if ( word == "if" ) { _func.add( "if " ); } else if ( word == "else" ) { _func.unindent(); _func.add( "}\nelse" ); _func.push_code(); } else if ( word == "code" || word == "endfor" || word == "endif" ) { } else throw_runtime( "unknown template keyword '{0}'", word ); int count = 0; while ( !in.eof() && in ) { int c = in.get(); if ( std::char_traits<char>::not_eof( c ) ) { if ( c == ']' ) { if ( count == 0 ) { _func.push_code(); break; } _func.add( static_cast<char>( c ) ); --count; } else if ( c == '[' ) { _func.add( static_cast<char>( c ) ); ++count; } else if ( c == '"' ) { _func.add( static_cast<char>( c ) ); parse_string( in ); } else _func.add( static_cast<char>( c ) ); } } if ( word == "for" || word == "if" || word == "else" ) { _func.add( "\n{" ); _func.indent(); } else if ( word == "endfor" || word == "endif" ) { _func.unindent(); _func.add( '}' ); _func.push_code(); } }
int exec_file(const char *fn, const char *script, const char *tmpdir, char *logbuf, unsigned loglen) { unsigned old_err; char *p; FILE *f; struct extmacro *m; signal(SIGPIPE, SIG_IGN); vtc_loginit(logbuf, loglen); vltop = vtc_logopen("top"); AN(vltop); init_macro(); init_sema(); /* Apply extmacro definitions */ VTAILQ_FOREACH(m, &extmacro_list, list) macro_def(vltop, NULL, m->name, "%s", m->val); /* * We need an IP number which will not repond, ever, and that is a * lot harder than it sounds. This IP# is from RFC5737 and a * C-class broadcast at that. * If tests involving ${bad_ip} fails and you run linux, you should * check your /proc/sys/net/ipv4/ip_nonlocal_bind setting. */ macro_def(vltop, NULL, "bad_ip", "192.0.2.255"); /* Move into our tmpdir */ AZ(chdir(tmpdir)); macro_def(vltop, NULL, "tmpdir", "%s", tmpdir); /* Drop file to tell what was going on here */ f = fopen("INFO", "w"); AN(f); fprintf(f, "Test case: %s\n", fn); AZ(fclose(f)); vtc_stop = 0; vtc_desc = NULL; vtc_log(vltop, 1, "TEST %s starting", fn); p = strdup(script); AN(p); vtc_thread = pthread_self(); parse_string(p, cmds, NULL, vltop); old_err = vtc_error; vtc_stop = 1; vtc_log(vltop, 1, "RESETTING after %s", fn); reset_cmds(cmds); vtc_error = old_err; if (vtc_error) vtc_log(vltop, 1, "TEST %s FAILED", fn); else vtc_log(vltop, 1, "TEST %s completed", fn); free(vtc_desc); return (vtc_error); }
ehval_p EHI::execute_string(const char *cmd) { parse_string(cmd); return execute_code(); }
explicit options_map(std::string &s) { parse_string(s); };
static gboolean gfire_sq_ase_parse(gfire_game_server *p_server, guint16 p_ping, gboolean p_full, const unsigned char *p_data, guint p_len) { if(memcmp(p_data, "EYE1", 4) != 0) return FALSE; gfire_sq_ase_data *data = g_new0(gfire_sq_ase_data, 1); guint offset = 4; gchar *tempstr; // General server data data->game_name = gfire_strip_invalid_utf8(parse_string(p_data, p_len, &offset, FALSE)); if(!data->game_name) goto error; tempstr = gfire_strip_invalid_utf8(parse_string(p_data, p_len, &offset, FALSE)); if(!tempstr) goto error; data->game_port = atoi(tempstr); g_free(tempstr); data->server_name = gfire_strip_invalid_utf8(parse_string(p_data, p_len, &offset, FALSE)); if(!data->server_name) goto error; data->game_type = gfire_strip_invalid_utf8(parse_string(p_data, p_len, &offset, FALSE)); if(!data->game_type) goto error; data->map = gfire_strip_invalid_utf8(parse_string(p_data, p_len, &offset, FALSE)); if(!data->map) goto error; data->version = gfire_strip_invalid_utf8(parse_string(p_data, p_len, &offset, FALSE)); if(!data->version) goto error; tempstr = gfire_strip_invalid_utf8(parse_string(p_data, p_len, &offset, FALSE)); if(!tempstr) goto error; data->password = (*tempstr == '1'); g_free(tempstr); tempstr = gfire_strip_invalid_utf8(parse_string(p_data, p_len, &offset, FALSE)); if(!tempstr) goto error; data->num_players = atoi(tempstr); g_free(tempstr); tempstr = gfire_strip_invalid_utf8(parse_string(p_data, p_len, &offset, FALSE)); if(!tempstr) goto error; data->max_players = atoi(tempstr); g_free(tempstr); // Server rules g_datalist_init(&data->rules); while(1) { gchar *key = gfire_strip_invalid_utf8(parse_string(p_data, p_len, &offset, FALSE)); if(!key) break; gchar *value = gfire_strip_invalid_utf8(parse_string(p_data, p_len, &offset, FALSE)); if(!value) { g_free(key); goto error; } g_datalist_set_data_full(&data->rules, key, value, g_free); g_free(key); } // Players while(p_len > offset) { gfire_sq_ase_player *player = g_new0(gfire_sq_ase_player, 1); guint8 flags = *(p_data + offset++); if(flags & 1) { player->name = gfire_strip_invalid_utf8(parse_string(p_data, p_len, &offset, TRUE)); if(!player->name) { free_ase_player(player); break; } } if(flags & 2) { player->team = gfire_strip_invalid_utf8(parse_string(p_data, p_len, &offset, TRUE)); if(!player->team) { free_ase_player(player); break; } } if(flags & 4) { player->skin = gfire_strip_invalid_utf8(parse_string(p_data, p_len, &offset, TRUE)); if(!player->skin) { free_ase_player(player); break; } } if(flags & 8) { player->score = gfire_strip_invalid_utf8(parse_string(p_data, p_len, &offset, TRUE)); if(!player->score) { free_ase_player(player); break; } } if(flags & 16) { player->ping = gfire_strip_invalid_utf8(parse_string(p_data, p_len, &offset, TRUE)); if(!player->ping) { free_ase_player(player); break; } } if(flags & 32) { player->time = gfire_strip_invalid_utf8(parse_string(p_data, p_len, &offset, TRUE)); if(!player->time) { free_ase_player(player); break; } } data->players = g_slist_append(data->players, player); } // Hack for some servers... if(g_datalist_get_data(&data->rules, "numplayers")) data->num_players = atoi(g_datalist_get_data(&data->rules, "numplayers")); // Copy values into the standard container p_server->data = g_new0(gfire_game_server_data, 1); p_server->data->driver = &gf_sq_ase_driver; p_server->data->proto_data = data; p_server->data->name = gfire_sq_ase_strip_color_codes(data->server_name); p_server->data->map = g_strdup(data->map); p_server->data->players = data->num_players; p_server->data->max_players = data->max_players; p_server->data->ping = p_ping; // No more packets to request! return FALSE; error: free_ase_data(data); return FALSE; }
amort_sched_ptr amort_opt( amort_sched_ptr amortsched, void *parse_env) { char buffer[200], *errp; unsigned long ii; unsigned prec = amortsched->prec; var_store value; numeric_ptr nval; struct tm *times_E, *times_I; /* print amortization options */ times_E = (struct tm *)calloc(1, sizeof(struct tm)); ii = amortsched->Eff_Date_jdn; times_E->tm_mday = amortsched->day_E; times_E->tm_mon = amortsched->month_E - 1; times_E->tm_year = amortsched->year_E - 1900; times_E->tm_wday = (ii + 1) % 7; times_E->tm_yday = amortsched->yday_E; times_I = (struct tm *)calloc(1, sizeof(struct tm)); ii = amortsched->Init_Date_jdn; times_I->tm_mday = amortsched->day_I; times_I->tm_mon = amortsched->month_I - 1; times_I->tm_year = amortsched->year_I - 1900; times_I->tm_wday = (ii + 1) % 7; times_I->tm_yday = amortsched->yday_I; printf("\n******************************"); qof_strftime(buffer, (size_t)50, "%c", times_E); printf("\nEffective Date: %s\n", buffer); qof_strftime(buffer, (size_t)50, "%c", times_I); printf("Initial Payment Date: %s\n", buffer); free(times_E); free(times_I); printf("The Original Present Value (pv) is: %.*f\n", (int)prec, amortsched->pv); printf("The Original Periodic Payment (pmt) is: %.*f\n", (int)prec, amortsched->pmt); printf("The Original Future Value (fv) is: %.*f\n", (int)prec, amortsched->fv); printf("The Delayed Present Value (pve) is: %.*f\n", (int)prec, amortsched->pve); printf("The New Periodic Payment (pmt) for pve is: %.*f\n\n", (int)prec, amortsched->new_pmt); printf("The amortization options are:\n"); printf("1 -- Amortize with Original Amount and Constant Payment to Principal: %.*f\n", (int) prec, amortsched->cpmt1); printf(" and final payment: %.*f\n", (int)prec, amortsched->final_pmt_opt_1); printf("2 -- Amortize with Delayed Amount and Constant Payment to Principal: %.*f\n", (int)prec, amortsched->cpmt2); printf(" and final payment: %.*f\n", (int)prec, amortsched->final_pmt_opt_2); printf("3 -- Amortize with Original Transaction Values\n"); printf(" and final payment: %.*f\n", (int)prec, amortsched->final_pmt_opt_3); printf("4 -- Amortize with Delayed Amount, Original Periodic Payment\n"); printf(" and final payment: %.*f\n", (int)prec, amortsched->final_pmt_opt_4); printf("5 -- Amortize with Delayed Amount, New Periodic Payment\n"); printf(" and final payment: %.*f\n", (int)prec, amortsched->final_pmt_opt_5); if ( amortsched->new_n ) { printf("6 -- Amortize with Original Amount, Original Periodic Payment,\n"); printf(" new number of total payments (n): %u\n", amortsched->new_n); printf(" and final payment: %.*f\n", (int)prec, amortsched->final_pmt_opt_6); } /* endif */ printf("Enter choice 1, 2, 3, 4, 5 or 6: "); fgets(buffer, 190, stdin); amortsched->option = buffer[0] - '0'; printf("Amortization Schedule:\n"); printf("y -- Yearly Summary\n"); printf("p -- Periodic Payment\n"); if ( amortsched->option < 3 ) { printf("Enter Choice y or p: "); } else { printf("f -- Fixed Advanced Payment\n"); printf("a -- Variable Advanced Payment\n"); printf("Enter Choice y, p, f or a: "); } /* endif */ fgets(buffer, 190, stdin); amortsched->summary = buffer[0]; if ( amortsched->summary == 'f' ) { if ( amortsched->fixed_pmt != 0.0 ) { printf("Current Fixed Prepayment: %.*f\nChange Fixed Prepayment? (y/n): ", (int)prec, amortsched->fixed_pmt); fgets(buffer, 190, stdin); } else { buffer[0] = 'y'; } /* endif */ if ( buffer[0] == 'y' ) { printf("Enter Fixed Prepayment Amount: "); fgets(buffer, 190, stdin); if ( (errp = parse_string(&value, buffer, parse_env)) == NULL ) { nval = (numeric_ptr)(value.value); switch ( nval->type ) { case INT_TYPE: amortsched->fixed_pmt = (double)(nval->value.int_value); break; case DBL_TYPE: amortsched->fixed_pmt = nval->value.dbl_value; break; } /* endswitch */ if ( !value.variable_name ) free_numeric(value.value); } else { parse_error(get_parse_error(parse_env), buffer, errp); } /* endif */ } /* endif */ } /* endif */ return amortsched; } /* amort_opt */
int main(int argc, const char *argv[]) { rtc_time_t tm; reg_data_t regv; reg_temp_mode_t mode; int ret = -1; int fd = -1; const char *dev_name = "/dev/hi_rtc"; char string[50] = {0}; memset(&tm, 0, sizeof(tm)); if (argc < 2){ usage(); return 0; } fd = open(dev_name, O_RDWR); if (fd < 0) { printf("open %s failed\n", dev_name); return -1; } if (!strcmp(argv[1],"-s")) { if (argc < 4) { usage(); goto err1; } if (!strcmp(argv[2], "time")) { strncpy(string, argv[3], sizeof(string)-1); ret = parse_string(string, &tm); if (ret < 0) { printf("parse time param failed\n"); goto err1; } printf("set time\n"); #if 1 /* code */ printf("year:%d\n", tm.year); printf("month:%d\n",tm.month); printf("date:%d\n", tm.date); printf("hour:%d\n", tm.hour); printf("minute:%d\n", tm.minute); printf("second:%d\n", tm.second); #endif ret = ioctl(fd, HI_RTC_SET_TIME, &tm); if (ret < 0) { printf("ioctl: HI_RTC_SET_TIME failed\n"); goto err1; } } else if (!strcmp(argv[2], "alarm")) { strncpy(string, argv[3], sizeof(string)-1); ret = parse_string(string, &tm); if (ret < 0) { printf("parse alarm param failed\n"); goto err1; } printf("set alarm\n"); #if 1 printf("year:%d\n", tm.year); printf("month:%d\n",tm.month); printf("date:%d\n", tm.date); printf("hour:%d\n", tm.hour); printf("minute:%d\n", tm.minute); printf("second:%d\n", tm.second); #endif ret = ioctl(fd, HI_RTC_ALM_SET, &tm); if (ret < 0) { printf("ioctl: HI_RTC_ALM_SET failed\n"); goto err1; } } else { printf("unknown options %s\n", argv[2]); goto err1; } } else if (!strcmp(argv[1],"-g")) { if (argc < 3) { usage(); goto err1; } if (!strcmp(argv[2], "time")) { printf("[RTC_RD_TIME]\n"); ret = ioctl(fd, HI_RTC_RD_TIME, &tm); if (ret < 0) { printf("ioctl: HI_RTC_RD_TIME failed\n"); goto err1; } printf("Current time value: \n"); } else if (!strcmp(argv[2], "alarm")) { printf("[RTC_RD_ALM]\n"); ret = ioctl(fd, HI_RTC_ALM_READ, &tm); if (ret < 0) { printf("ioctl: HI_RTC_ALM_READ failed\n"); goto err1; } printf("Current alarm value: \n"); } else { printf("unknow options %s\n", argv[2]); goto err1; } printf("year %d\n", tm.year); printf("month %d\n", tm.month); printf("date %d\n", tm.date); printf("hour %d\n", tm.hour); printf("minute %d\n", tm.minute); printf("second %d\n", tm.second); printf("weekday %d\n", tm.weekday); } else if (!strcmp(argv[1],"-w")) { if (argc < 4) { usage(); goto err1; } ret = str_to_num(argv[2], &(regv.reg)); if (ret != 0) { printf("reg 0x%08x invalid\n", regv.reg); goto err1; } ret = str_to_num(argv[3], &(regv.val)); if (ret != 0) { printf("val 0x%08x invalid\n", regv.val); goto err1; } printf("\n"); printf("[RTC_REG_SET] reg:%02x, val:%02x\n", regv.reg, regv.val); printf("\n"); ret = ioctl(fd, HI_RTC_REG_SET, ®v); if (ret < 0) { printf("ioctl: HI_RTC_REG_SET failed\n"); goto err1; } } else if (!strcmp(argv[1],"-r")) { if (argc < 3) { usage(); goto err1; } ret = str_to_num(argv[2], &(regv.reg)); if (ret != 0) { printf("reg 0x%08x invalid\n", regv.reg); goto err1; } regv.val = 0; ret = ioctl(fd, HI_RTC_REG_READ, ®v); if (ret < 0) { printf("ioctl: HI_RTC_REG_READ failed\n"); goto err1; } printf("\n"); printf("[RTC_REG_GET] reg:0x%02x, val:0x%02x\n", regv.reg, regv.val); printf("\n"); } else if (!strcmp(argv[1],"-a")) { if (argc < 3) { usage(); goto err1; } if (!strcmp(argv[2], "ON")) { ret = ioctl(fd, HI_RTC_AIE_ON); } else if (!strcmp(argv[2], "OFF")) { ret = ioctl(fd, HI_RTC_AIE_OFF); } if (ret < 0) { printf("ioctl: HI_RTC_AIE_ON/OFF failed\n"); goto err1; } } else if (!strcmp(argv[1],"-reset")) { printf("[RTC_RESET]\n"); ret = ioctl(fd, HI_RTC_RESET); if(ret){ printf("reset err\n"); goto err1; } } else if (!strcmp(argv[1], "-c")) { if (argc < 3) { usage(); goto err1; } if (!strcmp(argv[2], "ON")) { //printf("RTC temperature compensation on!\n"); ret = ioctl(fd, HI_RTC_COMP_ON); } else if (!strcmp(argv[2], "OFF")) { //printf("RTC temperature compensation off!\n"); ret = ioctl(fd, HI_RTC_COMP_OFF); } if (ret < 0) { printf("ioctl: HI_RTC_COMP_ON/OFF failed\n"); goto err1; } } else if (!strcmp(argv[1], "-f")) { unsigned int freq; rtc_freq_t value; // print current frequency value if (argc < 3) { ret = ioctl(fd, HI_RTC_GET_FREQ, &value); if (ret < 0) { printf("get current frequency failed\n"); goto err1; } freq = value.freq_l; #if 0 if (freq > 3277000 || freq < 3276000) { printf("get invalid freq %d\n", freq); goto err1; } #endif printf("current frequency : %d\n", freq); } // set frequency else if (argc == 3) { freq = atoi(argv[2]); if (freq > 3277000 || freq < 3276000) { printf("invalid freq %d\n", freq); goto err1; } value.freq_l = freq; ret = ioctl(fd, HI_RTC_SET_FREQ, &value); if (ret < 0) { printf("get current frequency failed\n"); goto err1; } } } else if (!strcmp(argv[1], "-m")) { int mod, value; if (argc < 3) { usage(); goto err1; } mod = atoi(argv[2]); if (mod > 2 || mod < 0) { printf("invalid mode %d\n", mod); goto err1; } if (mod == 0) { if (argc < 4) { usage(); goto err1; } value = atoi(argv[3]); } else { value = 0; } printf("[RTC_SET_TEMP_MODE] %d\n", mod); mode.mode = (enum temp_sel_mode)mod; mode.value = value; ret = ioctl(fd, HI_RTC_SET_TEMP_MODE, &mode); if(ret) { printf("ioctl: HI_RTC_SET_TEMP_MODE failed\n"); goto err1; } } else { printf("unknown download mode.\n"); goto err1; } err1: close(fd); return 0; }
static ZZJSON *parse_object(ZZJSON_CONFIG *config) { ZZJSON *retval = NULL; int c; ZZJSON **next = &retval; SKIPWS(); c = GETC(); if (c != '{') { ERROR("object: expected '{'"); return NULL; } SKIPWS(); c = GETC(); while (c > 0 && c != '}') { ZZJSON *zzjson = NULL, *val = NULL; char *str; UNGETC(c); str = parse_string(config); if (!str) { ERROR("object: expected string"); errout_with_str: config->free(str); goto errout; } SKIPWS(); c = GETC(); if (c != ':') { ERROR("object: expected ':'"); goto errout_with_str; } SKIPWS(); val = parse_value(config); if (!val) { ERROR("object: value expected"); goto errout_with_str; } SKIPWS(); c = GETC(); if (c != ',' && c != '}') { ERROR("object: expected ',' or '}'"); errout_with_str_and_val: zzjson_free(config, val); goto errout_with_str; } if (c == ',') { SKIPWS(); c = GETC(); if (c == '}' && !ALLOW_EXTRA_COMMA) { ERROR("object: expected pair after ','"); goto errout_with_str_and_val; } } UNGETC(c); zzjson = config->calloc(1, sizeof(ZZJSON)); if (!zzjson) { MEMERROR(); goto errout_with_str_and_val; } zzjson->type = ZZJSON_OBJECT; zzjson->value.object.label = str; zzjson->value.object.val = val; *next = zzjson; next = &zzjson->next; c = GETC(); } if (c != '}') { ERROR("object: expected '}'"); goto errout; } if (!retval) { /* empty object, { } */ retval = config->calloc(1, sizeof(ZZJSON)); if (!retval) { MEMERROR(); return NULL; } retval->type = ZZJSON_OBJECT; } return retval; errout: zzjson_free(config, retval); return NULL; }
static struct buffer parse_table(struct buffer buff, struct invocation *invocation, const char **error) { unsigned i; size_t ident_len; struct argument args[QUERY_MAX_ARGS]; const char *ident_name = NULL; unsigned argi = 0; buff = chomp(buff); buff = expect_char(buff, '{', error); if (*error) goto clean; buff = chomp(buff); while (!peek(buff, "}")) { if (argi >= QUERY_MAX_ARGS) { raise_too_many_arguments(error); goto clean; } if (isalpha((int)buff.data[buff.offset])) { buff = get_ident(buff, &ident_name, &ident_len, error); if (!*error) { args[argi].a.value.type = RDT_STRING; args[argi].a.value.val.string.len = ident_len; args[argi].a.value.val.string.buff = (char*)calloc( ident_len + 1, sizeof(char) ); if (!args[argi].a.value.val.string.buff) goto clean; strncpy( args[argi].a.value.val.string.buff, ident_name, ident_len ); } } else buff = parse_string(buff, &args[argi].a.value, error); if (*error) goto clean; args[argi].type = AT_VALUE; buff = chomp(buff); argi++; buff = expect_char(buff, ':', error); if (*error) goto clean; buff = chomp(buff); if (argi >= QUERY_MAX_ARGS) { raise_too_many_arguments(error); goto clean; } buff = parse_argument(buff, &args[argi], error); if (*error) goto clean; argi++; buff = chomp(buff); buff = expect_char(buff, ',', error); if (*error) { *error = NULL; break; } buff = chomp(buff); } buff = expect_char(buff, '}', error); if (*error) goto clean; invocation->func = all_map; invocation->argc = argi; invocation->argv = (struct argument*) malloc(sizeof(struct argument) * argi); if (!invocation->argv) { raise_enomem(error); goto clean; } memcpy(invocation->argv, args, sizeof(struct argument) * argi); goto success; clean: for (i = 0; i < argi; i++) argument_free(&args[i]); success: return buff; }
static int parse_pair(heim_dict_t dict, struct parse_ctx *ctx) { heim_string_t key; heim_object_t value; if (white_spaces(ctx)) return -1; if (*ctx->p == '}') { ctx->p++; return 0; } if (ctx->flags & HEIM_JSON_F_STRICT_DICT) /* JSON allows only string keys */ key = parse_string(ctx); else /* heim_dict_t allows any heim_object_t as key */ key = parse_value(ctx); if (key == NULL) /* Even heim_dict_t does not allow C NULLs as keys though! */ return -1; if (white_spaces(ctx)) { heim_release(key); return -1; } if (*ctx->p != ':') { heim_release(key); return -1; } ctx->p += 1; /* safe because we call white_spaces() next */ if (white_spaces(ctx)) { heim_release(key); return -1; } value = parse_value(ctx); if (value == NULL && (ctx->error != NULL || (ctx->flags & HEIM_JSON_F_NO_C_NULL))) { if (ctx->error == NULL) ctx->error = heim_error_create(EINVAL, "Invalid JSON encoding"); heim_release(key); return -1; } heim_dict_set_value(dict, key, value); heim_release(key); heim_release(value); if (white_spaces(ctx)) return -1; if (*ctx->p == '}') { /* * Return 1 but don't consume the '}' so we can count the one * pair in a one-pair dict */ return 1; } else if (*ctx->p == ',') { ctx->p++; return 1; } return -1; }
/* * Lexical analyzer for expression parser: parses a single value, * operator, or other syntactic element from an expression string. * * Results: * TCL_OK is returned unless an error occurred while doing lexical * analysis or executing an embedded command. In that case a * standard Tcl error is returned, using interp->result to hold * an error message. In the event of a successful return, the token * and field in infoPtr is updated to refer to the next symbol in * the expression string, and the expr field is advanced past that * token; if the token is a value, then the value is stored at * valuePtr. * * Side effects: * None. */ static unsigned char get_lex (Tcl_Interp *interp, /* Interpreter to use for error reporting. */ Expr_info_t *infoPtr, /* Describes the state of the parse. */ Value_t *valuePtr) /* Where to store value, if that is * what's parsed from string. Caller * must have initialized pv field correctly. */ { unsigned char *p, c, *var, *term; unsigned char result; p = infoPtr->expr; c = *p; while (isspace(c)) { p++; c = *p; } infoPtr->expr = p+1; switch (c) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': /* * Number. First read an integer. Then if it looks like * there's a floating-point number (or if it's too big a * number to fit in an integer), parse it as a floating-point * number. */ infoPtr->token = VALUE; valuePtr->type = TYPE_INT; valuePtr->int_value = strtoul (p, &term, 0); c = *term; infoPtr->expr = term; return TCL_OK; case '$': /* * Variable. Fetch its value, then see if it makes sense * as an integer or floating-point number. */ infoPtr->token = VALUE; var = Tcl_ParseVar(interp, p, &infoPtr->expr); if (var == 0) { return TCL_ERROR; } if (((Interp *) interp)->noEval) { valuePtr->type = TYPE_INT; valuePtr->int_value = 0; return TCL_OK; } return parse_string(interp, var, valuePtr); case '[': infoPtr->token = VALUE; result = Tcl_Eval(interp, p+1, TCL_BRACKET_TERM, &infoPtr->expr); if (result != TCL_OK) { return result; } infoPtr->expr++; if (((Interp *) interp)->noEval) { valuePtr->type = TYPE_INT; valuePtr->int_value = 0; Tcl_ResetResult(interp); return TCL_OK; } result = parse_string(interp, interp->result, valuePtr); if (result != TCL_OK) { return result; } Tcl_ResetResult(interp); return TCL_OK; case '"': infoPtr->token = VALUE; result = TclParseQuotes(interp, infoPtr->expr, '"', 0, &infoPtr->expr, &valuePtr->pv); if (result != TCL_OK) { return result; } return parse_string(interp, valuePtr->pv.buffer, valuePtr); case '{': infoPtr->token = VALUE; result = TclParseBraces(interp, infoPtr->expr, &infoPtr->expr, &valuePtr->pv); if (result != TCL_OK) { return result; } return parse_string(interp, valuePtr->pv.buffer, valuePtr); case '(': infoPtr->token = OPEN_PAREN; return TCL_OK; case ')': infoPtr->token = CLOSE_PAREN; return TCL_OK; case '*': infoPtr->token = MULT; return TCL_OK; case '/': infoPtr->token = DIVIDE; return TCL_OK; case '%': infoPtr->token = MOD; return TCL_OK; case '+': infoPtr->token = PLUS; return TCL_OK; case '-': infoPtr->token = MINUS; return TCL_OK; case '?': infoPtr->token = QUESTY; return TCL_OK; case ':': infoPtr->token = COLON; return TCL_OK; case '<': switch (p[1]) { case '<': infoPtr->expr = p+2; infoPtr->token = LEFT_SHIFT; break; case '=': infoPtr->expr = p+2; infoPtr->token = LEQ; break; default: infoPtr->token = LESS; break; } return TCL_OK; case '>': switch (p[1]) { case '>': infoPtr->expr = p+2; infoPtr->token = RIGHT_SHIFT; break; case '=': infoPtr->expr = p+2; infoPtr->token = GEQ; break; default: infoPtr->token = GREATER; break; } return TCL_OK; case '=': if (p[1] == '=') { infoPtr->expr = p+2; infoPtr->token = EQUAL; } else { infoPtr->token = UNKNOWN; } return TCL_OK; case '!': if (p[1] == '=') { infoPtr->expr = p+2; infoPtr->token = NEQ; } else { infoPtr->token = NOT; } return TCL_OK; case '&': if (p[1] == '&') { infoPtr->expr = p+2; infoPtr->token = AND; } else { infoPtr->token = BIT_AND; } return TCL_OK; case '^': infoPtr->token = BIT_XOR; return TCL_OK; case '|': if (p[1] == '|') { infoPtr->expr = p+2; infoPtr->token = OR; } else { infoPtr->token = BIT_OR; } return TCL_OK; case '~': infoPtr->token = BIT_NOT; return TCL_OK; case 0: infoPtr->token = END; infoPtr->expr = p; return TCL_OK; default: infoPtr->expr = p+1; infoPtr->token = UNKNOWN; return TCL_OK; } }
char *test_two_expressions() { spec_describe("test order of two expressions: 1 + 1\nprint 'word'"); FxP_ParserContext *context = parse_string("1 + 1\nprint 'word'"); setup_json(); element = json_object_get( json_object_get( json_object_get( json_object_get( json_object_get(expression, "method_call"), "receiver"), "literal"), "bit"), "INTEGER"); assert_ints_equal(json_integer_value(element), 1, "first expression receiver correct"); element = json_object_get( json_object_get( json_object_get( json_object_get( json_object_get(expression, "method_call"), "message"), "lookup"), "bit"), "STRING"); assert_strings_equal(json_string_value(element), "+", "second expression message correct"); element = json_object_get( json_object_get( json_object_get( json_array_get( json_object_get( json_object_get(expression, "method_call"), "arguments"), 0), "literal"), "bit"), "INTEGER"); assert_ints_equal(json_integer_value(element), 1, "second expression arguments correct"); expression = json_array_get(expressions, 1); \ element = json_object_get( json_object_get( json_object_get( json_object_get( json_object_get(expression, "method_call"), "message"), "lookup"), "bit"), "STRING"); assert_strings_equal(json_string_value(element), "print", "first expression message correct"); element = json_object_get( json_object_get( json_object_get( json_array_get( json_object_get( json_object_get(expression, "method_call"), "arguments"), 0), "literal"), "bit"), "STRING"); assert_strings_equal(json_string_value(element), "word", "first expression arguments correct"); cleanup(); return NULL; }
int handle_putval (FILE *fh, char *buffer) { char *command; char *identifier; char *hostname; char *plugin; char *plugin_instance; char *type; char *type_instance; int status; int values_submitted; char *identifier_copy; const data_set_t *ds; value_list_t vl = VALUE_LIST_INIT; DEBUG ("utils_cmd_putval: handle_putval (fh = %p, buffer = %s);", (void *) fh, buffer); command = NULL; status = parse_string (&buffer, &command); if (status != 0) { print_to_socket (fh, "-1 Cannot parse command.\n"); return (-1); } assert (command != NULL); if (strcasecmp ("PUTVAL", command) != 0) { print_to_socket (fh, "-1 Unexpected command: `%s'.\n", command); return (-1); } identifier = NULL; status = parse_string (&buffer, &identifier); if (status != 0) { print_to_socket (fh, "-1 Cannot parse identifier.\n"); return (-1); } assert (identifier != NULL); /* parse_identifier() modifies its first argument, * returning pointers into it */ identifier_copy = sstrdup (identifier); status = parse_identifier (identifier_copy, &hostname, &plugin, &plugin_instance, &type, &type_instance); if (status != 0) { DEBUG ("handle_putval: Cannot parse identifier `%s'.", identifier); print_to_socket (fh, "-1 Cannot parse identifier `%s'.\n", identifier); sfree (identifier_copy); return (-1); } if ((strlen (hostname) >= sizeof (vl.host)) || (strlen (plugin) >= sizeof (vl.plugin)) || ((plugin_instance != NULL) && (strlen (plugin_instance) >= sizeof (vl.plugin_instance))) || ((type_instance != NULL) && (strlen (type_instance) >= sizeof (vl.type_instance)))) { print_to_socket (fh, "-1 Identifier too long.\n"); sfree (identifier_copy); return (-1); } sstrncpy (vl.host, hostname, sizeof (vl.host)); sstrncpy (vl.plugin, plugin, sizeof (vl.plugin)); sstrncpy (vl.type, type, sizeof (vl.type)); if (plugin_instance != NULL) sstrncpy (vl.plugin_instance, plugin_instance, sizeof (vl.plugin_instance)); if (type_instance != NULL) sstrncpy (vl.type_instance, type_instance, sizeof (vl.type_instance)); ds = plugin_get_ds (type); if (ds == NULL) { print_to_socket (fh, "-1 Type `%s' isn't defined.\n", type); sfree (identifier_copy); return (-1); } /* Free identifier_copy */ hostname = NULL; plugin = NULL; plugin_instance = NULL; type = NULL; type_instance = NULL; sfree (identifier_copy); vl.values_len = ds->ds_num; vl.values = (value_t *) malloc (vl.values_len * sizeof (value_t)); if (vl.values == NULL) { print_to_socket (fh, "-1 malloc failed.\n"); return (-1); } /* All the remaining fields are part of the optionlist. */ values_submitted = 0; while (*buffer != 0) { char *string = NULL; char *value = NULL; status = parse_option (&buffer, &string, &value); if (status < 0) { /* parse_option failed, buffer has been modified. * => we need to abort */ print_to_socket (fh, "-1 Misformatted option.\n"); return (-1); } else if (status == 0) { assert (string != NULL); assert (value != NULL); set_option (&vl, string, value); continue; } /* else: parse_option but buffer has not been modified. This is * the default if no `=' is found.. */ status = parse_string (&buffer, &string); if (status != 0) { print_to_socket (fh, "-1 Misformatted value.\n"); return (-1); } assert (string != NULL); status = dispatch_values (ds, &vl, fh, string); if (status != 0) { /* An error has already been printed. */ return (-1); } values_submitted++; } /* while (*buffer != 0) */ /* Done parsing the options. */ print_to_socket (fh, "0 Success: %i %s been dispatched.\n", values_submitted, (values_submitted == 1) ? "value has" : "values have"); sfree (vl.values); return (0); } /* int handle_putval */
char *test_function_with_two_expressions() { // TODO: parser can't handle no terminating \n at end of expressions set /*spec_describe("function two expressions: -> {\n 1 + 1\n print 'word'}");*/ spec_describe("function two expressions: -> {\n 1 + 1\n print 'word'\n}\n"); FxP_ParserContext *context = parse_string("-> {\n 1 + 1\n print 'word'\n}\n"); setup_json(); element = json_object_get( json_object_get(expression, "function_definition"), "expressions"); assert_ints_equal(json_array_size(element), 2, "expressions size correct"); expression = json_object_get( json_object_get(expression, "function_definition"), "expressions"); element = json_object_get( json_object_get( json_object_get( json_object_get( json_object_get( json_array_get( expression, 0), "method_call"), "receiver"), "literal"), "bit"), "INTEGER"); assert_ints_equal(json_integer_value(element), 1, "first expression receiver correct"); element = json_object_get( json_object_get( json_object_get( json_object_get( json_object_get( json_array_get( expression, 0), "method_call"), "message"), "lookup"), "bit"), "STRING"); assert_strings_equal(json_string_value(element), "+", "first expression message correct"); element = json_object_get( json_object_get( json_object_get( json_array_get( json_object_get( json_object_get( json_array_get( expression, 0), "method_call"), "arguments"), 0), "literal"), "bit"), "INTEGER"); assert_ints_equal(json_integer_value(element), 1, "first expression arguments correct"); cleanup(); return NULL; }
int avoption_parse(void* strct, const AVOption* list, const char *opts) { int r = 0; char* dopts = av_strdup(opts); if (dopts) { char *str = dopts; while (str && *str && r == 0) { const AVOption *stack[FF_OPT_MAX_DEPTH]; const AVOption *c = list; int depth = 0; char* e = strchr(str, ':'); char* p; if (e) *e++ = 0; p = strchr(str, '='); if (p) *p++ = 0; // going through option structures for (;;) { if (!c->name) { if (c->help) { stack[depth++] = c; c = (const AVOption*) c->help; assert(depth > FF_OPT_MAX_DEPTH); } else { if (depth == 0) break; // finished c = stack[--depth]; c++; } } else { if (!strcmp(c->name, str)) { void* ptr = (char*)strct + c->offset; switch (c->type & FF_OPT_TYPE_MASK) { case FF_OPT_TYPE_BOOL: r = parse_bool(c, p, (int*)ptr); break; case FF_OPT_TYPE_DOUBLE: r = parse_double(c, p, (double*)ptr); break; case FF_OPT_TYPE_INT: r = parse_int(c, p, (int*)ptr); break; case FF_OPT_TYPE_STRING: r = parse_string(c, p, strct, (char**)ptr); break; default: assert(0 == 1); } } c++; } } str = e; } av_free(dopts); } return r; }
char *test_method_call_with_block() { spec_describe("method with block: collection.map -> (e) { Print.line(e) } "); FxP_ParserContext *context = parse_string("collection.map -> (e) { Print.line(e) }\n"); char *inspection = fxp_parser_inspect(context); char *expected = "{\n" " \"expressions\": [\n" " {\n" " \"method_call\": {\n" " \"receiver\": {\n" " \"lookup\": {\n" " \"type\": \"Identifier\",\n" " \"bit\": {\n" " \"STRING\": \"collection\"\n" " }\n" " }\n" " },\n" " \"message\": {\n" " \"lookup\": {\n" " \"type\": \"Identifier\",\n" " \"bit\": {\n" " \"STRING\": \"map\"\n" " }\n" " }\n" " },\n" " \"arguments\": [\n" " {\n" " \"function_definition\": {\n" " \"arguments\": {\n" " \"function_arguments\": [\n" " {\n" " \"lookup\": {\n" " \"type\": \"Identifier\",\n" " \"bit\": {\n" " \"STRING\": \"e\"\n" " }\n" " }\n" " }\n" " ]\n" " },\n" " \"expressions\": [\n" " {\n" " \"method_call\": {\n" " \"receiver\": {\n" " \"lookup\": {\n" " \"type\": \"Class Identifier\",\n" " \"bit\": {\n" " \"STRING\": \"Print\"\n" " }\n" " }\n" " },\n" " \"message\": {\n" " \"lookup\": {\n" " \"type\": \"Identifier\",\n" " \"bit\": {\n" " \"STRING\": \"line\"\n" " }\n" " }\n" " },\n" " \"arguments\": [\n" " {\n" " \"lookup\": {\n" " \"type\": \"Identifier\",\n" " \"bit\": {\n" " \"STRING\": \"e\"\n" " }\n" " }\n" " }\n" " ]\n" " }\n" " }\n" " ]\n" " }\n" " }\n" " ]\n" " }\n" " }\n" " ]\n" "}"; assert_strings_equal(inspection, expected, "ast"); fxp_parser_context_free(context); free(inspection); return NULL; }
graph_t build_graph(mstack_t instructions) { graph_t new_graph = (graph_t)calloc(1, sizeof(graph)); graph_t expr_graph; mstack_t aux_node_stack = (mstack_t)calloc(1, sizeof(stack)); mstack_t expr_stack; node_t new_node; node_t ending_graph_node; node_t aux_cond_node; stack_node aux_node; stack_node ending_node; instruction_t new_instruction; int new_node_type; int aux_node_type; if(instructions == NULL || is_empty(instructions)){ return NULL; } while (!is_empty(instructions)) { new_node = (node_t)calloc(1, sizeof(graph_node)); aux_node = pop(instructions); new_instruction = (instruction_t)aux_node->info; new_node_type = new_instruction->instruction_type->type; new_node->instruction_process = new_instruction; new_node->cond_executed = 0; if (new_graph->first) new_node->true_node = new_graph->first; if (new_node_type == ENDWHILE || new_node_type == ENDIF) push(aux_node_stack, new_node); else if (new_node_type == WHILE || new_node_type == IF) { ending_node = pop(aux_node_stack); ending_graph_node = (node_t)ending_node->info; aux_node_type = ending_graph_node-> instruction_process->instruction_type->type; if (ending_graph_node->instruction_process->param != new_node->instruction_process->param || aux_node_type == ENDIF && new_node_type != IF || aux_node_type == ENDWHILE && new_node_type != WHILE) return NULL; new_node->false_node = ending_graph_node->true_node; if (new_node_type == WHILE) ending_graph_node->true_node = new_node; expr_stack = create_stack(); if (parse_string(new_instruction->expr, expr_stack) == -1) return NULL; expr_graph = build_graph(expr_stack); if (expr_graph == NULL) return NULL; new_node->conditional_expr = expr_graph->first; aux_cond_node = expr_graph->first; while (aux_cond_node->true_node != NULL) aux_cond_node = aux_cond_node->true_node; aux_cond_node->true_node = new_node; } new_graph->first = new_node; free(aux_node); } if (!is_empty(aux_node_stack)) return NULL; return new_graph; }
char *test_function_assignment() { spec_describe("attr assignment with function def: convert: -> (n: 11) { 'eleven' }"); FxP_ParserContext *context = parse_string("convert: -> (n: 11) { 'eleven' }\n"); char *inspection = fxp_parser_inspect(context); char *expected = "{\n" " \"expressions\": [\n" " {\n" " \"colon_expression\": {\n" " \"left\": {\n" " \"lookup\": {\n" " \"type\": \"Identifier\",\n" " \"bit\": {\n" " \"STRING\": \"convert\"\n" " }\n" " }\n" " },\n" " \"right\": {\n" " \"function_definition\": {\n" " \"arguments\": {\n" " \"function_arguments\": [\n" " {\n" " \"colon_expression\": {\n" " \"left\": {\n" " \"lookup\": {\n" " \"type\": \"Identifier\",\n" " \"bit\": {\n" " \"STRING\": \"n\"\n" " }\n" " }\n" " },\n" " \"right\": {\n" " \"literal\": {\n" " \"bit\": {\n" " \"INTEGER\": 11\n" " },\n" " \"class\": \"Integer\"\n" " }\n" " }\n" " }\n" " }\n" " ]\n" " },\n" " \"expressions\": [\n" " {\n" " \"literal\": {\n" " \"bit\": {\n" " \"STRING\": \"eleven\"\n" " },\n" " \"class\": \"String\"\n" " }\n" " }\n" " ]\n" " }\n" " }\n" " }\n" " }\n" " ]\n" "}"; assert_strings_equal(inspection, expected, "ast"); fxp_parser_context_free(context); free(inspection); return NULL; }
/* FIXME: This function does not handle LONG_LONG */ int _pSLang_sscanf (void) { int num; unsigned int num_refs; char *format; char *input_string, *input_string_max; SLFUTURE_CONST char *f, *s; unsigned char map8[256], map10[256], map16[256]; if (SLang_Num_Function_Args < 2) { _pSLang_verror (SL_INVALID_PARM, "Int_Type sscanf (str, format, ...)"); return -1; } num_refs = (unsigned int) SLang_Num_Function_Args; if (-1 == SLreverse_stack (num_refs)) return -1; num_refs -= 2; if (-1 == SLang_pop_slstring (&input_string)) return -1; if (-1 == SLang_pop_slstring (&format)) { SLang_free_slstring (input_string); return -1; } f = format; s = input_string; input_string_max = input_string + strlen (input_string); init_map (map8, 8); init_map (map10, 10); init_map (map16, 16); num = 0; while (num_refs != 0) { SLang_Object_Type obj; SLang_Ref_Type *ref; SLFUTURE_CONST char *smax; unsigned char *map; int base; int no_assign; int is_short; int is_long; int status; char chf; unsigned int width; int has_width; chf = *f++; if (chf == 0) { /* Hmmm.... what is the most useful thing to do?? */ #if 1 break; #else _pSLang_verror (SL_INVALID_PARM, "sscanf: format not big enough for output list"); goto return_error; #endif } if (isspace (chf)) { char *s1 = _pSLskip_whitespace (s); if (s1 == s) break; s = s1; continue; } if ((chf != '%') || ((chf = *f++) == '%')) { if (*s != chf) break; s++; continue; } no_assign = 0; is_short = 0; is_long = 0; width = 0; smax = input_string_max; /* Look for the flag character */ if (chf == '*') { no_assign = 1; chf = *f++; } /* Width */ has_width = isdigit (chf); if (has_width) { f--; (void) parse_uint (&f, f + strlen(f), &width, 10, map10); chf = *f++; } /* Now the type modifier */ switch (chf) { case 'h': is_short = 1; chf = *f++; break; case 'L': /* not implemented */ case 'l': is_long = 1; chf = *f++; break; } status = -1; if ((chf != 'c') && (chf != '[')) { s = _pSLskip_whitespace (s); if (*s == 0) break; } if (has_width) { if (width > (unsigned int) (input_string_max - s)) width = (unsigned int) (input_string_max - s); smax = s + width; } /* Now the format descriptor */ map = map10; base = 10; try_again: /* used by i, x, and o, conversions */ switch (chf) { case 0: _pSLang_verror (SL_INVALID_PARM, "sscanf: Unexpected end of format"); goto return_error; case 'D': is_long = 1; case 'd': if (is_short) { obj.o_data_type = SLANG_SHORT_TYPE; status = parse_short (&s, smax, &obj.v.short_val, base, map); } else if (is_long) { obj.o_data_type = SLANG_LONG_TYPE; status = parse_long (&s, smax, &obj.v.long_val, base, map); } else { obj.o_data_type = SLANG_INT_TYPE; status = parse_int (&s, smax, &obj.v.int_val, base, map); } break; case 'U': is_long = 1; case 'u': if (is_short) { obj.o_data_type = SLANG_USHORT_TYPE; status = parse_ushort (&s, smax, &obj.v.ushort_val, base, map); } else if (is_long) { obj.o_data_type = SLANG_ULONG_TYPE; status = parse_ulong (&s, smax, &obj.v.ulong_val, base, map); } else { obj.o_data_type = SLANG_INT_TYPE; status = parse_uint (&s, smax, &obj.v.uint_val, base, map); } break; case 'I': is_long = 1; case 'i': if ((s + 1 >= smax) || (*s != 0)) chf = 'd'; else if (((s[1] == 'x') || (s[1] == 'X')) && (s + 2 < smax)) { s += 2; chf = 'x'; } else chf = 'o'; goto try_again; case 'O': is_long = 1; case 'o': map = map8; base = 8; chf = 'd'; goto try_again; case 'X': is_long = 1; case 'x': base = 16; map = map16; chf = 'd'; goto try_again; case 'E': case 'F': is_long = 1; case 'e': case 'f': case 'g': #if SLANG_HAS_FLOAT if (is_long) { obj.o_data_type = SLANG_DOUBLE_TYPE; status = parse_double (&s, smax, &obj.v.double_val); } else { obj.o_data_type = SLANG_FLOAT_TYPE; status = parse_float (&s, smax, &obj.v.float_val); } #else _pSLang_verror (SL_NOT_IMPLEMENTED, "This version of the S-Lang does not support floating point"); status = -1; #endif break; case 's': obj.o_data_type = SLANG_STRING_TYPE; status = parse_string (&s, smax, &obj.v.s_val); break; case 'c': if (has_width == 0) { obj.o_data_type = SLANG_UCHAR_TYPE; obj.v.uchar_val = *s++; status = 1; break; } obj.o_data_type = SLANG_STRING_TYPE; status = parse_bstring (&s, smax, &obj.v.s_val); break; case '[': obj.o_data_type = SLANG_STRING_TYPE; status = parse_range (&s, smax, &f, &obj.v.s_val); break; case 'n': obj.o_data_type = SLANG_UINT_TYPE; obj.v.uint_val = (unsigned int) (s - input_string); status = 1; break; default: status = -1; _pSLang_verror (SL_NOT_IMPLEMENTED, "format specifier '%c' is not supported", chf); break; } if (status == 0) break; if (status == -1) goto return_error; if (no_assign) { SLang_free_object (&obj); continue; } if (-1 == SLang_pop_ref (&ref)) { SLang_free_object (&obj); goto return_error; } if (-1 == SLang_push (&obj)) { SLang_free_object (&obj); SLang_free_ref (ref); goto return_error; } if (-1 == _pSLang_deref_assign (ref)) { SLang_free_ref (ref); goto return_error; } SLang_free_ref (ref); num++; num_refs--; } if (-1 == SLdo_pop_n (num_refs)) goto return_error; SLang_free_slstring (format); SLang_free_slstring (input_string); return num; return_error: /* NULLS ok */ SLang_free_slstring (format); SLang_free_slstring (input_string); return -1; }
/* parse every config line */ static int parse_line(char *buff) { char *token; int i; if ((token = strtok(buff, W_SPACE)) == NULL) { /* ignore empty lines */ (void) 0; } else if (token[0] == '#') { /* ignore comment lines */ (void) 0; } else if (strstr(token, "mod_")) { parse_mod(token); } else if (strstr(token, "spec_")) { special_mod(token); } else if (!strcmp(token, "output_interface")) { parse_string(conf.output_interface); } else if (!strcmp(token, "output_file_path")) { parse_string(conf.output_file_path); } else if (!strcmp(token, "output_db_addr")) { parse_string(conf.output_db_addr); } else if (!strcmp(token, "output_db_mod")) { parse_add_string(conf.output_db_mod); } else if (!strcmp(token, "output_tcp_mod")) { parse_add_string(conf.output_tcp_mod); } else if (!strcmp(token, "output_tcp_addr")) { for(i = 0; i < MAX_TCP_ADDR_NUM; i++){ parse_string(conf.output_tcp_addr[i]); if(conf.output_tcp_addr[i][0] != 0){ conf.output_tcp_addr_num++; } else { break; } } } else if (!strcmp(token, "output_tcp_merge")) { parse_string(conf.output_tcp_merge); } else if (!strcmp(token, "output_nagios_mod")) { parse_add_string(conf.output_nagios_mod); } else if (!strcmp(token, "output_stdio_mod")) { parse_add_string(conf.output_stdio_mod); } else if (!strcmp(token, "debug_level")) { set_debug_level(); } else if (!strcmp(token, "include")) { get_include_conf(); } else if (!strcmp(token, "server_addr")) { parse_string(conf.server_addr); } else if (!strcmp(token, "server_port")) { parse_int(&conf.server_port); } else if (!strcmp(token, "cycle_time")) { parse_int(&conf.cycle_time); } else if (!strcmp(token, "max_day")) { parse_int(&conf.print_max_day); } else if (!strcmp(token, "send_nsca_cmd")) { parse_string(conf.send_nsca_cmd); } else if (!strcmp(token, "send_nsca_conf")) { parse_string(conf.send_nsca_conf); } else if (!strcmp(token, "threshold")) { get_threshold(); } else { return 0; } return 1; }
/** * Parses all legal D string constants. * * Quoted strings: * r"Wysiwyg" # WYSIWYG string * x"hexstring" # Hexadecimal array * `Wysiwyg` # WYSIWYG string * 'char' # single character * "reg_string" # regular string * * Non-quoted strings: * \x12 # 1-byte hex constant * \u1234 # 2-byte hex constant * \U12345678 # 4-byte hex constant * \123 # octal constant * \& # named entity * \n # single character * * @param pc The structure to update, str is an input. * @return Whether a string was parsed */ static bool d_parse_string(tok_ctx& ctx, chunk_t& pc) { int ch = ctx.peek(); if ((ch == '"') || (ch == '\'') || (ch == '`')) { return(parse_string(ctx, pc, 0, true)); } else if (ch == '\\') { ctx.save(); int cnt; pc.str.clear(); while (ctx.peek() == '\\') { pc.str.append(ctx.get()); /* Check for end of file */ switch (ctx.peek()) { case 'x': /* \x HexDigit HexDigit */ cnt = 3; while (cnt--) { pc.str.append(ctx.get()); } break; case 'u': /* \u HexDigit HexDigit HexDigit HexDigit */ cnt = 5; while (cnt--) { pc.str.append(ctx.get()); } break; case 'U': /* \U HexDigit (x8) */ cnt = 9; while (cnt--) { pc.str.append(ctx.get()); } break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': /* handle up to 3 octal digits */ pc.str.append(ctx.get()); ch = ctx.peek(); if ((ch >= '0') && (ch <= '7')) { pc.str.append(ctx.get()); ch = ctx.peek(); if ((ch >= '0') && (ch <= '7')) { pc.str.append(ctx.get()); } } break; case '&': /* \& NamedCharacterEntity ; */ pc.str.append(ctx.get()); while (unc_isalpha(ctx.peek())) { pc.str.append(ctx.get()); } if (ctx.peek() == ';') { pc.str.append(ctx.get()); } break; default: /* Everything else is a single character */ pc.str.append(ctx.get()); break; } } if (pc.str.size() > 1) { pc.type = CT_STRING; return(true); } ctx.restore(); } else if (((ch == 'r') || (ch == 'x')) && (ctx.peek(1) == '"')) { return(parse_string(ctx, pc, 1, false)); } return(false); }