/** * The block function. * * block ::= const-declaration var-declaration statement. */ int block(FILE *input_file, token_type *token) { int error_code = 0; symbol *symbol; // sl, dl, ra curr_m[curr_l] += 3; error_code = emit(INC, 0, 3); if(error_code) return error_code; // const if(*token == constsym) { do { // identsym *token = get_token(input_file); if(*token != identsym) return 4; symbol = get_symbol(input_file, 1); // eqsym *token = get_token(input_file); if(*token != eqsym) { if(*token == becomessym) return 1; else return 3; } // number *token = get_token(input_file); if(*token != numbersym) return 2; if(!symbol->kind) { symbol->kind = 1; symbol->val = get_number(input_file); } else { return 29; } *token = get_token(input_file); } while(*token == commasym); if(*token != semicolonsym) return 5; *token = get_token(input_file); } // int if(*token == intsym) { int num_vars = 0; do { // identsym *token = get_token(input_file); if(*token != identsym) return 4; symbol = get_symbol(input_file, 1); if(!symbol->kind) { symbol->kind = 2; symbol->level = curr_l; symbol->addr = curr_m[curr_l]++; num_vars++; } else { return 28; } *token = get_token(input_file); } while(*token == commasym); if(*token != semicolonsym) return 5; error_code = emit(INC, 0, num_vars); if(error_code) return error_code; *token = get_token(input_file); } // proc while(*token == procsym) { // identsym *token = get_token(input_file); if(*token != identsym) return 4; // add identifier to symbol_table symbol = get_symbol(input_file, 1); if(!symbol->kind) { symbol->kind = 3; symbol->level = curr_l; symbol->addr = cx+1; /*curr_m[curr_l]++;*/ curr_l++; } else { return 28; } // semicolonsym *token = get_token(input_file); if(*token != semicolonsym) return 5; *token = get_token(input_file); // JMP over the proc code int c1 = cx; error_code = emit(JMP, 0, 0); if(error_code) return error_code; // recurse block again error_code = block(input_file, token); if(error_code) return error_code; // return error_code = emit(OPR, 0, OPR_RET); if(error_code) return error_code; // set the address for the JMP code[c1].m = cx; // some cleanup, uses the curr_l global // clears all symbols at curr_l and then decrement curr_l proc_cleanup(); // semicolonsym if(*token != semicolonsym) return 5; *token = get_token(input_file); } error_code = statement(input_file, token); if(error_code) return error_code; return error_code; }
/** * The statement function. * * statement ::= [ ident ":=" expression * | "call" ident * | "begin" statement { ";" statement } "end" * | "if" condition "then" statement ["else" statement] * | "while" condition "do" statement * | "read" ident * | "write" expression * | e ] . */ int statement(FILE *input_file, token_type *token) { symbol *symbol; //int number; int error_code = 0; if(*token == identsym) { symbol = get_symbol(input_file, 0); if(!symbol->kind) { return 11; } if(symbol->kind != 2) { return 12; } *token = get_token(input_file); // becomessym if(*token != becomessym) return 13; *token = get_token(input_file); error_code = expression(input_file, token); if(error_code) return error_code; error_code = emit(STO, abs(symbol->level - curr_l), symbol->addr); if(error_code) return error_code; } // callsym else if(*token == callsym) { *token = get_token(input_file); if(*token != identsym) return 14; symbol = get_symbol(input_file, 0); if(!symbol) { return 14; } else if(!symbol->kind) { return 11; } else if(symbol->kind != 3) { return 15; } error_code = emit(CAL, abs(symbol->level - curr_l), symbol->addr); if(error_code) return error_code; *token = get_token(input_file); } // beginsym else if(*token == beginsym) { *token = get_token(input_file); error_code = statement(input_file, token); if(error_code) return error_code; while(*token == semicolonsym) { *token = get_token(input_file); error_code = statement(input_file, token); if(error_code) return error_code; } // XXX not sure if this is right, but let's roll with it if(*token != endsym) { if(*token == periodsym || *token == nulsym) return 17; return 10; } *token = get_token(input_file); } // ifsym else if(*token == ifsym) { *token = get_token(input_file); // condition error_code = condition(input_file, token); if(error_code) return error_code; if(*token != thensym) return 16; // then expected *token = get_token(input_file); int c1 = cx; error_code = emit(JPC, 0, 0); if(error_code) return error_code; error_code = statement(input_file, token); if(error_code) return error_code; // this is for jumping over the else int c2 = cx; error_code = emit(JMP, 0, 0); if(error_code) return error_code; code[c1].m = cx; // token is either semicolonsym or elsesym at this point if(*token == elsesym) { *token = get_token(input_file); error_code = statement(input_file, token); if(error_code) return error_code; } code[c2].m = cx; return error_code; } // whilesym else if(*token == whilesym) { int cx1 = cx; *token = get_token(input_file); // condition error_code = condition(input_file, token); if(error_code) return error_code; int cx2 = cx; error_code = emit(JPC, 0, 0); if(error_code) return error_code; if(*token != dosym) return 18; // do expected *token = get_token(input_file); error_code = statement(input_file, token); if(error_code) return error_code; error_code = emit(JMP, 0, cx1); if(error_code) return error_code; code[cx2].m = cx; return error_code; } else if(*token == outsym) { *token = get_token(input_file); error_code = expression(input_file, token); if(error_code) return error_code; error_code = emit(SIO_OUT, 0, 1); if(error_code) return error_code; } else if(*token == insym) { *token = get_token(input_file); if(*token == identsym) { symbol = get_symbol(input_file, 0); if(!symbol->kind) { return 11; } else if(symbol->kind == 2) { error_code = emit(SIO_IN, 0, 2); if(error_code) return error_code; error_code = emit(STO, abs(symbol->level - curr_l), symbol->addr); if(error_code) return error_code; } else { return 27; } } else { return 27; } *token = get_token(input_file); } /* XXX statements can be the empty string so wtf else { // statement expected return 7; } */ return error_code; }
/* * Parse list of statements */ static int conf_parse_group(ifd_conf_node_t * group, char closing) { ifd_conf_node_t *node; char *token; int rc = 0; while (1) { if (ateof()) { if (closing == (char)END_OF_FILE) break; ct_error("%s:%u: unexpected end of file", config_filename, config_line); return -1; } if ((rc = get_token(&token)) < 0) break; /* Check if this is the closing group character; if * so, return. No other separators allowed here */ if (*token == closing) break; if (issepa(*token)) goto unexpected; node = conf_add_node(group, token); if ((rc = get_token(&token)) < 0) break; /* Get the value - the following are valid * name = value; * name value { ... }; * name { ... }; * value, value, ... */ if (*token == EQUALS) { /* name = value case */ if ((rc = get_token(&token)) < 0) break; } if (!issepa(*token)) { node->value = strdup(token); /* Get the next token */ if ((rc = get_token(&token)) < 0) break; } else if (*token == GROUP_BEGIN || *token == COMMA) { /* Do-nothing cases: * name { ... } * foo, bar, baz, ... */ } else { /* everything else illegal here */ goto unexpected; } if (*token == GROUP_BEGIN) { /* Parse the group, then get the next * token */ if ((rc = conf_parse_group(node, GROUP_END)) < 0 || (rc = get_token(&token)) < 0) break; } if (*token != SEMICOLON && *token != COMMA) goto unexpected; } return rc; unexpected: ct_error("%s: line %d: unexpected token \"%s\"", config_filename, config_line, token); return -1; }
static NMErr ParseConfigString( const char *inConfigStr, NMType inGameID, const char *inGameName, const void *inEnumData, NMUInt32 inDataLen, NMIPConfigPriv *outConfig) { NMErr status = kNMNoError; NMInetPort port = GenerateDefaultPort(inGameID); InetHost host = 0x7f000001; // loopback address NMBoolean gotToken; NMSInt32 tokenLen; char workString[kMaxHostNameLen + 1]; NMUInt32 p; outConfig->type = kModuleID; outConfig->version = kVersion; outConfig->gameID = inGameID; outConfig->connectionMode = kNMNormalMode; if (inGameName) { strncpy(outConfig->name, inGameName, kMaxGameNameLen); outConfig->name[kMaxGameNameLen]= 0; } else { strcpy(outConfig->name, "unknown"); } if (inDataLen) { if (inDataLen > kNMEnumDataLen) return kNMInvalidConfigErr; op_assert(inDataLen <= kNMEnumDataLen); machine_move_data(inEnumData, outConfig->customEnumData, inDataLen); outConfig->customEnumDataLen = inDataLen; } else { outConfig->customEnumDataLen = 0; } if (OTUtils::OTInitialized()) { OTInitInetAddress((InetAddress *)&outConfig->address, port, host); } else { op_vpause("Classic not supported!"); } // default netSprocketMode outConfig->netSprocketMode = kDefaultNetSprocketMode; // If we got a null string, just create a default config if (inConfigStr == NULL) return kNMNoError; //Try_ { // Generic module information // Read the type tokenLen = sizeof (NMType); gotToken = get_token(inConfigStr, kConfigModuleType, LONG_DATA, &outConfig->type, &tokenLen); if (!gotToken) outConfig->type = kModuleID; // Read the version tokenLen = sizeof (NMUInt32); gotToken = get_token(inConfigStr, kConfigModuleVersion, LONG_DATA, &outConfig->version, &tokenLen); if (!gotToken) outConfig->version = kVersion; // Read the game id tokenLen = sizeof (NMUInt32); gotToken = get_token(inConfigStr, kConfigGameID, LONG_DATA, &outConfig->gameID, &tokenLen); if (!gotToken) outConfig->gameID = 0; // Read the game name if (inGameName == NULL || inGameName[0] == 0) { tokenLen = kMaxGameNameLen; gotToken = get_token(inConfigStr, kConfigGameName, STRING_DATA, &outConfig->name, &tokenLen); if (!gotToken) strcpy(outConfig->name, "unknown"); } // Read the connection mode tokenLen = sizeof (NMUInt32); gotToken = get_token(inConfigStr, kConfigEndpointMode, LONG_DATA, &outConfig->connectionMode, &tokenLen); if (! gotToken) outConfig->connectionMode = kNMNormalMode; // Read the netSprocketMode mode tokenLen = sizeof (NMBoolean); gotToken = get_token(inConfigStr, kConfigNetSprocketMode, BOOLEAN_DATA, &outConfig->netSprocketMode, &tokenLen); if (!gotToken) outConfig->netSprocketMode = kDefaultNetSprocketMode; // read the custom data, if any if (inDataLen == 0) { tokenLen = kNMEnumDataLen; gotToken = get_token(inConfigStr, kConfigCustomData, BINARY_DATA, &outConfig->customEnumData, &tokenLen); if (gotToken) outConfig->customEnumDataLen = tokenLen; } // IP Module-specific information // Read the dotted quad IP address tokenLen = kMaxHostNameLen; gotToken = get_token(inConfigStr, kIPConfigAddress, STRING_DATA, workString, &tokenLen); if (! gotToken) { outConfig->address.fHost = host; } else { // This is OT-dependent, and could cause the PPP module to dial-in. // It will also fail if DNS is not available status = OTUtils::MakeInetAddressFromString(workString, &outConfig->address); } if (outConfig->address.fPort == 0) outConfig->address.fPort = port; // Read the port. We don't care if it's not present. It might have been in the address tokenLen = sizeof (NMUInt32); gotToken = get_token(inConfigStr, kIPConfigPort, LONG_DATA, &p, &tokenLen); if (gotToken) outConfig->address.fPort = p; return kNMNoError; } //Catch_(code) error: if (status) { NMErr code = status; return code; } return status; }
void matrix_format ( MPL *mpl, SET *set, /* not changed */ MEMBER *memb, /* modified */ SLICE *slice, /* not changed */ int tr ) { SLICE *list, *col, *temp; TUPLE *tuple; SYMBOL *row; insist(set != NULL); insist(memb != NULL); insist(slice != NULL); insist(set->dimen == slice_dimen(mpl, slice)); insist(memb->value.set->dim == set->dimen); insist(slice_arity(mpl, slice) == 2); /* read the matrix heading that contains column symbols (there may be no columns at all) */ list = create_slice(mpl); while (mpl->token != T_ASSIGN) { /* read column symbol and append it to the column list */ if (!is_symbol(mpl)) error(mpl, "number, symbol, or := missing where expected"); list = expand_slice(mpl, list, read_symbol(mpl)); } get_token(mpl /* := */); /* read zero or more rows that contain matrix data */ while (is_symbol(mpl)) { /* read row symbol (if the matrix has no columns, row symbols are just ignored) */ row = read_symbol(mpl); /* read the matrix row accordingly to the column list */ for (col = list; col != NULL; col = col->next) { int which = 0; /* check indicator */ if (is_literal(mpl, "+")) ; else if (is_literal(mpl, "-")) { get_token(mpl /* - */); continue; } else { int lack = slice_dimen(mpl, col); if (lack == 1) error(mpl, "one item missing in data group beginning " "with %s", format_symbol(mpl, row)); else error(mpl, "%d items missing in data group beginning " "with %s", lack, format_symbol(mpl, row)); } /* construct complete n-tuple */ tuple = create_tuple(mpl); for (temp = slice; temp != NULL; temp = temp->next) { if (temp->sym == NULL) { /* substitution is needed */ switch (++which) { case 1: /* substitute in the first null position */ tuple = expand_tuple(mpl, tuple, copy_symbol(mpl, tr ? col->sym : row)); break; case 2: /* substitute in the second null position */ tuple = expand_tuple(mpl, tuple, copy_symbol(mpl, tr ? row : col->sym)); break; default: insist(which != which); } } else { /* copy symbol from the slice */ tuple = expand_tuple(mpl, tuple, copy_symbol(mpl, temp->sym)); } } insist(which == 2); /* add constructed n-tuple to elemental set */ check_then_add(mpl, memb->value.set, tuple); get_token(mpl /* + */); } /* delete the row symbol */ delete_symbol(mpl, row); } /* delete the column list */ delete_slice(mpl, list); return; }
void tabular_format ( MPL *mpl, PARAMETER *par, /* not changed */ SLICE *slice, /* not changed */ int tr ) { SLICE *list, *col, *temp; TUPLE *tuple; SYMBOL *row; insist(par != NULL); insist(par->dim == slice_dimen(mpl, slice)); insist(slice_arity(mpl, slice) == 2); /* read the table heading that contains column symbols (the table may have no columns) */ list = create_slice(mpl); while (mpl->token != T_ASSIGN) { /* read column symbol and append it to the column list */ if (!is_symbol(mpl)) error(mpl, "number, symbol, or := missing where expected"); list = expand_slice(mpl, list, read_symbol(mpl)); } get_token(mpl /* := */); /* read zero or more rows that contain tabular data */ while (is_symbol(mpl)) { /* read row symbol (if the table has no columns, these symbols are just ignored) */ row = read_symbol(mpl); /* read values accordingly to the column list */ for (col = list; col != NULL; col = col->next) { int which = 0; /* if the token is single point, no value is provided */ if (is_literal(mpl, ".")) { get_token(mpl /* . */); continue; } /* construct complete subscript list */ tuple = create_tuple(mpl); for (temp = slice; temp != NULL; temp = temp->next) { if (temp->sym == NULL) { /* substitution is needed */ switch (++which) { case 1: /* substitute in the first null position */ tuple = expand_tuple(mpl, tuple, copy_symbol(mpl, tr ? col->sym : row)); break; case 2: /* substitute in the second null position */ tuple = expand_tuple(mpl, tuple, copy_symbol(mpl, tr ? row : col->sym)); break; default: insist(which != which); } } else { /* copy symbol from the slice */ tuple = expand_tuple(mpl, tuple, copy_symbol(mpl, temp->sym)); } } insist(which == 2); /* read value and assign it to new parameter member */ if (!is_symbol(mpl)) { int lack = slice_dimen(mpl, col); if (lack == 1) error(mpl, "one item missing in data group beginning " "with %s", format_symbol(mpl, row)); else error(mpl, "%d items missing in data group beginning " "with %s", lack, format_symbol(mpl, row)); } read_value(mpl, par, tuple); } /* delete the row symbol */ delete_symbol(mpl, row); } /* delete the column list */ delete_slice(mpl, list); return; }
int parse_codec_cfg(const char *cfgfile) { codecs_t *codec = NULL; // current codec codecs_t **codecsp = NULL;// points to audio_codecs or to video_codecs char *endptr; // strtoul()... int *nr_codecsp; int codec_type; /* TYPE_VIDEO/TYPE_AUDIO */ int tmp, i; // in case we call it a second time codecs_uninit_free(); nr_vcodecs = 0; nr_acodecs = 0; if(cfgfile==NULL) { #ifdef CODECS2HTML return 0; #else video_codecs = builtin_video_codecs; audio_codecs = builtin_audio_codecs; nr_vcodecs = sizeof(builtin_video_codecs)/sizeof(codecs_t); nr_acodecs = sizeof(builtin_audio_codecs)/sizeof(codecs_t); return 1; #endif } mp_msg(MSGT_CODECCFG,MSGL_V,MSGTR_ReadingFile, cfgfile); if ((fp = fopen(cfgfile, "r")) == NULL) { mp_msg(MSGT_CODECCFG,MSGL_V,MSGTR_CantOpenFileError, cfgfile, strerror(errno)); return 0; } if ((line = malloc(MAX_LINE_LEN + 1)) == NULL) { mp_msg(MSGT_CODECCFG,MSGL_FATAL,MSGTR_CantGetMemoryForLine, strerror(errno)); return 0; } read_nextline = 1; /* * this only catches release lines at the start of * codecs.conf, before audiocodecs and videocodecs. */ while ((tmp = get_token(1, 1)) == RET_EOL) /* NOTHING */; if (tmp == RET_EOF) goto out; if (!strcmp(token[0], "release")) { if (get_token(1, 2) < 0) goto err_out_parse_error; tmp = atoi(token[0]); if (tmp < CODEC_CFG_MIN) goto err_out_release_num; codecs_conf_release = tmp; while ((tmp = get_token(1, 1)) == RET_EOL) /* NOTHING */; if (tmp == RET_EOF) goto out; } else goto err_out_release_num; /* * check if the next block starts with 'audiocodec' or * with 'videocodec' */ if (!strcmp(token[0], "audiocodec") || !strcmp(token[0], "videocodec")) goto loop_enter; goto err_out_parse_error; while ((tmp = get_token(1, 1)) != RET_EOF) { if (tmp == RET_EOL) continue; if (!strcmp(token[0], "audiocodec") || !strcmp(token[0], "videocodec")) { if (!validate_codec(codec, codec_type)) goto err_out_not_valid; loop_enter: if (*token[0] == 'v') { codec_type = TYPE_VIDEO; nr_codecsp = &nr_vcodecs; codecsp = &video_codecs; } else if (*token[0] == 'a') { codec_type = TYPE_AUDIO; nr_codecsp = &nr_acodecs; codecsp = &audio_codecs; #ifdef DEBUG } else { mp_msg(MSGT_CODECCFG,MSGL_ERR,"picsba\n"); goto err_out; #endif } if (!(*codecsp = realloc(*codecsp, sizeof(codecs_t) * (*nr_codecsp + 2)))) { mp_msg(MSGT_CODECCFG,MSGL_FATAL,MSGTR_CantReallocCodecsp, strerror(errno)); goto err_out; } codec=*codecsp + *nr_codecsp; ++*nr_codecsp; memset(codec,0,sizeof(codecs_t)); memset(codec->fourcc, 0xff, sizeof(codec->fourcc)); memset(codec->outfmt, 0xff, sizeof(codec->outfmt)); memset(codec->infmt, 0xff, sizeof(codec->infmt)); if (get_token(1, 1) < 0) goto err_out_parse_error; for (i = 0; i < *nr_codecsp - 1; i++) { if(( (*codecsp)[i].name!=NULL) && (!strcmp(token[0], (*codecsp)[i].name)) ) { mp_msg(MSGT_CODECCFG,MSGL_ERR,MSGTR_CodecNameNotUnique, token[0]); goto err_out_print_linenum; } } if (!(codec->name = strdup(token[0]))) { mp_msg(MSGT_CODECCFG,MSGL_ERR,MSGTR_CantStrdupName, strerror(errno)); goto err_out; } } else if (!strcmp(token[0], "info")) { if (codec->info || get_token(1, 1) < 0) goto err_out_parse_error; if (!(codec->info = strdup(token[0]))) { mp_msg(MSGT_CODECCFG,MSGL_ERR,MSGTR_CantStrdupInfo, strerror(errno)); goto err_out; } } else if (!strcmp(token[0], "comment")) { if (get_token(1, 1) < 0) goto err_out_parse_error; add_comment(token[0], &codec->comment); } else if (!strcmp(token[0], "fourcc")) { if (get_token(1, 2) < 0) goto err_out_parse_error; if (!add_to_fourcc(token[0], token[1], codec->fourcc, codec->fourccmap)) goto err_out_print_linenum; } else if (!strcmp(token[0], "format")) { if (get_token(1, 2) < 0) goto err_out_parse_error; if (!add_to_format(token[0], token[1], codec->fourcc,codec->fourccmap)) goto err_out_print_linenum; } else if (!strcmp(token[0], "driver")) { if (get_token(1, 1) < 0) goto err_out_parse_error; if (!(codec->drv = strdup(token[0]))) { mp_msg(MSGT_CODECCFG,MSGL_ERR,MSGTR_CantStrdupDriver, strerror(errno)); goto err_out; } } else if (!strcmp(token[0], "dll")) { if (get_token(1, 1) < 0) goto err_out_parse_error; if (!(codec->dll = strdup(token[0]))) { mp_msg(MSGT_CODECCFG,MSGL_ERR,MSGTR_CantStrdupDLL, strerror(errno)); goto err_out; } } else if (!strcmp(token[0], "guid")) { if (get_token(11, 11) < 0) goto err_out_parse_error; codec->guid.f1=strtoul(token[0],&endptr,0); if ((*endptr != ',' || *(endptr + 1) != '\0') && *endptr != '\0') goto err_out_parse_error; codec->guid.f2=strtoul(token[1],&endptr,0); if ((*endptr != ',' || *(endptr + 1) != '\0') && *endptr != '\0') goto err_out_parse_error; codec->guid.f3=strtoul(token[2],&endptr,0); if ((*endptr != ',' || *(endptr + 1) != '\0') && *endptr != '\0') goto err_out_parse_error; for (i = 0; i < 8; i++) { codec->guid.f4[i]=strtoul(token[i + 3],&endptr,0); if ((*endptr != ',' || *(endptr + 1) != '\0') && *endptr != '\0') goto err_out_parse_error; } } else if (!strcmp(token[0], "out")) { if (get_token(1, 2) < 0) goto err_out_parse_error; if (!add_to_inout(token[0], token[1], codec->outfmt, codec->outflags)) goto err_out_print_linenum; } else if (!strcmp(token[0], "in")) { if (get_token(1, 2) < 0) goto err_out_parse_error; if (!add_to_inout(token[0], token[1], codec->infmt, codec->inflags)) goto err_out_print_linenum; } else if (!strcmp(token[0], "flags")) { if (get_token(1, 1) < 0) goto err_out_parse_error; if (!strcmp(token[0], "seekable")) codec->flags |= CODECS_FLAG_SEEKABLE; else if (!strcmp(token[0], "align16")) codec->flags |= CODECS_FLAG_ALIGN16; else goto err_out_parse_error; } else if (!strcmp(token[0], "status")) { if (get_token(1, 1) < 0) goto err_out_parse_error; if (!strcasecmp(token[0], "working")) codec->status = CODECS_STATUS_WORKING; else if (!strcasecmp(token[0], "crashing")) codec->status = CODECS_STATUS_NOT_WORKING; else if (!strcasecmp(token[0], "untested")) codec->status = CODECS_STATUS_UNTESTED; else if (!strcasecmp(token[0], "buggy")) codec->status = CODECS_STATUS_PROBLEMS; else goto err_out_parse_error; } else if (!strcmp(token[0], "cpuflags")) { if (get_token(1, 1) < 0) goto err_out_parse_error; if (!(codec->cpuflags = get_cpuflags(token[0]))) goto err_out_parse_error; } else goto err_out_parse_error; } if (!validate_codec(codec, codec_type)) goto err_out_not_valid; mp_msg(MSGT_CODECCFG,MSGL_INFO,MSGTR_AudioVideoCodecTotals, nr_acodecs, nr_vcodecs); if(video_codecs) video_codecs[nr_vcodecs].name = NULL; if(audio_codecs) audio_codecs[nr_acodecs].name = NULL; out: free(line); line=NULL; fclose(fp); return 1; err_out_parse_error: mp_msg(MSGT_CODECCFG,MSGL_ERR,MSGTR_ParseError); err_out_print_linenum: PRINT_LINENUM; err_out: codecs_uninit_free(); free(line); line=NULL; line_num = 0; fclose(fp); return 0; err_out_not_valid: mp_msg(MSGT_CODECCFG,MSGL_ERR,MSGTR_CodecDefinitionIncorrect); goto err_out_print_linenum; err_out_release_num: mp_msg(MSGT_CODECCFG,MSGL_ERR,MSGTR_OutdatedCodecsConf); goto err_out_print_linenum; }
void parameter_data(MPL *mpl) { PARAMETER *par; SYMBOL *altval = NULL; SLICE *slice; int tr = 0; insist(is_literal(mpl, "param")); get_token(mpl /* param */); /* read optional default value */ if (is_literal(mpl, "default")) { get_token(mpl /* default */); if (!is_symbol(mpl)) error(mpl, "default value missing where expected"); altval = read_symbol(mpl); /* if the default value follows the keyword 'param', the next token must be only the colon */ if (mpl->token != T_COLON) error(mpl, "colon missing where expected"); } /* being used after the keyword 'param' or the optional default value the colon begins data in the tabbing format */ if (mpl->token == T_COLON) { get_token(mpl /* : */); /* skip optional comma */ if (mpl->token == T_COMMA) get_token(mpl /* , */); /* read parameter data in the tabbing format */ tabbing_format(mpl, altval); /* on reading data in the tabbing format the default value is always copied, so delete the original symbol */ if (altval != NULL) delete_symbol(mpl, altval); /* the next token must be only semicolon */ if (mpl->token != T_SEMICOLON) error(mpl, "symbol, number, or semicolon missing where expe" "cted"); get_token(mpl /* ; */); goto done; } /* in other cases there must be symbolic name of parameter, which follows the keyword 'param' */ if (!is_symbol(mpl)) error(mpl, "parameter name missing where expected"); /* select the parameter to saturate it with data */ par = select_parameter(mpl, mpl->image); get_token(mpl /* <symbol> */); /* read optional default value */ if (is_literal(mpl, "default")) { get_token(mpl /* default */); if (!is_symbol(mpl)) error(mpl, "default value missing where expected"); altval = read_symbol(mpl); /* set default value for the parameter */ set_default(mpl, par, altval); } /* create initial fake slice of all asterisks */ slice = fake_slice(mpl, par->dim); /* read zero or more data assignments */ for (;;) { /* skip optional comma */ if (mpl->token == T_COMMA) get_token(mpl /* , */); /* process current assignment */ if (mpl->token == T_ASSIGN) { /* assignment ligature is non-significant element */ get_token(mpl /* := */); } else if (mpl->token == T_LBRACKET) { /* left bracket begins new slice; delete the current slice and read new one */ delete_slice(mpl, slice); slice = read_slice(mpl, par->name, par->dim); /* each new slice resets the "transpose" indicator */ tr = 0; } else if (is_symbol(mpl)) { /* number or symbol begins data in the plain format */ plain_format(mpl, par, slice); } else if (mpl->token == T_COLON) { /* colon begins data in the tabular format */ if (par->dim == 0) err1: error(mpl, "%s not a subscripted parameter", par->name); if (slice_arity(mpl, slice) != 2) err2: error(mpl, "slice currently used must specify 2 asterisk" "s, not %d", slice_arity(mpl, slice)); get_token(mpl /* : */); /* read parameter data in the tabular format */ tabular_format(mpl, par, slice, tr); } else if (mpl->token == T_LEFT) { /* left parenthesis begins the "transpose" indicator, which is followed by data in the tabular format */ get_token(mpl /* ( */); if (!is_literal(mpl, "tr")) err3: error(mpl, "transpose indicator (tr) incomplete"); if (par->dim == 0) goto err1; if (slice_arity(mpl, slice) != 2) goto err2; get_token(mpl /* tr */); if (mpl->token != T_RIGHT) goto err3; get_token(mpl /* ) */); /* in this case the colon is optional */ if (mpl->token == T_COLON) get_token(mpl /* : */); /* set the "transpose" indicator */ tr = 1; /* read parameter data in the tabular format */ tabular_format(mpl, par, slice, tr); } else if (mpl->token == T_SEMICOLON) { /* semicolon terminates the data block */ get_token(mpl /* ; */); break; } else error(mpl, "syntax error in parameter data block"); } /* delete the current slice */ delete_slice(mpl, slice); done: return; }
// Parse drive database from abstract input pointer. static bool parse_drive_database(parse_ptr src, drive_database & db, const char * path) { int state = 0, field = 0; std::string values[5]; bool ok = true; token_info token; int line = 1; src = get_token(src, token, path, line); for (;;) { // EOF is ok after '}', trailing ',' is also allowed. if (!token.type && (state == 0 || state == 4)) break; // Check expected token const char expect[] = "{\",},"; if (token.type != expect[state]) { if (token.type != '?') pout("%s(%d): Syntax error, '%c' expected\n", path, token.line, expect[state]); ok = false; // Skip to next entry while (token.type && token.type != '{') src = get_token(src, token, path, line); state = 0; if (token.type) continue; break; } // Interpret parser state switch (state) { case 0: // ... ^{...} state = 1; field = 0; break; case 1: // {... ^"..." ...} switch (field) { case 1: case 2: if (!token.value.empty()) { regular_expression regex; if (!regex.compile(token.value.c_str(), REG_EXTENDED)) { pout("%s(%d): Error in regular expression: %s\n", path, token.line, regex.get_errmsg()); ok = false; } } else if (field == 1) { pout("%s(%d): Missing regular expression for drive model\n", path, token.line); ok = false; } break; case 4: if (!token.value.empty()) { // Syntax check switch (get_modelfamily_type(values[0].c_str())) { case DBENTRY_ATA_DEFAULT: { ata_vendor_attr_defs defs; if (!parse_default_presets(token.value.c_str(), defs)) { pout("%s(%d): Syntax error in DEFAULT option string\n", path, token.line); ok = false; } } break; default: { // DBENTRY_ATA ata_vendor_attr_defs defs; firmwarebug_defs fix; if (!parse_presets(token.value.c_str(), defs, fix)) { pout("%s(%d): Syntax error in preset option string\n", path, token.line); ok = false; } } break; case DBENTRY_USB: { std::string type; if (!parse_usb_type(token.value.c_str(), type)) { pout("%s(%d): Syntax error in USB type string\n", path, token.line); ok = false; } } break; } } break; } values[field] = token.value; state = (++field < 5 ? 2 : 3); break; case 2: // {... "..."^, ...} state = 1; break; case 3: // {...^}, ... { drive_settings entry; entry.modelfamily = values[0].c_str(); entry.modelregexp = values[1].c_str(); entry.firmwareregexp = values[2].c_str(); entry.warningmsg = values[3].c_str(); entry.presets = values[4].c_str(); db.push_back(entry); } state = 4; break; case 4: // {...}^, ... state = 0; break; default: pout("Bad state %d\n", state); return false; } src = get_token(src, token, path, line); } return ok; }
static int parse_ifdef_expression(struct _asm_context *asm_context, int *num, int paren_count, int precedence, int state) { char token[TOKENLEN]; struct _operator operator; int token_type; //int state=0; // 0 = get next num to process int not=0; int n1=0; int n; operator.operation=OPER_NONE; operator.precedence=precedence; n=*num; while(1) { token_type=get_token(asm_context, token, TOKENLEN); #ifdef DEBUG printf("debug> #if: %d) %s n=%d paren_count=%d precedence=%d state=%d\n", token_type, token, n, paren_count, precedence, state); #endif if (token_type==TOKEN_EOL || token_type==TOKEN_EOF) { pushback(asm_context, token, token_type); if (paren_count!=0) { print_error("Unbalanced parentheses.", asm_context); return -1; } if (state!=1) { print_error("Unexpected end of expression.", asm_context); return -1; } if (operator.operation!=OPER_NONE) { n=eval_operation(operator.operation,n1,n); #ifdef DEBUG printf("debug> #if eval_operation() @EOL n=%d precedence=%d state=%d\n", n, precedence, state); #endif if (n==-1) { return -1; } } *num=n; return 0; } if (state!=1) { if (state==2) { n1=n; } if (token_type==TOKEN_SYMBOL) { if (IS_TOKEN(token,'!')) { not^=1; continue; } else if (IS_TOKEN(token,'(')) { if (parse_ifdef_expression(asm_context, &n, paren_count+1, PREC_OR, 0)==-1) return -1; } else if (IS_TOKEN(token,')')) { if (paren_count==0) { print_error_unexp(token, asm_context); return -1; } if (state!=1) { print_error("Unexpected end of expression.", asm_context); return -1; } if (operator.operation!=OPER_NONE) { n=eval_operation(operator.operation,n1,n); #ifdef DEBUG printf("debug> #if eval_operation() @paren n=%d\n", n); #endif if (n==-1) { return -1; } } *num=n; return 0; } } else if (token_type==TOKEN_STRING) { int param_count; char *value=defines_heap_lookup(&asm_context->defines_heap, token, ¶m_count); if (strcasecmp(token, "defined")==0) { n=parse_defined(asm_context); #ifdef DEBUG printf("debug> #if: parse_defined()=%d\n", n); #endif if (n==-1) return -1; } else if (value!=NULL && param_count==0 && is_num(value)) { n=atoi(value); } else { print_error_unexp(token, asm_context); return -1; } } else if (token_type==TOKEN_NUMBER) { n=atoi(token); } if (not==1) { if (n==0) { n=1; } else { n=0; } not=0; } #if 0 if (state==2) { #ifdef DEBUG printf("debug> #if eval_operation() n1=%d n=%d\n", n1, n); #endif n=eval_operation(operator.operation,n1,n); state=0; #ifdef DEBUG printf("debug> #if eval_operation() n=%d operation=%d\n", n, operator.operation); #endif } #endif state=1; continue; } if (token_type==TOKEN_SYMBOL || token_type==TOKEN_EQUALITY) { struct _operator next_operator; if (get_operator(token, &next_operator)==-1) { print_error_unexp(token, asm_context); return -1; } #ifdef DEBUG printf("debug> #if get_operator() token=%s operation=%d precedence=%d\n", token, next_operator.operation, next_operator.precedence); #endif if (next_operator.precedence>precedence) { pushback(asm_context, token, token_type); if (parse_ifdef_expression(asm_context, &n, paren_count, next_operator.precedence, 1)==-1) return -1; } else if (next_operator.precedence<precedence) { pushback(asm_context, token, token_type); return 0; } else { state=2; if (operator.operation!=OPER_NONE) { n=eval_operation(operator.operation,n1,n); #ifdef DEBUG printf("debug> #if eval_operation() @ state 2 n=%d\n", n); #endif if (n==-1) { return -1; } } operator=next_operator; } continue; } print_error_unexp(token, asm_context); return -1; } return -1; }
// --- bool cmp_function( const char* s1, const char* s2 ) { CStr t1; CStr t2; bool b1; bool b2; bool complete = true; bool call = true; enum { it_type, it_name, it_comma } counter = it_type; b1 = get_token( s1, t1 ); if ( !::lstrcmp(t1,"static") ) b1 = get_token( s1, t1 ); b2 = get_token( s2, t2 ); if ( !::lstrcmp(t2,"static") ) b2 = get_token( s2, t2 ); while( 1 ) { if ( b1 != b2 ) return false; if ( !b1 ) return true; if ( counter == it_name ) ; else if ( lstrcmp(t1,t2) ) return false; if ( complete ) { if ( *t1 == BRACKET_O ) { if (*s1 == BRACKET_C) // has no parameters { if (*s2 == BRACKET_C) return true; return false; } complete = false; // switch to parameter mode } } else { switch( counter ) { case it_type: if ( call && !lstrcmp(t1,"pr_call") ) { call = false; complete = true; // switch to complete mode } else if ( !lstrcmp(t1,"const") ) ; // do not switch to "it_name: mode else counter = it_name; break; case it_name: if ( ((*t1 == STAR) || (*t2 == STAR)) ) { if ( *t1 != *t2 ) return false; } else counter = it_comma; break; case it_comma: counter = it_type; if ( *t1 == BRACKET_C ) // we got it !! return true; break; } } b1 = get_token( s1, t1 ); b2 = get_token( s2, t2 ); } }
/****************************************************************************** ** Function: read_hex_data() ** ** Purpose: ** This routine reads hex digits from the file specified by fc and places the ** data in the buffer specified by the void buffer pointer. The software will ** read data until it hits the end of the line or it has read max_bytes of data. ** Note that his code assumes that there will be only one data item (packet) per line. */ static void read_hex_data(utf_file_context_type *fc, void *buffer, unsigned short int max_bytes, unsigned short int data_type) { unsigned short int i; unsigned short int bytes_read = 0; unsigned long int *dword_ptr = (unsigned long int *)buffer; unsigned short int *word_ptr = (unsigned short int *)buffer; unsigned char *byte_ptr = (unsigned char *)buffer; switch(data_type) { /* assumes that 1 NUMBER token has already been read prior to calling this routine */ case UTF_AS_BYTE: while ((token != END_OF_LINE) && (bytes_read < max_bytes)) { *byte_ptr = 0; for (i=0; i < 2; i++) { if (token == END_OF_LINE) UTF_error("File: %s, Line: %d, Not Enough Characters For AS_BYTE Read", fc->filename, fc->line_number-1); if (token != NUMBER) UTF_error("File: %s, Line: %d, Invalid Hex Number Read", fc->filename, fc->line_number); *byte_ptr = (*byte_ptr << 4) + c_to_hex(number_token); token = get_token(fc); } bytes_read += 1; byte_ptr++; } if ((token != END_OF_LINE) && (bytes_read >= max_bytes)) UTF_error("File: %s, Line: %d, Input Data Exceeds Max Size of %d", fc->filename, fc->line_number, max_bytes); break; case UTF_AS_WORD: if ((max_bytes % 2) != 0) UTF_error("File: %s, Line: %d, Invalid Max_Bytes Parameter For AS_WORD Read, %d", fc->filename, fc->line_number, max_bytes); while ((token != END_OF_LINE) && (bytes_read < max_bytes)) { *word_ptr = 0; for (i=0; i < 4; i++) { if (token == END_OF_LINE) UTF_error("File: %s, Line: %d, Not Enough Characters For AS_WORD Read", fc->filename, fc->line_number-1); if (token != NUMBER) UTF_error("File: %s, Line: %d, Invalid Hex Number Read", fc->filename, fc->line_number); *word_ptr = (*word_ptr << 4) + c_to_hex(number_token); token = get_token(fc); } bytes_read += 2; word_ptr++; } if ((token != END_OF_LINE) && (bytes_read >= max_bytes)) UTF_error("File: %s, Line: %d, Input Data Exceeds Max Size of %d", fc->filename, fc->line_number, max_bytes); break; case UTF_AS_DWORD: if ((max_bytes % 4) != 0) UTF_error("File: %s, Line: %d, Invalid Max_Bytes Parameter For AS_DWORD Read, %d", fc->filename, fc->line_number, max_bytes); while ((token != END_OF_LINE) && (bytes_read < max_bytes)) { *dword_ptr = 0; for (i=0; i < 8; i++) { if (token == END_OF_LINE) UTF_error("File: %s, Line: %d, Not Enough Characters For AS_DWORD Read", fc->filename, fc->line_number-1); if (token != NUMBER) UTF_error("File: %s, Line: %d, Invalid Hex Number Read", fc->filename, fc->line_number); *dword_ptr = (*dword_ptr << 4) + c_to_hex(number_token); token = get_token(fc); } bytes_read += 4; dword_ptr++; } if ((token != END_OF_LINE) && (bytes_read >= max_bytes)) UTF_error("File: %s, Line: %d, Input Data Exceeds Max Size of %d", fc->filename, fc->line_number, max_bytes); break; default: UTF_error("File: %s, Line: %d, Invalid DATA_TYPE For Read, %d", fc->filename, fc->line_number, data_type); break; } }
//----------- End of function FileTxt::get_num ------// // // Convert current token to number and return the number // double FileTxt::get_num() { return atof( get_token() ); }
device_t *cartslot_get_pcb(device_t *device) { multicartslot_t *cart = get_token(device); return cart->pcb_device; }
int asmgen_parse_syms(struct SymTab **curSyms, FILE *handle) { struct ScanData asmScan; unsigned int offset = 0; struct Token curToken; TokenType ttype; struct ASMRecord *rec, *asmrec = NULL; int found; /* set up the scanner */ SCANNER_INIT(&asmScan,handle); /* main loop */ while (1) { switch (get_token(&curToken, &asmScan)) { case TOK_EOF: /* end of file */ SCANNER_STOP(&asmScan); /* make a special symbol to note size of assembled file */ symtab_record(curSyms, "$filesize", NULL, offset); return 0; break; case TOK_LABEL: /* hit a line label */ symtab_record(curSyms, curToken.token, NULL, offset); break; case TOK_ENDL: /* end of line at beginning, skip to next */ break; case TOK_DIRECTIVE: /* directive, pass current data to directive handler */ directive_parse(&asmScan, &curToken, curSyms, &asmrec, &offset); break; case TOK_IDENT: /* assume to be an assembly mnemonic */ DEBUG(3) printf("Got identifier - %s\n", curToken.token); /* find mnemonic in record */ found = 0; for (rec=asmrec; (found==0)&&(rec!=NULL); rec=rec->next) { if (strcmp(curToken.token, rec->mnemonic) == 0) { found = 1; offset += rec->byte_count; /* scan tokens until end of line */ do { ttype = get_token(&curToken, &asmScan); } while ((ttype != TOK_EOF) && (ttype != TOK_ENDL)); } } if (found == 0) { fprintf(stderr, "ERROR - mnemonic %s not found\n", curToken.token); SCANNER_STOP(&asmScan); return -1; } break; default: fprintf(stderr, "Unexpected Token %s, line %d\n", curToken.token, curToken.linenum); SCANNER_STOP(&asmScan); return -1; break; } } }
void setup_chromaticity_correction(NAMELIST_TEXT *nltext, RUN *run, LINE_LIST *beamline, CHROM_CORRECTION *chrom) { VMATRIX *M; ELEMENT_LIST *eptr, *elast; #include "chrom.h" unsigned long unstable; log_entry("setup_chromaticity_correction"); cp_str(&sextupoles, "sf sd"); /* process namelist input */ set_namelist_processing_flags(STICKY_NAMELIST_DEFAULTS); set_print_namelist_flags(0); if (processNamelist(&chromaticity, nltext)==NAMELIST_ERROR) bombElegant(NULL, NULL); str_toupper(sextupoles); if (echoNamelists) print_namelist(stdout, &chromaticity); if (run->default_order<2) bombElegant("default order must be >= 2 for chromaticity correction", NULL); if (chrom->name) tfree(chrom->name); chrom->name = tmalloc(sizeof(*chrom->name)*(chrom->n_families=1)); while ((chrom->name[chrom->n_families-1]=get_token(sextupoles))) chrom->name = trealloc(chrom->name, sizeof(*chrom->name)*(chrom->n_families+=1)); if ((--chrom->n_families)<1) bombElegant("too few sextupoles given for chromaticity correction", NULL); chrom->chromx = dnux_dp; chrom->chromy = dnuy_dp; chrom->n_iterations = n_iterations; chrom->correction_fraction = correction_fraction; alter_defined_values = change_defined_values; chrom->strengthLimit = strength_limit; chrom->use_perturbed_matrix = use_perturbed_matrix; chrom->sextupole_tweek = sextupole_tweek; chrom->tolerance = tolerance; verbosityLevel = verbosity; chrom->exit_on_failure = exit_on_failure; if (!use_perturbed_matrix) { if (!beamline->twiss0 || !beamline->matrix) { double beta_x, alpha_x, eta_x, etap_x; double beta_y, alpha_y, eta_y, etap_y; fprintf(stdout, "Computing periodic Twiss parameters.\n"); fflush(stdout); if (!beamline->twiss0) beamline->twiss0 = tmalloc(sizeof(*beamline->twiss0)); eptr = beamline->elem_twiss = &(beamline->elem); elast = eptr; while (eptr) { if (eptr->type==T_RECIRC) beamline->elem_twiss = beamline->elem_recirc = eptr; elast = eptr; eptr = eptr->succ; } if (beamline->links) { /* rebaseline_element_links(beamline->links, run, beamline); */ if (assert_element_links(beamline->links, run, beamline, STATIC_LINK+DYNAMIC_LINK)) { beamline->flags &= ~BEAMLINE_CONCAT_CURRENT; beamline->flags &= ~BEAMLINE_TWISS_CURRENT; beamline->flags &= ~BEAMLINE_RADINT_CURRENT; } } M = beamline->matrix = compute_periodic_twiss(&beta_x, &alpha_x, &eta_x, &etap_x, beamline->tune, &beta_y, &alpha_y, &eta_y, &etap_y, beamline->tune+1, beamline->elem_twiss, NULL, run, &unstable, NULL, NULL); beamline->twiss0->betax = beta_x; beamline->twiss0->alphax = alpha_x; beamline->twiss0->phix = 0; beamline->twiss0->etax = eta_x; beamline->twiss0->etapx = etap_x; beamline->twiss0->betay = beta_y; beamline->twiss0->alphay = alpha_y; beamline->twiss0->phiy = 0; beamline->twiss0->etay = eta_y; beamline->twiss0->etapy = etap_y; propagate_twiss_parameters(beamline->twiss0, beamline->tune, beamline->waists, NULL, beamline->elem_twiss, run, NULL, beamline->couplingFactor); } if (!(M=beamline->matrix) || !M->C || !M->R || !M->T) bombElegant("something wrong with transfer map for beamline (setup_chromaticity_correction)", NULL); computeChromCorrectionMatrix(run, beamline, chrom); } #if USE_MPI if (!writePermitted) strength_log = NULL; #endif if (strength_log) { strength_log = compose_filename(strength_log, run->rootname); fp_sl = fopen_e(strength_log, "w", 0); fprintf(fp_sl, "SDDS1\n&column name=Step, type=long, description=\"Simulation step\" &end\n"); fprintf(fp_sl, "&column name=K2, type=double, units=\"1/m$a2$n\" &end\n"); fprintf(fp_sl, "&column name=SextupoleName, type=string &end\n"); fprintf(fp_sl, "&data mode=ascii, no_row_counts=1 &end\n"); fflush(fp_sl); } log_exit("setup_chromaticity_correction"); }
int asmgen_assemble(struct SymTab **curSyms, FILE *input, char *data) { struct ScanData cfgScan; struct Token curToken; struct ASMRecord *instr; struct ASMRecord *asmcfg = NULL; unsigned int argCount, fieldNum, value; unsigned int offset = 0, outBits; int x; /* set up the scanner */ SCANNER_INIT(&cfgScan, input); /* try to assemble this thing */ while (1) { switch (get_token(&curToken, &cfgScan)) { case TOK_EOF: /* end of file, stop assembling */ return 0; break; case TOK_LABEL: case TOK_ENDL: /* ignore these tokens, just pass over */ break; case TOK_DIRECTIVE: /* directive, pass current data to directive handler */ directive_parse(&cfgScan, &curToken, NULL, &asmcfg, &offset); break; case TOK_IDENT: /* assume this is a format entry */ DEBUG(1) printf("\nAssembling mnemonic %s\n", curToken.token); /* find instruction layout */ for (instr = asmcfg; (instr!=NULL) && (strcmp(instr->mnemonic, curToken.token) != 0); instr = instr->next) { } /* shouldn't happen, but just in case */ if (instr == NULL) { printf("ERROR - Unexpected instruction %s\n", curToken.token); return -1; } /* got it, so start assembling */ DEBUG(1) printf("Found format for instruction %s, %d bytes\n", curToken.token, instr->byte_count); outBits = instr->asm_mask; for (argCount=0; argCount<instr->num_args; argCount++) { /* parse next token or parenthesized expression */ if (asmgen_parse_value(&cfgScan, curSyms, &value) != 0) { fprintf(stderr, "ERROR - Argument %d bad, line %d\n", argCount, curToken.linenum); return -1; } if (CHECK_FIELD_TOO_SMALL(instr->arg_widths[argCount], value)) { printf("WARNING - Value 0x%x not representable with %d bits, line %d\n", value, instr->arg_widths[argCount], curToken.linenum); } /* token OK, fill in all fields using this */ for (fieldNum=0; instr->fmt_args[fieldNum].argNum > -1; fieldNum++) { if (argCount == instr->fmt_args[fieldNum].argNum) { DEBUG(1) printf("Field number %d uses arg %d (value 0x%x)\n", fieldNum, argCount, value); outBits |= GETBITS(0,instr->arg_widths[argCount], value) << instr->fmt_args[fieldNum].argOffset; } } } /* expect the newline at the end */ if (get_token(&curToken, &cfgScan) != TOK_ENDL) { fprintf(stderr, "ERROR - Bad token %s at end of line %d\n", curToken.token, curToken.linenum); return -1; } /* fill in the assembled instruction into the data buffer */ DEBUG(1) printf("Outputting %d bytes\n", instr->byte_count); for (x=(instr->byte_count-1); x>=0; x--) { data[offset] = GETBITS(8*x,(8*x)+7, outBits); DEBUG(1) printf("Assembled %02x\n", data[offset]); offset += 1; } break; default: /* dunno, this is bad */ fprintf(stderr, "ERROR - Bad token %s at line %d\n", curToken.token, curToken.linenum); return -1; break; } } return 0; }
SLICE *read_slice ( MPL *mpl, char *name, /* not changed */ int dim ) { SLICE *slice; int close; insist(name != NULL); switch (mpl->token) { case T_LBRACKET: close = T_RBRACKET; break; case T_LEFT: insist(dim > 0); close = T_RIGHT; break; default: insist(mpl != mpl); } if (dim == 0) error(mpl, "%s cannot be subscripted", name); get_token(mpl /* ( | [ */); /* read slice components */ slice = create_slice(mpl); for (;;) { /* the current token must be a symbol or asterisk */ if (is_symbol(mpl)) slice = expand_slice(mpl, slice, read_symbol(mpl)); else if (mpl->token == T_ASTERISK) { slice = expand_slice(mpl, slice, NULL); get_token(mpl /* * */); } else error(mpl, "number, symbol, or asterisk missing where expec" "ted"); /* check a token that follows the symbol */ if (mpl->token == T_COMMA) get_token(mpl /* , */); else if (mpl->token == close) break; else error(mpl, "syntax error in slice"); } /* number of slice components must be the same as the appropriate dimension */ if (slice_dimen(mpl, slice) != dim) { switch (close) { case T_RBRACKET: error(mpl, "%s must have %d subscript%s, not %d", name, dim, dim == 1 ? "" : "s", slice_dimen(mpl, slice)); break; case T_RIGHT: error(mpl, "%s has dimension %d, not %d", name, dim, slice_dimen(mpl, slice)); break; default: insist(close != close); } } get_token(mpl /* ) | ] */); return slice; }
int asmgen_parse_value(struct ScanData *scanner, struct SymTab **curSyms, unsigned int *pResult) { struct Token curToken; unsigned int lval, rval; /* scan next token or expression */ switch (get_token(&curToken, scanner)) { case TOK_INT: /* integer value, just pass it back */ DEBUG(1) printf("Got an integer - %d\n", curToken.value); lval = curToken.value; if (curToken.limHigh - curToken.limLow < 8*sizeof(lval) - 1) { /* if token is specified with a bitslice, use only those bits */ lval = GETBITS(curToken.limLow, curToken.limHigh, lval); } *pResult = lval; return 0; break; case TOK_IDENT: /* identifier, locate it in the symbol table */ DEBUG(1) printf("Got a symbol lookup - '%s'\n", curToken.token); if (symtab_lookup(curSyms, curToken.token, NULL, (int*)&lval) == 0) { /* symbol table lookup success */ if (curToken.limHigh - curToken.limLow < 8*sizeof(lval) - 1) { /* if token is specified with a bitslice, use only those bits */ lval = GETBITS(curToken.limLow, curToken.limHigh, lval); } *pResult = lval; return 0; } printf("ERROR - Symbol '%s' Not Found\n", curToken.token); break; case TOK_LPAREN: /* left parentheses, beginning of an arithmetic expression */ /* start by evaluating first term (may be another expression */ if (asmgen_parse_value(scanner, curSyms, &lval) != 0) { /* error parsing sub-expression */ printf("ERROR - Cannot Parse Arithmetic Expression\n"); return -1; } /* inner loop to evalate left-to-right arithmetic expressions */ while (1) { /* get next token */ switch (get_token(&curToken, scanner)) { case TOK_RPAREN: /* close parentheses, end of sub-expression */ *pResult = lval; return 0; break; case TOK_ARITHOP: /* arithmetic operation (+/-), get right hand value */ if (asmgen_parse_value(scanner, curSyms, &rval) != 0) { /* error parsing sub-expression */ printf("ERROR - Cannot Parse Arithmetic Expression\n"); return -1; } /* handle arithmetic operation */ switch (curToken.token[0]) { case '+': lval += rval; break; case '-': lval -= rval; break; default: /* unhandled */ printf("ERROR - Unknown Arithmetic operation '%s'\n", curToken.token); return -1; break; } break; default: printf("ERROR - Unexpected token '%s' while parsing subexpression\n", curToken.token); return -1; break; } } break; default: /* unknown token */ printf("Unhandled token \'%s\'\n", curToken.token); break; } return -1; }
void set_data(MPL *mpl) { SET *set; TUPLE *tuple; MEMBER *memb; SLICE *slice; int tr = 0; insist(is_literal(mpl, "set")); get_token(mpl /* set */); /* symbolic name of set must follows the keyword 'set' */ if (!is_symbol(mpl)) error(mpl, "set name missing where expected"); /* select the set to saturate it with data */ set = select_set(mpl, mpl->image); get_token(mpl /* <symbolic name> */); /* read optional subscript list, which identifies member of the set to be read */ tuple = create_tuple(mpl); if (mpl->token == T_LBRACKET) { /* subscript list is specified */ if (set->dim == 0) error(mpl, "%s cannot be subscripted", set->name); get_token(mpl /* [ */); /* read symbols and construct subscript list */ for (;;) { if (!is_symbol(mpl)) error(mpl, "number or symbol missing where expected"); tuple = expand_tuple(mpl, tuple, read_symbol(mpl)); if (mpl->token == T_COMMA) get_token(mpl /* , */); else if (mpl->token == T_RBRACKET) break; else error(mpl, "syntax error in subscript list"); } if (set->dim != tuple_dimen(mpl, tuple)) error(mpl, "%s must have %d subscript%s rather than %d", set->name, set->dim, set->dim == 1 ? "" : "s", tuple_dimen(mpl, tuple)); get_token(mpl /* ] */); } else { /* subscript list is not specified */ if (set->dim != 0) error(mpl, "%s must be subscripted", set->name); } /* there must be no member with the same subscript list */ if (find_member(mpl, set->array, tuple) != NULL) error(mpl, "%s%s already defined", set->name, format_tuple(mpl, '[', tuple)); /* add new member to the set and assign it empty elemental set */ memb = add_member(mpl, set->array, tuple); memb->value.set = create_elemset(mpl, set->dimen); /* create an initial fake slice of all asterisks */ slice = fake_slice(mpl, set->dimen); /* read zero or more data assignments */ for (;;) { /* skip optional comma */ if (mpl->token == T_COMMA) get_token(mpl /* , */); /* process assignment element */ if (mpl->token == T_ASSIGN) { /* assignment ligature is non-significant element */ get_token(mpl /* := */); } else if (mpl->token == T_LEFT) { /* left parenthesis begins either new slice or "transpose" indicator */ int is_tr; get_token(mpl /* ( */); is_tr = is_literal(mpl, "tr"); unget_token(mpl /* ( */); if (is_tr) goto left; /* delete the current slice and read new one */ delete_slice(mpl, slice); slice = read_slice(mpl, set->name, set->dimen); /* each new slice resets the "transpose" indicator */ tr = 0; /* if the new slice is 0-ary, formally there is one 0-tuple (in the simple format) that follows it */ if (slice_arity(mpl, slice) == 0) simple_format(mpl, set, memb, slice); } else if (is_symbol(mpl)) { /* number or symbol begins data in the simple format */ simple_format(mpl, set, memb, slice); } else if (mpl->token == T_COLON) { /* colon begins data in the matrix format */ if (slice_arity(mpl, slice) != 2) err1: error(mpl, "slice currently used must specify 2 asterisk" "s, not %d", slice_arity(mpl, slice)); get_token(mpl /* : */); /* read elemental set data in the matrix format */ matrix_format(mpl, set, memb, slice, tr); } else if (mpl->token == T_LEFT) left: { /* left parenthesis begins the "transpose" indicator, which is followed by data in the matrix format */ get_token(mpl /* ( */); if (!is_literal(mpl, "tr")) err2: error(mpl, "transpose indicator (tr) incomplete"); if (slice_arity(mpl, slice) != 2) goto err1; get_token(mpl /* tr */); if (mpl->token != T_RIGHT) goto err2; get_token(mpl /* ) */); /* in this case the colon is optional */ if (mpl->token == T_COLON) get_token(mpl /* : */); /* set the "transpose" indicator */ tr = 1; /* read elemental set data in the matrix format */ matrix_format(mpl, set, memb, slice, tr); } else if (mpl->token == T_SEMICOLON) { /* semicolon terminates the data block */ get_token(mpl /* ; */); break; } else error(mpl, "syntax error in set data block"); } /* delete the current slice */ delete_slice(mpl, slice); return; }
// Parse the next part of the string as an expression bool get_expression(const char **s, uint32 *v, int priority, int flags) { uint32 b; char store[MAX_CMDLEN]; get_token(s, store, sizeof(store), 1); char *x = store; if (!*x) { // Got empty token, could be a unary operator or a parenthesis switch (peek_char (s)) { case '(': (*s)++; if (!get_expression (s, v, 0, PAREN_EAT | PAREN_EXPECT)) return false; break; case '+': (*s)++; if (!get_expression (s, v, 4, flags & ~PAREN_EAT)) return false; break; case '-': (*s)++; if (!get_expression (s, v, 4, flags & ~PAREN_EAT)) return false; *v = (uint32)-(int32)*v; break; case '!': (*s)++; if (!get_expression (s, v, 4, flags & ~PAREN_EAT)) return false; *v = !*v; break; case '~': (*s)++; if (!get_expression (s, v, 4, flags & ~PAREN_EAT)) return false; *v = ~*v; break; case 0: case ',': return false; default: ScriptError("Unexpected input '%s'", *s); return false; } } else { if (*x >= '0' && *x <= '9') { // We got a number char *err; *v = strtoul(x, &err, 0); if (*err) { ScriptError("Expected a number, got %s", x); return false; } } // Look through variables else if (!GetVar(x, s, v)) { ScriptError("Unknown variable '%s' in expression", x); return false; } } // Peek next char and see if it is a operator bool unk_op = false; while (!unk_op) { char op = peek_char (s); if ((op == '=' || op == '!') && *(*s + 1) == '=') { if (priority > 1) return true; *s += 2; if (!get_expression (s, &b, 1, flags & ~PAREN_EAT)) return false; if (op == '=') *v = (*v == b); else *v = (*v != b); continue; } switch (op) { case '+': case '-': case '|': case '^': if (priority > 2) return true; (*s)++; if (!get_expression (s, &b, 2, flags & ~PAREN_EAT)) return false; switch (op) { case '+': *v += b; break; case '-': *v -= b; break; case '|': *v |= b; break; case '^': *v ^= b; break; } break; case '*': case '/': case '%': case '&': if (priority > 3) return true; (*s)++; if (!get_expression (s, &b, 3, flags & ~PAREN_EAT)) return false; switch (op) { case '*': *v *= b; break; case '/': *v /= b; break; case '%': *v %= b; break; case '&': *v &= b; break; } break; case ')': if (!(flags & PAREN_EXPECT)) { ScriptError("Unexpected ')'"); return false; } if (flags & PAREN_EAT) (*s)++; return true; default: unk_op = true; break; } } if (flags & PAREN_EXPECT) { ScriptError("No closing ')'"); return false; } return true; }
void tabbing_format ( MPL *mpl, SYMBOL *altval /* not changed */ ) { SET *set = NULL; PARAMETER *par; SLICE *list, *col; TUPLE *tuple; int next_token, j, dim = 0; char *last_name = NULL; /* read the optional <prefix> */ if (is_symbol(mpl)) { get_token(mpl /* <symbol> */); next_token = mpl->token; unget_token(mpl /* <symbol> */); if (next_token == T_COLON) { /* select the set to saturate it with data */ set = select_set(mpl, mpl->image); /* the set must be simple (i.e. not set of sets) */ if (set->dim != 0) error(mpl, "%s must be a simple set", set->name); /* and must not be defined yet */ if (set->array->head != NULL) error(mpl, "%s already defined", set->name); /* add new (the only) member to the set and assign it empty elemental set */ add_member(mpl, set->array, NULL)->value.set = create_elemset(mpl, set->dimen); last_name = set->name, dim = set->dimen; get_token(mpl /* <symbol> */); insist(mpl->token == T_COLON); get_token(mpl /* : */); } } /* read the table heading that contains parameter names */ list = create_slice(mpl); while (mpl->token != T_ASSIGN) { /* there must be symbolic name of parameter */ if (!is_symbol(mpl)) error(mpl, "parameter name or := missing where expected"); /* select the parameter to saturate it with data */ par = select_parameter(mpl, mpl->image); /* the parameter must be subscripted */ if (par->dim == 0) error(mpl, "%s not a subscripted parameter", mpl->image); /* the set (if specified) and all the parameters in the data block must have identical dimension */ if (dim != 0 && par->dim != dim) { insist(last_name != NULL); error(mpl, "%s has dimension %d while %s has dimension %d", last_name, dim, par->name, par->dim); } /* set default value for the parameter (if specified) */ if (altval != NULL) set_default(mpl, par, copy_symbol(mpl, altval)); /* append the parameter to the column list */ list = expand_slice(mpl, list, (SYMBOL *)par); last_name = par->name, dim = par->dim; get_token(mpl /* <symbol> */); /* skip optional comma */ if (mpl->token == T_COMMA) get_token(mpl /* , */); } if (slice_dimen(mpl, list) == 0) error(mpl, "at least one parameter name required"); get_token(mpl /* := */); /* skip optional comma */ if (mpl->token == T_COMMA) get_token(mpl /* , */); /* read rows that contain tabbing data */ while (is_symbol(mpl)) { /* read subscript list */ tuple = create_tuple(mpl); for (j = 1; j <= dim; j++) { /* read j-th subscript */ if (!is_symbol(mpl)) { int lack = slice_dimen(mpl, list) + dim - j + 1; insist(tuple != NULL); insist(lack > 1); error(mpl, "%d items missing in data group beginning wit" "h %s", lack, format_symbol(mpl, tuple->sym)); } /* read and append j-th subscript to the n-tuple */ tuple = expand_tuple(mpl, tuple, read_symbol(mpl)); /* skip optional comma *between* <symbols> */ if (j < dim && mpl->token == T_COMMA) get_token(mpl /* , */); } /* if the set is specified, add to it new n-tuple, which is a copy of the subscript list just read */ if (set != NULL) check_then_add(mpl, set->array->head->value.set, copy_tuple(mpl, tuple)); /* skip optional comma between <symbol> and <value> */ if (mpl->token == T_COMMA) get_token(mpl /* , */); /* read values accordingly to the column list */ for (col = list; col != NULL; col = col->next) { /* if the token is single point, no value is provided */ if (is_literal(mpl, ".")) { get_token(mpl /* . */); continue; } /* read value and assign it to new parameter member */ if (!is_symbol(mpl)) { int lack = slice_dimen(mpl, col); insist(tuple != NULL); if (lack == 1) error(mpl, "one item missing in data group beginning " "with %s", format_symbol(mpl, tuple->sym)); else error(mpl, "%d items missing in data group beginning " "with %s", lack, format_symbol(mpl, tuple->sym)); } read_value(mpl, (PARAMETER *)col->sym, copy_tuple(mpl, tuple)); /* skip optional comma preceding the next value */ if (col->next != NULL && mpl->token == T_COMMA) get_token(mpl /* , */); } /* delete the original subscript list */ delete_tuple(mpl, tuple); /* skip optional comma (only if there is next data group) */ if (mpl->token == T_COMMA) { get_token(mpl /* , */); if (!is_symbol(mpl)) unget_token(mpl /* , */); } } /* delete the column list (it contains parameters, not symbols, so nullify it before) */ for (col = list; col != NULL; col = col->next) col->sym = NULL; delete_slice(mpl, list); return; }
static void cmd_joinlist(const char *cmd, const char *args) { char destname[MAX_CMDLEN]; if (get_token(&args, destname, sizeof(destname), 1)) { ScriptError("Expected <dest list>"); return; } commandBase *rawvar = FindVar(destname); listVarBase *destvar = listVarBase::cast(rawvar); if (!destvar) { if (rawvar) { ScriptError("Expected list variable"); return; } const char *tmp = args; char peek[MAX_CMDLEN]; if (get_token(&tmp, peek, sizeof(peek), 1)) { ScriptError("Expected <source list1>"); return; } listVarBase *peekvar = listVarBase::cast(FindVar(peek)); if (!peekvar) { ScriptError("Expected <source list1>"); return; } destvar = static_cast<listVarBase*>(peekvar->newVar()); if (!destvar) { ScriptError("Unable to allocate new variable %s", destname); return; } AddVar(destname, destvar); } for (;;) { char srcvarname[MAX_CMDLEN]; if (get_token(&args, srcvarname, sizeof(srcvarname), 1)) // Done return; rawvar = FindVar(srcvarname); if (!rawvar) { ScriptError("Expected <source list> instead of %s", srcvarname); return; } if (strcmp(rawvar->type, destvar->type) != 0) { ScriptError("Type mismatch on list variable %s", srcvarname); return; } listVarBase *srcvar = static_cast<listVarBase*>(rawvar); uint cnt = *srcvar->count; uint copycnt = min(cnt, destvar->maxavail - *destvar->count); void *p = (char *)destvar->data + destvar->datasize * (*destvar->count); memcpy(p, srcvar->data, destvar->datasize * copycnt); *destvar->count += copycnt; if (cnt != copycnt) { Output(C_WARN "Truncating list '%s' to %d" , destname, destvar->maxavail); return; } } }
static RNumCalcValue prim(RNum *num, RNumCalc *nc, int get) { RNumCalcValue v = {0}; if (get) { get_token (num, nc); } switch (nc->curr_tok) { case RNCNUMBER: v = nc->number_value; get_token (num, nc); return v; case RNCNAME: //fprintf (stderr, "error: unknown keyword (%s)\n", nc->string_value); //double& v = table[nc->string_value]; r_str_chop (nc->string_value); v = Nset (r_num_get (num, nc->string_value)); get_token (num, nc); if (nc->curr_tok == RNCASSIGN) { v = expr (num, nc, 1); } if (nc->curr_tok == RNCINC) { Naddi (v, 1); } if (nc->curr_tok == RNCDEC) { Nsubi (v, 1); } return v; case RNCNEG: v = nc->number_value; get_token (num, nc); return Nneg (nc->number_value); //prim (num, nc, 1), 1); case RNCINC: return Naddi (prim (num, nc, 1), 1); case RNCDEC: return Naddi (prim (num, nc, 1), -1); case RNCORR: return Norr (v, prim (num, nc, 1)); case RNCMINUS: return Nsub (v, prim (num, nc, 1)); case RNCLEFTP: v = expr (num, nc, 1); if (nc->curr_tok == RNCRIGHTP) { get_token (num, nc); } else { error (num, nc, " ')' expected"); } case RNCEND: case RNCXOR: case RNCAND: case RNCPLUS: case RNCMOD: case RNCMUL: case RNCDIV: case RNCPRINT: case RNCASSIGN: case RNCRIGHTP: case RNCSHL: case RNCSHR: return v; //default: error (num, nc, "primary expected"); } return v; }
/** * The factor function. * * factor ::= ident | number | "(" expression ")". */ int factor(FILE *input_file, token_type *token) { int error_code = 0; symbol *symbol; int number; // identsym if(*token == identsym) { symbol = get_symbol(input_file, 0); if(!symbol->kind) { return 11; } if(symbol->kind == 1) { error_code = emit(LIT, 0, symbol->val); } else if(symbol->kind == 2) { error_code = emit(LOD, abs(symbol->level - curr_l), symbol->addr); } else { return 21; } if(error_code) return error_code; *token = get_token(input_file); } // is number? else if(*token == numbersym) { number = get_number(input_file); error_code = emit(LIT, 0, number); if(error_code) return error_code; *token = get_token(input_file); if(*token == nulsym) { return 17; } } // (...) else if(*token == lparentsym) { *token = get_token(input_file); error_code = expression(input_file, token); if(error_code) return error_code; if(*token != rparentsym) { return 22; } *token = get_token(input_file); } else if(*token == nulsym) { return 17; } // bad start symbol/not a valid factor else { return 23; } return error_code; }
Error VariantParser::parse_value(Token& token,Variant &value,Stream *p_stream,int &line,String &r_err_str,ResourceParser *p_res_parser) { /* { Error err = get_token(p_stream,token,line,r_err_str); if (err) return err; }*/ if (token.type==TK_CURLY_BRACKET_OPEN) { Dictionary d; Error err = _parse_dictionary(d,p_stream,line,r_err_str,p_res_parser); if (err) return err; value=d; return OK; } else if (token.type==TK_BRACKET_OPEN) { Array a; Error err = _parse_array(a,p_stream,line,r_err_str,p_res_parser); if (err) return err; value=a; return OK; } else if (token.type==TK_IDENTIFIER) { /* VECTOR2, // 5 RECT2, VECTOR3, MATRIX32, PLANE, QUAT, // 10 _AABB, //sorry naming convention fail :( not like it's used often MATRIX3, TRANSFORM, // misc types COLOR, IMAGE, // 15 NODE_PATH, _RID, OBJECT, INPUT_EVENT, DICTIONARY, // 20 ARRAY, // arrays RAW_ARRAY, INT_ARRAY, REAL_ARRAY, STRING_ARRAY, // 25 VECTOR2_ARRAY, VECTOR3_ARRAY, COLOR_ARRAY, VARIANT_MAX */ String id = token.value; if (id=="true") value=true; else if (id=="false") value=false; else if (id=="null" || id=="nil") value=Variant(); else if (id=="Vector2"){ Vector<float> args; Error err = _parse_construct<float>(p_stream,args,line,r_err_str); if (err) return err; if (args.size()!=2) { r_err_str="Expected 2 arguments for constructor"; } value=Vector2(args[0],args[1]); return OK; } else if (id=="Rect2"){ Vector<float> args; Error err = _parse_construct<float>(p_stream,args,line,r_err_str); if (err) return err; if (args.size()!=4) { r_err_str="Expected 4 arguments for constructor"; } value=Rect2(args[0],args[1],args[2],args[3]); return OK; } else if (id=="Vector3"){ Vector<float> args; Error err = _parse_construct<float>(p_stream,args,line,r_err_str); if (err) return err; if (args.size()!=3) { r_err_str="Expected 3 arguments for constructor"; } value=Vector3(args[0],args[1],args[2]); return OK; } else if (id=="Matrix32"){ Vector<float> args; Error err = _parse_construct<float>(p_stream,args,line,r_err_str); if (err) return err; if (args.size()!=6) { r_err_str="Expected 6 arguments for constructor"; } Matrix32 m; m[0]=Vector2(args[0],args[1]); m[1]=Vector2(args[2],args[3]); m[2]=Vector2(args[4],args[5]); value=m; return OK; } else if (id=="Plane") { Vector<float> args; Error err = _parse_construct<float>(p_stream,args,line,r_err_str); if (err) return err; if (args.size()!=4) { r_err_str="Expected 4 arguments for constructor"; } value=Plane(args[0],args[1],args[2],args[3]); return OK; } else if (id=="Quat") { Vector<float> args; Error err = _parse_construct<float>(p_stream,args,line,r_err_str); if (err) return err; if (args.size()!=4) { r_err_str="Expected 4 arguments for constructor"; } value=Quat(args[0],args[1],args[2],args[3]); return OK; } else if (id=="AABB"){ Vector<float> args; Error err = _parse_construct<float>(p_stream,args,line,r_err_str); if (err) return err; if (args.size()!=6) { r_err_str="Expected 6 arguments for constructor"; } value=AABB(Vector3(args[0],args[1],args[2]),Vector3(args[3],args[4],args[5])); return OK; } else if (id=="Matrix3"){ Vector<float> args; Error err = _parse_construct<float>(p_stream,args,line,r_err_str); if (err) return err; if (args.size()!=9) { r_err_str="Expected 9 arguments for constructor"; } value=Matrix3(args[0],args[1],args[2],args[3],args[4],args[5],args[6],args[7],args[8]); return OK; } else if (id=="Transform"){ Vector<float> args; Error err = _parse_construct<float>(p_stream,args,line,r_err_str); if (err) return err; if (args.size()!=12) { r_err_str="Expected 12 arguments for constructor"; } value=Transform(Matrix3(args[0],args[1],args[2],args[3],args[4],args[5],args[6],args[7],args[8]),Vector3(args[9],args[10],args[11])); return OK; } else if (id=="Color") { Vector<float> args; Error err = _parse_construct<float>(p_stream,args,line,r_err_str); if (err) return err; if (args.size()!=4) { r_err_str="Expected 4 arguments for constructor"; } value=Color(args[0],args[1],args[2],args[3]); return OK; } else if (id=="Image") { //:| get_token(p_stream,token,line,r_err_str); if (token.type!=TK_PARENTHESIS_OPEN) { r_err_str="Expected '('"; return ERR_PARSE_ERROR; } get_token(p_stream,token,line,r_err_str); if (token.type==TK_PARENTHESIS_CLOSE) { value=Image(); // just an Image() return OK; } else if (token.type!=TK_NUMBER) { r_err_str="Expected number (width)"; return ERR_PARSE_ERROR; } get_token(p_stream,token,line,r_err_str); int width=token.value; if (token.type!=TK_COMMA) { r_err_str="Expected ','"; return ERR_PARSE_ERROR; } get_token(p_stream,token,line,r_err_str); if (token.type!=TK_NUMBER) { r_err_str="Expected number (height)"; return ERR_PARSE_ERROR; } int height=token.value; get_token(p_stream,token,line,r_err_str); if (token.type!=TK_COMMA) { r_err_str="Expected ','"; return ERR_PARSE_ERROR; } get_token(p_stream,token,line,r_err_str); if (token.type!=TK_NUMBER) { r_err_str="Expected number (mipmaps)"; return ERR_PARSE_ERROR; } int mipmaps=token.value; get_token(p_stream,token,line,r_err_str); if (token.type!=TK_COMMA) { r_err_str="Expected ','"; return ERR_PARSE_ERROR; } get_token(p_stream,token,line,r_err_str); if (token.type!=TK_IDENTIFIER) { r_err_str="Expected identifier (format)"; return ERR_PARSE_ERROR; } String sformat=token.value; Image::Format format; if (sformat=="GRAYSCALE") format=Image::FORMAT_GRAYSCALE; else if (sformat=="INTENSITY") format=Image::FORMAT_INTENSITY; else if (sformat=="GRAYSCALE_ALPHA") format=Image::FORMAT_GRAYSCALE_ALPHA; else if (sformat=="RGB") format=Image::FORMAT_RGB; else if (sformat=="RGBA") format=Image::FORMAT_RGBA; else if (sformat=="INDEXED") format=Image::FORMAT_INDEXED; else if (sformat=="INDEXED_ALPHA") format=Image::FORMAT_INDEXED_ALPHA; else if (sformat=="BC1") format=Image::FORMAT_BC1; else if (sformat=="BC2") format=Image::FORMAT_BC2; else if (sformat=="BC3") format=Image::FORMAT_BC3; else if (sformat=="BC4") format=Image::FORMAT_BC4; else if (sformat=="BC5") format=Image::FORMAT_BC5; else if (sformat=="PVRTC2") format=Image::FORMAT_PVRTC2; else if (sformat=="PVRTC2_ALPHA") format=Image::FORMAT_PVRTC2_ALPHA; else if (sformat=="PVRTC4") format=Image::FORMAT_PVRTC4; else if (sformat=="PVRTC4_ALPHA") format=Image::FORMAT_PVRTC4_ALPHA; else if (sformat=="ATC") format=Image::FORMAT_ATC; else if (sformat=="ATC_ALPHA_EXPLICIT") format=Image::FORMAT_ATC_ALPHA_EXPLICIT; else if (sformat=="ATC_ALPHA_INTERPOLATED") format=Image::FORMAT_ATC_ALPHA_INTERPOLATED; else if (sformat=="CUSTOM") format=Image::FORMAT_CUSTOM; else { r_err_str="Invalid image format: '"+sformat+"'"; return ERR_PARSE_ERROR; }; int len = Image::get_image_data_size(width,height,format,mipmaps); DVector<uint8_t> buffer; buffer.resize(len); if (buffer.size()!=len) { r_err_str="Couldn't allocate image buffer of size: "+itos(len); } { DVector<uint8_t>::Write w=buffer.write(); for(int i=0;i<len;i++) { get_token(p_stream,token,line,r_err_str); if (token.type!=TK_COMMA) { r_err_str="Expected ','"; return ERR_PARSE_ERROR; } get_token(p_stream,token,line,r_err_str); if (token.type!=TK_NUMBER) { r_err_str="Expected number"; return ERR_PARSE_ERROR; } w[i]=int(token.value); } } Image img(width,height,mipmaps,format,buffer); value=img; return OK; } else if (id=="NodePath") { get_token(p_stream,token,line,r_err_str); if (token.type!=TK_PARENTHESIS_OPEN) { r_err_str="Expected '('"; return ERR_PARSE_ERROR; } get_token(p_stream,token,line,r_err_str); if (token.type!=TK_STRING) { r_err_str="Expected string as argument for NodePath()"; return ERR_PARSE_ERROR; } value=NodePath(String(token.value)); get_token(p_stream,token,line,r_err_str); if (token.type!=TK_PARENTHESIS_CLOSE) { r_err_str="Expected ')'"; return ERR_PARSE_ERROR; } } else if (id=="RID") { get_token(p_stream,token,line,r_err_str); if (token.type!=TK_PARENTHESIS_OPEN) { r_err_str="Expected '('"; return ERR_PARSE_ERROR; } get_token(p_stream,token,line,r_err_str); if (token.type!=TK_NUMBER) { r_err_str="Expected number as argument"; return ERR_PARSE_ERROR; } value=token.value; get_token(p_stream,token,line,r_err_str); if (token.type!=TK_PARENTHESIS_CLOSE) { r_err_str="Expected ')'"; return ERR_PARSE_ERROR; } return OK; } else if (id=="Resource" || id=="SubResource" || id=="ExtResource") { get_token(p_stream,token,line,r_err_str); if (token.type!=TK_PARENTHESIS_OPEN) { r_err_str="Expected '('"; return ERR_PARSE_ERROR; } if (p_res_parser && id=="Resource" && p_res_parser->func){ RES res; Error err = p_res_parser->func(p_res_parser->userdata,p_stream,res,line,r_err_str); if (err) return err; value=res; return OK; } else if (p_res_parser && id=="ExtResource" && p_res_parser->ext_func){ RES res; Error err = p_res_parser->ext_func(p_res_parser->userdata,p_stream,res,line,r_err_str); if (err) return err; value=res; return OK; } else if (p_res_parser && id=="SubResource" && p_res_parser->sub_func){ RES res; Error err = p_res_parser->sub_func(p_res_parser->userdata,p_stream,res,line,r_err_str); if (err) return err; value=res; return OK; } else { get_token(p_stream,token,line,r_err_str); if (token.type==TK_STRING) { String path=token.value; RES res = ResourceLoader::load(path); if (res.is_null()) { r_err_str="Can't load resource at path: '"+path+"'."; return ERR_PARSE_ERROR; } get_token(p_stream,token,line,r_err_str); if (token.type!=TK_PARENTHESIS_CLOSE) { r_err_str="Expected ')'"; return ERR_PARSE_ERROR; } value=res; return OK; } else { r_err_str="Expected string as argument for Resource()."; return ERR_PARSE_ERROR; } } return OK; } else if (id=="InputEvent") { get_token(p_stream,token,line,r_err_str); if (token.type!=TK_PARENTHESIS_OPEN) { r_err_str="Expected '('"; return ERR_PARSE_ERROR; } get_token(p_stream,token,line,r_err_str); if (token.type!=TK_IDENTIFIER) { r_err_str="Expected identifier"; return ERR_PARSE_ERROR; } String id = token.value; InputEvent ie; if (id=="KEY") { get_token(p_stream,token,line,r_err_str); if (token.type!=TK_COMMA) { r_err_str="Expected ','"; return ERR_PARSE_ERROR; } ie.type=InputEvent::KEY; get_token(p_stream,token,line,r_err_str); if (token.type==TK_IDENTIFIER) { String name=token.value; ie.key.scancode=find_keycode(name); } else if (token.type==TK_NUMBER) { ie.key.scancode=token.value; } else { r_err_str="Expected string or integer for keycode"; return ERR_PARSE_ERROR; } get_token(p_stream,token,line,r_err_str); if (token.type==TK_COMMA) { get_token(p_stream,token,line,r_err_str); if (token.type!=TK_IDENTIFIER) { r_err_str="Expected identifier with modifier flas"; return ERR_PARSE_ERROR; } String mods=token.value; if (mods.findn("C")!=-1) ie.key.mod.control=true; if (mods.findn("A")!=-1) ie.key.mod.alt=true; if (mods.findn("S")!=-1) ie.key.mod.shift=true; if (mods.findn("M")!=-1) ie.key.mod.meta=true; get_token(p_stream,token,line,r_err_str); if (token.type!=TK_PARENTHESIS_CLOSE) { r_err_str="Expected ')'"; return ERR_PARSE_ERROR; } } else if (token.type!=TK_PARENTHESIS_CLOSE) { r_err_str="Expected ')' or modifier flags."; return ERR_PARSE_ERROR; } } else if (id=="MBUTTON") { get_token(p_stream,token,line,r_err_str); if (token.type!=TK_COMMA) { r_err_str="Expected ','"; return ERR_PARSE_ERROR; } ie.type=InputEvent::MOUSE_BUTTON; get_token(p_stream,token,line,r_err_str); if (token.type!=TK_NUMBER) { r_err_str="Expected button index"; return ERR_PARSE_ERROR; } ie.mouse_button.button_index = token.value; get_token(p_stream,token,line,r_err_str); if (token.type!=TK_PARENTHESIS_CLOSE) { r_err_str="Expected ')'"; return ERR_PARSE_ERROR; } } else if (id=="JBUTTON") { get_token(p_stream,token,line,r_err_str); if (token.type!=TK_COMMA) { r_err_str="Expected ','"; return ERR_PARSE_ERROR; } ie.type=InputEvent::JOYSTICK_BUTTON; get_token(p_stream,token,line,r_err_str); if (token.type!=TK_NUMBER) { r_err_str="Expected button index"; return ERR_PARSE_ERROR; } ie.joy_button.button_index = token.value; get_token(p_stream,token,line,r_err_str); if (token.type!=TK_PARENTHESIS_CLOSE) { r_err_str="Expected ')'"; return ERR_PARSE_ERROR; } } else if (id=="JAXIS") { get_token(p_stream,token,line,r_err_str); if (token.type!=TK_COMMA) { r_err_str="Expected ','"; return ERR_PARSE_ERROR; } ie.type=InputEvent::JOYSTICK_MOTION; get_token(p_stream,token,line,r_err_str); if (token.type!=TK_NUMBER) { r_err_str="Expected axis index"; return ERR_PARSE_ERROR; } ie.joy_motion.axis = token.value; get_token(p_stream,token,line,r_err_str); if (token.type!=TK_COMMA) { r_err_str="Expected ',' after axis index"; return ERR_PARSE_ERROR; } get_token(p_stream,token,line,r_err_str); if (token.type!=TK_NUMBER) { r_err_str="Expected axis sign"; return ERR_PARSE_ERROR; } ie.joy_motion.axis_value = token.value; get_token(p_stream,token,line,r_err_str); if (token.type!=TK_PARENTHESIS_CLOSE) { r_err_str="Expected ')' for jaxis"; return ERR_PARSE_ERROR; } } else { r_err_str="Invalid input event type."; return ERR_PARSE_ERROR; } value=ie; return OK; } else if (id=="ByteArray") { Vector<uint8_t> args; Error err = _parse_construct<uint8_t>(p_stream,args,line,r_err_str); if (err) return err; DVector<uint8_t> arr; { int len=args.size(); arr.resize(len); DVector<uint8_t>::Write w = arr.write(); for(int i=0;i<len;i++) { w[i]=args[i]; } } value=arr; return OK; } else if (id=="IntArray") { Vector<int32_t> args; Error err = _parse_construct<int32_t>(p_stream,args,line,r_err_str); if (err) return err; DVector<int32_t> arr; { int len=args.size(); arr.resize(len); DVector<int32_t>::Write w = arr.write(); for(int i=0;i<len;i++) { w[i]=int(args[i]); } } value=arr; return OK; } else if (id=="FloatArray") { Vector<float> args; Error err = _parse_construct<float>(p_stream,args,line,r_err_str); if (err) return err; DVector<float> arr; { int len=args.size(); arr.resize(len); DVector<float>::Write w = arr.write(); for(int i=0;i<len;i++) { w[i]=args[i]; } } value=arr; return OK; } else if (id=="StringArray") { get_token(p_stream,token,line,r_err_str); if (token.type!=TK_PARENTHESIS_OPEN) { r_err_str="Expected '('"; return ERR_PARSE_ERROR; } Vector<String> cs; bool first=true; while(true) { if (!first) { get_token(p_stream,token,line,r_err_str); if (token.type==TK_COMMA) { //do none } else if (token.type==TK_PARENTHESIS_CLOSE) { break; } else { r_err_str="Expected ',' or ')'"; return ERR_PARSE_ERROR; } } get_token(p_stream,token,line,r_err_str); if (token.type!=TK_STRING) { r_err_str="Expected string"; return ERR_PARSE_ERROR; } first=false; cs.push_back(token.value); } DVector<String> arr; { int len=cs.size(); arr.resize(len); DVector<String>::Write w = arr.write(); for(int i=0;i<len;i++) { w[i]=cs[i]; } } value=arr; return OK; } else if (id=="Vector2Array") { Vector<float> args; Error err = _parse_construct<float>(p_stream,args,line,r_err_str); if (err) return err; DVector<Vector2> arr; { int len=args.size()/2; arr.resize(len); DVector<Vector2>::Write w = arr.write(); for(int i=0;i<len;i++) { w[i]=Vector2(args[i*2+0],args[i*2+1]); } } value=arr; return OK; } else if (id=="Vector3Array") { Vector<float> args; Error err = _parse_construct<float>(p_stream,args,line,r_err_str); if (err) return err; DVector<Vector3> arr; { int len=args.size()/3; arr.resize(len); DVector<Vector3>::Write w = arr.write(); for(int i=0;i<len;i++) { w[i]=Vector3(args[i*3+0],args[i*3+1],args[i*3+2]); } } value=arr; return OK; } else if (id=="ColorArray") { Vector<float> args; Error err = _parse_construct<float>(p_stream,args,line,r_err_str); if (err) return err; DVector<Color> arr; { int len=args.size()/4; arr.resize(len); DVector<Color>::Write w = arr.write(); for(int i=0;i<len;i++) { w[i]=Color(args[i*4+0],args[i*4+1],args[i*4+2],args[i*4+3]); } } value=arr; return OK; } else if (id=="key") { // compatibility with engine.cfg Vector<String> params; Error err = _parse_enginecfg(p_stream,params,line,r_err_str); if (err) return err; ERR_FAIL_COND_V(params.size()!=1 && params.size()!=2,ERR_PARSE_ERROR); int scode=0; if (params[0].is_numeric()) { scode=params[0].to_int(); if (scode < 10) { scode=KEY_0+scode; } } else scode=find_keycode(params[0]); InputEvent ie; ie.type=InputEvent::KEY; ie.key.scancode=scode; if (params.size()==2) { String mods=params[1]; if (mods.findn("C")!=-1) ie.key.mod.control=true; if (mods.findn("A")!=-1) ie.key.mod.alt=true; if (mods.findn("S")!=-1) ie.key.mod.shift=true; if (mods.findn("M")!=-1) ie.key.mod.meta=true; } value=ie; return OK; } else if (id=="mbutton") { // compatibility with engine.cfg Vector<String> params; Error err = _parse_enginecfg(p_stream,params,line,r_err_str); if (err) return err; ERR_FAIL_COND_V(params.size()!=2,ERR_PARSE_ERROR); InputEvent ie; ie.type=InputEvent::MOUSE_BUTTON; ie.device=params[0].to_int(); ie.mouse_button.button_index=params[1].to_int(); value=ie; return OK; } else if (id=="jbutton") { // compatibility with engine.cfg Vector<String> params; Error err = _parse_enginecfg(p_stream,params,line,r_err_str); if (err) return err; ERR_FAIL_COND_V(params.size()!=2,ERR_PARSE_ERROR); InputEvent ie; ie.type=InputEvent::JOYSTICK_BUTTON; ie.device=params[0].to_int(); ie.joy_button.button_index=params[1].to_int(); value=ie; return OK; } else if (id=="jaxis") { // compatibility with engine.cfg Vector<String> params; Error err = _parse_enginecfg(p_stream,params,line,r_err_str); if (err) return err; ERR_FAIL_COND_V(params.size()!=2,ERR_PARSE_ERROR); InputEvent ie; ie.type=InputEvent::JOYSTICK_MOTION; ie.device=params[0].to_int(); int axis=params[1].to_int(); ie.joy_motion.axis=axis>>1; ie.joy_motion.axis_value=axis&1?1:-1; value= ie; return OK; } else if (id=="img") { // compatibility with engine.cfg
void get_name( void ) { get_token(); if( flag ) fixate_literal_string(); else *--sp = 0; /* placeholder for string pointer on failure */ }
int command_parse_set(void) { /* commands could look like the following: * set ignorecase * set noignorecase * set focus=gdb * set tabstop=8 */ int rv = 1; switch ((rv = yylex())) { case EOL:{ /* TODO: Print out all the variables that have been set. */ } break; case IDENTIFIER:{ int boolean = 1; const char *value = NULL; const char *token = get_token(); int length = strlen(token); struct ConfigVariable *variable = NULL; if (length > 2 && token[0] == 'n' && token[1] == 'o') { value = token + 2; boolean = 0; } else { value = token; } if ((variable = get_variable(value)) != NULL) { rv = 0; if (boolean == 0 && variable->type != CONFIG_TYPE_BOOL) { /* this is an error, you cant' do: * set notabstop */ rv = 1; } switch (variable->type) { case CONFIG_TYPE_BOOL: *(int *) (variable->data) = boolean; break; case CONFIG_TYPE_INT:{ if (yylex() == '=' && yylex() == NUMBER) { int data = strtol(get_token(), NULL, 10); *(int *) (variable->data) = data; } else { rv = 1; } } break; case CONFIG_TYPE_STRING:{ if (yylex() == '=' && (rv = yylex(), rv == STRING || rv == IDENTIFIER)) { /* BAM! comma operator */ char *data = (char *) get_token(); if (rv == STRING) { /* get rid of quotes */ data = data + 1; data[strlen(data) - 1] = '\0'; } if (variable->data) { free(variable->data); } variable->data = strdup(data); } else { rv = 1; } } break; case CONFIG_TYPE_FUNC_VOID:{ int (*functor) (void) = (int (*)(void)) variable->data; if (functor) { rv = functor(); } else { rv = 1; } } break; case CONFIG_TYPE_FUNC_BOOL:{ int (*functor) (int) = (int (*)(int)) variable->data; if (functor) { rv = functor(boolean); } else { rv = 1; } } break; case CONFIG_TYPE_FUNC_INT:{ int (*functor) (int) = (int (*)(int)) variable->data; if (yylex() == '=' && yylex() == NUMBER) { int data = strtol(get_token(), NULL, 10); if (functor) { rv = functor(data); } else { rv = 1; } } else { rv = 1; } } break; case CONFIG_TYPE_FUNC_STRING:{ int (*functor) (const char *) = (int (*)(const char *)) variable->data; if (yylex() == '=' && (rv = yylex(), rv == STRING || rv == IDENTIFIER)) { /* BAM! comma operator */ char *data = (char *) get_token(); if (rv == STRING) { /* get rid of quotes */ data = data + 1; data[strlen(data) - 1] = '\0'; } if (functor) { rv = functor(data); } else { rv = 1; } } else { rv = 1; } } break; default: rv = 1; break; } /* Tell callback function this variable has changed. */ variable_changed_cb(variable); } } break; default: break; } return rv; }
int command_parse_string(const char *buffer) { extern YY_BUFFER_STATE yy_scan_string(const char *yy_str); extern void yy_delete_buffer(YY_BUFFER_STATE state); int rv = 1; YY_BUFFER_STATE state = yy_scan_string((char *) buffer); switch (yylex()) { case SET: /* get the next token */ rv = command_parse_set(); break; case UNSET: case BIND: case MACRO: /* ignore this stuff for now. */ rv = 1; break; case NUMBER:{ const char *number = get_token(); if (number[0] == '+') { source_vscroll(if_get_sview(), atoi(number + 1)); rv = 0; } else if (number[0] == '-') { source_vscroll(if_get_sview(), -atoi(number + 1)); rv = 0; } else { source_set_sel_line(if_get_sview(), atoi(number)); rv = 0; } if_draw(); } break; case IDENTIFIER:{ COMMANDS *command = get_command(get_token()); if (command) { command->action(command->param); rv = 0; } else { rv = 1; } } break; case EOL: /* basically just an empty line, don't do nothin. */ rv = 0; break; default: rv = 1; break; } yy_delete_buffer(state); return rv; }
static void test_stp_main(int argc, char *argv[]) { struct test_case *tc; FILE *input_file; int i; vlog_set_pattern(VLF_CONSOLE, "%c|%p|%m"); vlog_set_levels(NULL, VLF_SYSLOG, VLL_OFF); if (argc != 2) { ovs_fatal(0, "usage: test-stp INPUT.STP\n"); } file_name = argv[1]; input_file = fopen(file_name, "r"); if (!input_file) { ovs_fatal(errno, "error opening \"%s\"", file_name); } tc = new_test_case(); for (i = 0; i < 26; i++) { char name[2]; name[0] = 'a' + i; name[1] = '\0'; new_lan(tc, name); } for (line_number = 1; fgets(line, sizeof line, input_file); line_number++) { char *newline, *hash; newline = strchr(line, '\n'); if (newline) { *newline = '\0'; } hash = strchr(line, '#'); if (hash) { *hash = '\0'; } pos = line; if (!get_token()) { continue; } if (match("bridge")) { struct bridge *bridge; int bridge_no, port_no; bridge_no = must_get_int(); if (bridge_no < tc->n_bridges) { bridge = tc->bridges[bridge_no]; } else if (bridge_no == tc->n_bridges) { bridge = new_bridge(tc, must_get_int()); } else { err("bridges must be numbered consecutively from 0"); } if (match("^")) { stp_set_bridge_priority(bridge->stp, must_get_int()); } if (match("=")) { for (port_no = 0; port_no < STP_MAX_PORTS; port_no++) { struct stp_port *p = stp_get_port(bridge->stp, port_no); if (!token || match("X")) { stp_port_disable(p); } else if (match("_")) { /* Nothing to do. */ } else { struct lan *lan; int path_cost; if (!strcmp(token, "0")) { lan = NULL; } else if (strlen(token) == 1 && islower((unsigned char)*token)) { lan = tc->lans[*token - 'a']; } else { err("%s is not a valid LAN name " "(0 or a lowercase letter)", token); } get_token(); path_cost = match(":") ? must_get_int() : 10; if (port_no < bridge->n_ports) { stp_port_set_path_cost(p, path_cost); stp_port_enable(p); reconnect_port(bridge, port_no, lan); } else if (port_no == bridge->n_ports) { new_port(bridge, lan, path_cost); } else { err("ports must be numbered consecutively"); } if (match("^")) { stp_port_set_priority(p, must_get_int()); } } } } } else if (match("run")) { simulate(tc, must_get_int()); } else if (match("dump")) { dump(tc); } else if (match("tree")) { tree(tc); } else if (match("check")) { struct bridge *b; struct stp *stp; int bridge_no, port_no; bridge_no = must_get_int(); if (bridge_no >= tc->n_bridges) { err("no bridge numbered %d", bridge_no); } b = tc->bridges[bridge_no]; stp = b->stp; must_match("="); if (match("rootid")) { uint64_t rootid; must_match(":"); rootid = must_get_int(); if (match("^")) { rootid |= (uint64_t) must_get_int() << 48; } else { rootid |= UINT64_C(0x8000) << 48; } if (stp_get_designated_root(stp) != rootid) { warn("%s: root %"PRIx64", not %"PRIx64, stp_get_name(stp), stp_get_designated_root(stp), rootid); } } if (match("root")) { if (stp_get_root_path_cost(stp)) { warn("%s: root path cost of root is %u but should be 0", stp_get_name(stp), stp_get_root_path_cost(stp)); } if (!stp_is_root_bridge(stp)) { warn("%s: root is %"PRIx64", not %"PRIx64, stp_get_name(stp), stp_get_designated_root(stp), stp_get_bridge_id(stp)); } for (port_no = 0; port_no < b->n_ports; port_no++) { struct stp_port *p = stp_get_port(stp, port_no); enum stp_state state = stp_port_get_state(p); if (!(state & (STP_DISABLED | STP_FORWARDING))) { warn("%s: root port %d in state %s", stp_get_name(b->stp), port_no, stp_state_name(state)); } } } else { for (port_no = 0; port_no < STP_MAX_PORTS; port_no++) { struct stp_port *p = stp_get_port(stp, port_no); enum stp_state state; if (token == NULL || match("D")) { state = STP_DISABLED; } else if (match("B")) { state = STP_BLOCKING; } else if (match("Li")) { state = STP_LISTENING; } else if (match("Le")) { state = STP_LEARNING; } else if (match("F")) { state = STP_FORWARDING; } else if (match("_")) { continue; } else { err("unknown port state %s", token); } if (stp_port_get_state(p) != state) { warn("%s port %d: state is %s but should be %s", stp_get_name(stp), port_no, stp_state_name(stp_port_get_state(p)), stp_state_name(state)); } if (state == STP_FORWARDING) { struct stp_port *root_port = stp_get_root_port(stp); if (match(":")) { int root_path_cost = must_get_int(); if (p != root_port) { warn("%s: port %d is not the root port", stp_get_name(stp), port_no); if (!root_port) { warn("%s: (there is no root port)", stp_get_name(stp)); } else { warn("%s: (port %d is the root port)", stp_get_name(stp), stp_port_no(root_port)); } } else if (root_path_cost != stp_get_root_path_cost(stp)) { warn("%s: root path cost is %u, should be %d", stp_get_name(stp), stp_get_root_path_cost(stp), root_path_cost); } } else if (p == root_port) { warn("%s: port %d is the root port but " "not expected to be", stp_get_name(stp), port_no); } } } } if (n_warnings) { exit(EXIT_FAILURE); } } if (get_token()) { err("trailing garbage on line"); } } free(token); for (i = 0; i < tc->n_lans; i++) { struct lan *lan = tc->lans[i]; free(CONST_CAST(char *, lan->name)); free(lan); } for (i = 0; i < tc->n_bridges; i++) { struct bridge *bridge = tc->bridges[i]; stp_unref(bridge->stp); free(bridge); } free(tc); fclose(input_file); }