HRESULT CMixerControl::LoadControl(XMLEl* pLibrary) { XMLEl* pThis = 0; CCString sValues; PCWSTR wszCurrent = 0;// Current place in the sValues string. WCHAR* wszToken = 0;// The token. To avoid a buffer-overrun we make this string the same size as sValues. int i = 0;// Current index we're workin on. MIXERCONTROLDETAILS_BOOLEAN* pBoolean = (MIXERCONTROLDETAILS_BOOLEAN*)m_pRaw; MIXERCONTROLDETAILS_UNSIGNED* pUnsigned = (MIXERCONTROLDETAILS_UNSIGNED*)m_pRaw; MIXERCONTROLDETAILS_SIGNED* pSigned = (MIXERCONTROLDETAILS_SIGNED*)m_pRaw; if(FAILED(GetNode(0, pLibrary, &pThis, FALSE))) { return MIX_E_XMLERR; } // Here, we concern ourself with the value attribute. if(FAILED(XMLGetAttribute(pThis, CCString(L"Values"), &sValues))) { SAFE_RELEASE(pThis); return MIX_E_XMLERR; } // Let's go case-insensitive. sValues.upr(); // If we're doing raw binary data, we can skip all the parsing. if(m_DataType == MIXDT_CUSTOM) { sValues.ToBinary(m_pRaw, m_mc.Metrics.cbCustomData); SAFE_RELEASE(pThis); return S_OK; } // Set up our looping stuff. wszCurrent = sValues; wszToken = (WCHAR*)malloc((wcslen(wszCurrent)+1)*sizeof(WCHAR)); while(1) { wszCurrent = NextToken(wszToken, wszCurrent); if(m_DataType == MIXDT_BOOLEAN) { // Now wszToken is the current token. if(wcsicmp(wszToken, L"TRUE") == 0) { pBoolean[i].fValue = TRUE; } else if(wcsicmp(wszToken, L"FALSE") == 0) { pBoolean[i].fValue = FALSE; } } else if(m_DataType == MIXDT_SIGNED) { pSigned[i].lValue = wcstol(wszToken, 0, 10); } else if(m_DataType == MIXDT_UNSIGNED) { pUnsigned[i].dwValue = wcstoul(wszToken, 0, 10); } i++; if(i >= m_nRawItems) break; if(wszCurrent == 0) break; } free(wszToken); wszToken = 0; SAFE_RELEASE(pThis); // Now commit the buffer. _CommitRawBuffer(); return S_OK; }
/* * funcbody starts with the current symbol being either * the first parameter id or the begin for the local * block. If begin is the current symbol then funcbody * assumes that the function has no parameters. */ int ParseFunction(SYM *sp) { int i; SYM *sp1, *sp2, *pl, *osp; Statement *stmt; int nump; __int16 *ta; int nn; std::string name; dfs.puts("<ParseFunction>\n"); isFuncBody = true; if (sp==NULL) { fatal("Compiler error: ParseFunction: SYM is NULL\r\n"); } dfs.printf("***********************************\n"); dfs.printf("***********************************\n"); dfs.printf("***********************************\n"); if (sp->parent) dfs.printf("Parent: %s\n", (char *)sp->GetParentPtr()->name->c_str()); dfs.printf("Parsing function: %s\n", (char *)sp->name->c_str()); dfs.printf("***********************************\n"); dfs.printf("***********************************\n"); dfs.printf("***********************************\n"); sp->stkname = stkname; if (verbose) printf("Parsing function: %s\r\n", (char *)sp->name->c_str()); nump = nparms; iflevel = 0; // There could be unnamed parameters in a function prototype. dfs.printf("A"); // declare parameters // Building a parameter list here allows both styles of parameter // declarations. the original 'C' style is parsed here. Originally the // parameter types appeared as list after the parenthesis and before the // function body. sp->BuildParameterList(&nump); dfs.printf("B"); sp->mangledName = sp->BuildSignature(1); // build against parameters // If the symbol has a parent then it must be a class // method. Search the parent table(s) for matching // signatures. osp = sp; name = *sp->name; if (sp->parent) { SYM *sp2; dfs.printf("PArent Class:%s|",(char *)sp->GetParentPtr()->name->c_str()); sp2 = sp->GetParentPtr()->Find(name); if (sp2) { dfs.printf("Found at least inexact match"); sp2 = sp->FindExactMatch(TABLE::matchno); } if (sp2 == nullptr) error(ERR_METHOD_NOTFOUND); else sp = sp2; sp->PrintParameterTypes(); } else { if (gsyms[0].Find(name)) { sp = TABLE::match[TABLE::matchno-1]; } } dfs.printf("C"); if (sp != osp) { dfs.printf("ParseFunction: sp changed\n"); osp->params.CopyTo(&sp->params); osp->proto.CopyTo(&sp->proto); sp->derivitives = osp->derivitives; sp->mangledName = osp->mangledName; // Should free osp here. It's not needed anymore } if (lastst == closepa) { NextToken(); } dfs.printf("D"); if (sp->tp->type == bt_pointer) { if (lastst==assign) { doinit(sp); } sp->IsNocall = isNocall; sp->IsPascal = isPascal; sp->IsKernel = isKernel; sp->IsInterrupt = isInterrupt; sp->IsTask = isTask; sp->NumParms = nump; sp->IsVirtual = isVirtual; isPascal = FALSE; isKernel = FALSE; isOscall = FALSE; isInterrupt = FALSE; isTask = FALSE; isNocall = FALSE; // ReleaseLocalMemory(); /* release local symbols (parameters)*/ return 1; } dfs.printf("E"); if (lastst == semicolon) { // Function prototype dfs.printf("e"); sp->IsPrototype = 1; sp->IsNocall = isNocall; sp->IsPascal = isPascal; sp->IsKernel = isKernel; sp->IsInterrupt = isInterrupt; sp->IsTask = isTask; sp->IsVirtual = isVirtual; sp->NumParms = nump; sp->params.MoveTo(&sp->proto); isPascal = FALSE; isKernel = FALSE; isOscall = FALSE; isInterrupt = FALSE; isTask = FALSE; isNocall = FALSE; // ReleaseLocalMemory(); /* release local symbols (parameters)*/ goto j1; } else if(lastst != begin) { dfs.printf("F"); // NextToken(); ParameterDeclaration::Parse(2); // for old-style parameter list //needpunc(closepa); if (lastst==semicolon) { sp->IsPrototype = 1; sp->IsNocall = isNocall; sp->IsPascal = isPascal; sp->IsKernel = isKernel; sp->IsInterrupt = isInterrupt; sp->IsTask = isTask; sp->IsVirtual = isVirtual; sp->NumParms = nump; isPascal = FALSE; isKernel = FALSE; isOscall = FALSE; isInterrupt = FALSE; isTask = FALSE; isNocall = FALSE; // ReleaseLocalMemory(); /* release local symbols (parameters)*/ } // Check for end of function parameter list. else if (funcdecl==2 && lastst==closepa) { ; } else { sp->IsNocall = isNocall; sp->IsPascal = isPascal; sp->IsKernel = isKernel; sp->IsInterrupt = isInterrupt; sp->IsTask = isTask; sp->IsVirtual = isVirtual; isPascal = FALSE; isKernel = FALSE; isOscall = FALSE; isInterrupt = FALSE; isTask = FALSE; isNocall = FALSE; sp->NumParms = nump; stmt = ParseFunctionBody(sp); funcbottom(stmt); } } // error(ERR_BLOCK); else { dfs.printf("G"); sp->IsNocall = isNocall; sp->IsPascal = isPascal; sp->IsKernel = isKernel; sp->IsInterrupt = isInterrupt; sp->IsTask = isTask; sp->IsVirtual = isVirtual; isPascal = FALSE; isKernel = FALSE; isOscall = FALSE; isInterrupt = FALSE; isTask = FALSE; isNocall = FALSE; sp->NumParms = nump; stmt = ParseFunctionBody(sp); funcbottom(stmt); } j1: dfs.printf("F"); dfs.puts("</ParseFunction>\n"); return 0; }
static void ForStatement (void) /* Handle a 'for' statement */ { ExprDesc lval1; ExprDesc lval3; int HaveIncExpr; CodeMark IncExprStart; CodeMark IncExprEnd; int PendingToken; /* Get several local labels needed later */ unsigned TestLabel = GetLocalLabel (); unsigned BreakLabel = GetLocalLabel (); unsigned IncLabel = GetLocalLabel (); unsigned BodyLabel = GetLocalLabel (); /* Skip the FOR token */ NextToken (); /* Add the loop to the loop stack. A continue jumps to the start of the * the increment condition. */ AddLoop (BreakLabel, IncLabel); /* Skip the opening paren */ ConsumeLParen (); /* Parse the initializer expression */ if (CurTok.Tok != TOK_SEMI) { Expression0 (&lval1); } ConsumeSemi (); /* Label for the test expressions */ g_defcodelabel (TestLabel); /* Parse the test expression */ if (CurTok.Tok != TOK_SEMI) { Test (BodyLabel, 1); g_jump (BreakLabel); } else { g_jump (BodyLabel); } ConsumeSemi (); /* Remember the start of the increment expression */ GetCodePos (&IncExprStart); /* Label for the increment expression */ g_defcodelabel (IncLabel); /* Parse the increment expression */ HaveIncExpr = (CurTok.Tok != TOK_RPAREN); if (HaveIncExpr) { Expression0 (&lval3); } /* Jump to the test */ g_jump (TestLabel); /* Remember the end of the increment expression */ GetCodePos (&IncExprEnd); /* Skip the closing paren */ ConsumeRParen (); /* Loop body */ g_defcodelabel (BodyLabel); Statement (&PendingToken); /* If we had an increment expression, move the code to the bottom of * the loop. In this case we don't need to jump there at the end of * the loop body. */ if (HaveIncExpr) { CodeMark Here; GetCodePos (&Here); MoveCode (&IncExprStart, &IncExprEnd, &Here); } else { /* Jump back to the increment expression */ g_jump (IncLabel); } /* Skip a pending token if we have one */ SkipPending (PendingToken); /* Declare the break label */ g_defcodelabel (BreakLabel); /* Remove the loop from the loop stack */ DelLoop (); }
/* * funcbody starts with the current symbol being either * the first parameter id or the begin for the local * block. If begin is the current symbol then funcbody * assumes that the function has no parameters. */ int ParseFunction(SYM *sp) { int poffset, i; int oldglobal; SYM *sp1, *sp2; Statement *stmt; if (sp==NULL) { fatal("Compiler error: ParseFunction: SYM is NULL\r\n"); } sp->stkname = stkname; if (verbose) printf("Parsing function: %s\r\n", sp->name); oldglobal = global_flag; global_flag = 0; poffset = 24; /* size of return block */ nparms = 0; iflevel = 0; // There could be unnamed parameters in a function prototype. if(lastst == id || 1) { /* declare parameters */ //while(lastst == id) { // names[nparms++] = litlate(lastid); // NextToken(); // if( lastst == comma) // NextToken(); // else // break; // } //needpunc(closepa); // dodecl(sc_member); /* declare parameters */ sp->parms = (SYM *)NULL; ParseParameterDeclarations(1); for(i = 0;i < nparms;++i) { if( (sp1 = search(names[i],&lsyms)) == NULL) sp1 = makeint(names[i]); //if( sp1->tp->size < 8 ) //{ // sp1->value.i = poffset;// + (8 - sp1->tp->size); // poffset += 8; //} //else //{ // sp1->value.i = poffset; // poffset += sp1->tp->size; //} sp1->value.i = poffset; // Check for aggregate types passed as parameters. Structs // and unions use the type size. // if (sp1->tp->type==bt_struct || sp1->tp->type==bt_union) { poffset += round8(sp1->tp->size); if (round8(sp1->tp->size) > 8) sp->IsLeaf = FALSE; // } // else // poffset += 8; //sp1->value.i = poffset; //poffset += 8; sp1->storage_class = sc_auto; sp1->nextparm = (SYM *)NULL; // record parameter list if (sp->parms == (SYM *)NULL) { sp->parms = sp1; } else { sp1->nextparm = sp->parms; sp->parms = sp1; } } // Process extra hidden parameter if (sp->tp->btp->type==bt_struct || sp->tp->btp->type==bt_union) { sp1 = makeint(litlate("_pHiddenStructPtr")); sp1->value.i = poffset; poffset += 8; sp1->storage_class = sc_auto; sp1->nextparm = (SYM *)NULL; // record parameter list if (sp->parms == (SYM *)NULL) { sp->parms = sp1; } else { sp1->nextparm = sp->parms; sp->parms = sp1; } nparms++; } } if (lastst == closepa) NextToken(); if (sp->tp->type == bt_pointer) { if (lastst==assign) { doinit(sp); } sp->IsNocall = isNocall; sp->IsPascal = isPascal; sp->IsKernel = isKernel; sp->IsInterrupt = isInterrupt; sp->IsTask = isTask; sp->NumParms = nparms; isPascal = FALSE; isKernel = FALSE; isOscall = FALSE; isInterrupt = FALSE; isTask = FALSE; isNocall = FALSE; ReleaseLocalMemory(); /* release local symbols (parameters)*/ global_flag = oldglobal; return 1; } if (lastst == semicolon) { // Function prototype sp->IsPrototype = 1; sp->IsNocall = isNocall; sp->IsPascal = isPascal; sp->IsKernel = isKernel; sp->IsInterrupt = isInterrupt; sp->IsTask = isTask; sp->NumParms = nparms; isPascal = FALSE; isKernel = FALSE; isOscall = FALSE; isInterrupt = FALSE; isTask = FALSE; isNocall = FALSE; ReleaseLocalMemory(); /* release local symbols (parameters)*/ goto j1; } else if(lastst != begin) { // NextToken(); ParseParameterDeclarations(2); // for old-style parameter list //needpunc(closepa); if (lastst==semicolon) { sp->IsPrototype = 1; sp->IsNocall = isNocall; sp->IsPascal = isPascal; sp->IsKernel = isKernel; sp->IsInterrupt = isInterrupt; sp->IsTask = isTask; sp->NumParms = nparms; isPascal = FALSE; isKernel = FALSE; isOscall = FALSE; isInterrupt = FALSE; isTask = FALSE; isNocall = FALSE; ReleaseLocalMemory(); /* release local symbols (parameters)*/ } // Check for end of function parameter list. else if (funcdecl==2 && lastst==closepa) { ; } else { sp->IsNocall = isNocall; sp->IsPascal = isPascal; sp->IsKernel = isKernel; sp->IsInterrupt = isInterrupt; sp->IsTask = isTask; isPascal = FALSE; isKernel = FALSE; isOscall = FALSE; isInterrupt = FALSE; isTask = FALSE; isNocall = FALSE; sp->NumParms = nparms; stmt = ParseFunctionBody(sp); funcbottom(stmt); } } // error(ERR_BLOCK); else { sp->IsNocall = isNocall; sp->IsPascal = isPascal; sp->IsKernel = isKernel; sp->IsInterrupt = isInterrupt; sp->IsTask = isTask; isPascal = FALSE; isKernel = FALSE; isOscall = FALSE; isInterrupt = FALSE; isTask = FALSE; isNocall = FALSE; sp->NumParms = nparms; stmt = ParseFunctionBody(sp); funcbottom(stmt); } j1: global_flag = oldglobal; return 0; }
//------------------------------------------------------------------------------ int NextThenAcceptToken(READFILE Stream,TokenType Type,char * Value) { NextToken(Stream); return(AcceptToken(Stream,Type,Value)); }
// show one of the root menus bool MenuMaker_ShowMenu(int id, const char* param) { char buffer[MAX_PATH]; Menu *m; int x, y, n, flags, toggle; static const char * const menu_string_ids[] = { "", "root", "workspaces", "icons", "tasks", "configuration", NULL }; enum { e_lastmenu, e_root, e_workspaces, e_icons, e_tasks, e_configuration, }; x = y = flags = n = toggle = 0; switch (id) { case BB_MENU_BROAM: // @ShowMenu ... while (param[0] == '-') { const char *p = NextToken(buffer, ¶m, NULL); if (0 == strcmp(p, "-at")) { for (;;++param) { if (*param == 'r') flags |= BBMENU_XRIGHT; else if (*param == 'b') flags |= BBMENU_YBOTTOM; else break; } x = atoi(NextToken(buffer, ¶m, " ,")); param += ',' == *param; y = atoi(NextToken(buffer, ¶m, NULL)); flags |= BBMENU_XY; } else if (0 == strcmp(p, "-key")) { flags |= BBMENU_KBD; } else if (0 == strcmp(p, "-toggle")) { toggle = 1; } else if (0 == strcmp(p, "-pinned")) { flags |= BBMENU_PINNED; } else if (0 == strcmp(p, "-ontop")) { flags |= BBMENU_ONTOP; } else if (0 == strcmp(p, "-notitle")) { flags |= BBMENU_NOTITLE; } } break; case BB_MENU_ROOT: // Main menu param = "root"; break; case BB_MENU_TASKS: // Workspaces menu param = "workspaces"; break; case BB_MENU_ICONS: // Iconized tasks menu param = "icons"; break; case BB_MENU_UPDATE: Menu_Update(MENU_UPD_ROOT); Menu_All_Redraw(0); return false; case BB_MENU_SIGNAL: // just to signal e.g. BBSoundFX return true; default: return false; } // If invoked by kbd and the menu currently has focus, // hide it and return if (((flags & BBMENU_KBD) || toggle) && Menu_ToggleCheck(param)) return false; //DWORD t1 = GetTickCount(); switch (get_string_index(param, menu_string_ids)) { case e_root: case e_lastmenu: m = MakeRootMenu("root", menuPath(NULL), default_root_menu, true); break; case e_workspaces: m = MakeDesktopMenu(0, true); break; case e_icons: m = MakeDesktopMenu(1, true); break; case e_tasks: m = MakeDesktopMenu(2, true); break; case e_configuration: m = MakeConfigMenu(true); break; default: n = get_workspace_number(param); // e.g. 'workspace1' if (-1 != n) { m = MakeTaskFolder(n, true); } else if (FindRCFile(buffer, param, NULL)) { m = MakeRootMenu(param, buffer, NULL, true); } else { const char *cmd = get_special_command(¶m, buffer, sizeof buffer); m = MakeFolderMenu(NULL, param, cmd); } break; } if (NULL == m) return false; MenuOption(m, flags, x, y); ShowMenu(m); //dbg_printf("showmenu time %d", GetTickCount() - t1); return true; }
/* ParseConfigurationFile - parse a configuration file */ BoardConfig *BoardConfig::parseConfigurationFile(const char *name) { char path[PATH_MAX]; BoardConfig *baseConfig, *config; const char *src; char *tag, *dst; LineBuf buf; FILE *fp; int ch; /* make a local copy of the name in lowercase */ src = name; dst = path; while ((*dst++ = tolower(*src++)) != '\0') ; /* check for a request for the default configuration */ if (strcmp(path, DEF_BOARD) == 0) return getDefaultConfiguration(); /* make the configuration file name */ strcat(path, ".cfg"); /* open the configuration file */ if (!(fp = fopen(path, "r"))) return NULL; /* create a new board configuration */ baseConfig = config = newBoardConfig(getDefaultConfiguration(), name); /* initialize the line number */ buf.lineNumber = 0; /* process each line in the configuration file */ while (fgets(buf.lineBuf, sizeof(buf.lineBuf), fp)) { char *p; int len; /* check for a comment at the end of the line */ if ((p = strchr(buf.lineBuf, '#')) != NULL) *p = '\0'; /* trim any trailing newline and spaces */ for (len = strlen(buf.lineBuf); len > 0; --len) if (!isspace(buf.lineBuf[len-1])) break; buf.lineBuf[len] = '\0'; /* initialize token parser */ buf.linePtr = buf.lineBuf; ++buf.lineNumber; /* look for the first token on the line */ switch (SkipSpaces(&buf)) { case '\0': /* blank line */ case '#': /* comment */ // ignore blank lines and comments break; case '[': /* configuration tag */ /* get the configuration name */ ++buf.linePtr; if (!(tag = NextToken(&buf, "]", &ch))) ParseError(&buf, "missing configuration tag"); if (ch != ']') { if (SkipSpaces(&buf) != ']') ParseError(&buf, "missing close bracket after configuration tag"); ++buf.linePtr; } if (SkipSpaces(&buf) != '\0') ParseError(&buf, "missing end of line"); /* add a new board configuration */ config = newBoardConfig(baseConfig, tag); break; default: /* tag:value pair */ /* get the tag */ if (!(tag = NextToken(&buf, ":", &ch))) ParseError(&buf, "missing tag"); /* check for the colon separator */ if (ch != ':') { if (SkipSpaces(&buf) != ':') ParseError(&buf, "missing colon"); ++buf.linePtr; } /* skip leading spaces before the value */ SkipSpaces(&buf); /* set the configuration value */ config->setConfigField(tag, buf.linePtr); break; } } /* close the board configuration file */ fclose(fp); //DumpBoardConfiguration(baseConfig); /* return the board configuration */ return baseConfig; }
double Evaluate (double acc, struct TokenStruct op, char *status, char *look, struct Variable *Vars) { #ifdef DEBUG printf ("Evaluate in; acc: %f, op: %s, status: %i, look: %c;\n", acc, op.Token, *status, *look); #endif /* if (*status > 0) { // if there are errors from other routines, handle error return; }*/ if (!op.priority) { // no operator present; return passed in value, if valid if (!*status) { return acc; } else if (*status < 0) { *status += 8; } HandleError (op, *status, look); return; } else if (op.priority == -1) { // invalid operator *status = 1; HandleError (op, *status, look); return; } else if (op.priority == 1) { if (op.Token[0] == ')' && *status < 0) { *status = 0; return acc; } else if (*status == -2 && op.Token[0] == ',') { return acc; } // end of argument else { *status += 8; } // ',' after substatement (-1 -> 7) or other (0 -> 8) HandleError (op, *status, look); return; } struct TokenStruct val = NextToken (look); double cur; char neg = 0; if (val.Token[0] == '-') { // if value is negative (has - preceding it), evaluate as negative and get next token neg = 1; val = NextToken (look); } if (val.Token[0] == '(') { cur = EvalSubStatement (status, look, Vars); } // sub statement if (*status > 0) { return; } // invalid sub statement struct TokenStruct nop = NextToken (look); // next operator if (nop.Token[0] == '(') { // Function; TokenType (*Val) > 0 && cur = EvalFunction (val, status, look, Vars); nop = NextToken (look); // get operator after function } else if (val.Token[0] != '(') { cur = Resolve (val, status, Vars); } // not a function or substatement, so resolve normally if (*status > 0) { // invalid function or value HandleError (val, *status, look); return; } if (neg) { cur *= -1.0; } // account for negative numbers switch (op.Token[0]) { case '+': if (nop.priority <= op.priority) { return Evaluate (acc + cur, nop, status, look, Vars); } // operator has equal or greater precedence than next operator else { return acc + (Evaluate (cur, nop, status, look, Vars)); } // operator has less precedence than next operator case '-': if (nop.priority <= op.priority) { return Evaluate (acc - cur, nop, status, look, Vars); } else { return acc - (Evaluate (cur, nop, status, look, Vars)); } case '*': if (nop.priority <= op.priority) { return Evaluate (acc * cur, nop, status, look, Vars); } else { return acc * (Evaluate (cur, nop, status, look, Vars)); } case '/': if (nop.priority <= op.priority) { return Evaluate (acc / cur, nop, status, look, Vars); } else { return acc / (Evaluate (cur, nop, status, look, Vars)); } case '%': if (nop.priority <= op.priority) { return Evaluate (fmod (acc, cur), nop, status, look, Vars); } else { return fmod (acc, (Evaluate (cur, nop, status, look, Vars))); } case '^': if (nop.priority <= op.priority) { return Evaluate (pow (acc, cur), nop, status, look, Vars); } else { return pow (acc, (Evaluate (cur, nop, status, look, Vars))); } } *status = 1; HandleError (op, *status, look); return; // invalid operator }
char Parse (struct Variable *Vars) { // grabs first two tokens to see if they are an assign statment // Symbol-specified functions: // = (Assign), + (Add), - (Subtract), * (Multiply), / (Divide), % (Modulus), ^ (Power) // Future symbols: ! (Factorial / Gamma function), // Unused symbols: ~, `, @, #, $, &, [, ], {, }, |, \, ;, :, ', ", ?, ,, <, >, line_index = 0; char look = 0, status = 0; printf ("> "); fflush (0); struct TokenStruct /*Oper*/and = NextToken (&look); // check for calculator commands if (!strcmp (and.Token, "DISPLAY")) { // display variable tree char *disp = 0; DisplayVars (Vars, disp, 0); HandleError (and, 0, &look); return 0; } else if (!strcmp (and.Token, "ECHO")) { // toggle input echo mode ECHO = 1 - ECHO; if (ECHO) { puts ("Input echo on"); } else { puts ("Input echo off"); } HandleError (and, 0, &look); return 0; } else if (!strcmp (and.Token, "HELP")) { // display help screen puts ("Basic Calculator V 0.9"); puts ("--------------------------------------------------------------------------------"); puts ("This program is meant to be used as a general purpose calculator, akin to bc. Users can input arithmitic expressions of arbitrary length, assign and retrieve variables, and calculate common math functions. If the expression input isn't valid, the program displays an error message, indicates where in the line the problem occured, clears the input and resumes operation. In addition, users can work in interactive mode or redirect input scripts to execute a list of operations."); puts ("--------------------------------------------------------------------------------"); puts ("COMMANDS: (case sensitive)"); puts (" DISPLAY : Display defined variables and their associated values."); puts (" ECHO : Echo user input on next line. Useful when using an input script."); puts (" HELP : Display this help screen."); puts (" QUIT : Quit this calculator program."); puts ("--------------------------------------------------------------------------------"); puts ("MATH FUNCTIONS: (not case sensitive)\n"); puts ("ABS / ABSOLUTE :\n return the absolute value of the argument. Accepts one argument."); puts ("ASIN / ARCSINE :\n return the arc sine (inverse sine function) of the argument. Accepts one argument."); puts ("ACOS / ARCCOSINE :\n return the arc cosine (inverse cosine function) of the argument. Accepts one argument."); puts ("ATAN / ARCTANGENT :\n return the arc tangent (inverse tangent function) of the argument. Accepts one argument."); puts ("COS / COSINE :\n return the cosine of the argument. Accepts one argument."); puts ("DIST / DISTANCE / HYPOTENUSE :\n return the pythangorian distance (hypotenuse) between two values. Accepts two arguments."); puts ("E :\n return the value of e. Accepts no arguments."); puts ("EXP :\n return the exponent of the argument (e ^ arg). Accepts one argument."); puts ("LN / NATURAL_LOG :\n return the natural log of the argument (arg = e ^ x). Accepts one argument."); puts ("LOG / LOGARITHM :\n return the natural log of an argument OR the log of one argument in terms of another (log A / log b). Accepts one or two arguments."); puts ("MOD / MODULUS :\n return the remainder of one argument divided by another. Accepts two arguments."); puts ("PI :\n return the value of pi. Accepts no arguments."); puts ("POW / POWER :\n return the value of one argument raised to the power of the other. Accepts two arguments."); puts ("PROD / PRODUCT :\n return the product of the arguments. Accepts one or more arguments."); puts ("SIN / SINE :\n return the sine of the argument. Accepts one argument."); puts ("SQRT / SQUARE_ROOT :\n return the square root of the argument. Accepts one argument."); puts ("SUM / SUMMATION :\n return the sum of the arguments. Accepts one or more arguments."); puts ("TAN / TANGENT :\n return the tangent of the argument. Accepts one argument."); HandleError (and, 0, &look); return 0; } else if (!strcmp (and.Token, "QUIT")) { // quit calculator HandleError (and, 0, &look); return 1; } struct TokenStruct /*Oper*/ator; struct TokenStruct tmp; tmp.Token = malloc (sizeof (char) * 2); tmp.Token = "+"; tmp.type = TokenType ('+'); tmp.priority = OpPriority ('+'); if (!and.priority) { return 0; } // no operand; blank line double result = 0.0; double sign = 1.0; if (and.Token[0] == '-') { // negative value sign = -1.0; and = NextToken (&look); } if (and.Token[0] == '(') { result = sign * EvalSubStatement (&status, &look, Vars); } // substatement if (status) { return 0; } ator = NextToken (&look); // must be determined *after* substatement, and *before* function, assignment, or variable // function, assignment, or variable; need operator to decide if (ator.Token[0] == '(') { // function result = sign * EvalFunction (and, &status, &look, Vars); if (status) { if (status == 5 || status == 9) { HandleError (and, status, &look); } return 0; } ator = NextToken (&look); result = Evaluate (result, ator, &status, &look, Vars); } else if (and.type == 1 && ator.Token[0] == '=') { result = Evaluate (0.0, tmp, &status, &look, Vars); } // assignment; don't need to check status here since it will be checked as soon as this statement is finished else { // variable, number, substatement, or invalid if (and.Token[0] != '(') { result = sign * Resolve (and, &status, Vars); if (status) { HandleError (and, status, &look); return 0; } } result = Evaluate (result, ator, &status, &look, Vars); } if (status) { return 0; } else if (ator.Token[0] == '=') { AssignValue (and.Token, result, Vars); printf ("%s ", and.Token); } printf ("= %f;\n", result); return 0; }
void ParseAttribute (Declaration* D) /* Parse an additional __attribute__ modifier */ { /* Do we have an attribute? */ if (CurTok.Tok != TOK_ATTRIBUTE) { /* No attribute, bail out */ return; } /* Skip the attribute token */ NextToken (); /* Expect two(!) open braces */ ConsumeLParen (); ConsumeLParen (); /* Read a list of attributes */ while (1) { ident AttrName; const AttrDesc* Attr = 0; /* Identifier follows */ if (CurTok.Tok != TOK_IDENT) { /* No attribute name */ Error ("Attribute name expected"); /* Skip until end of attribute */ ErrorSkip (); /* Bail out */ return; } /* Map the attribute name to its id, then skip the identifier */ strcpy (AttrName, CurTok.Ident); Attr = FindAttribute (AttrName); NextToken (); /* Did we find a valid attribute? */ if (Attr) { /* Call the handler */ Attr->Handler (D); } else { /* Attribute not known, maybe typo */ Error ("Illegal attribute: `%s'", AttrName); /* Skip until end of attribute */ ErrorSkip (); /* Bail out */ return; } /* If a comma follows, there's a next attribute. Otherwise this is the ** end of the attribute list. */ if (CurTok.Tok != TOK_COMMA) { break; } NextToken (); } /* The declaration is terminated with two closing braces */ ConsumeRParen (); ConsumeRParen (); }
int ParseFile(char* pcStart, FILE *fileDest, PFNOUTLINE OutputLine) { char *pc, *pcLine; int nLine; EXPORT exp; int included; //fprintf(stderr, "info: line %d, pcStart:'%.30s'\n", nLine, pcStart); /* Loop all lines */ nLine = 1; exp.nNumber = 0; for (pcLine = pcStart; *pcLine; pcLine = NextLine(pcLine), nLine++) { pc = pcLine; exp.nArgCount = 0; exp.uFlags = 0; exp.nNumber++; //fprintf(stderr, "info: line %d, token:'%d, %.20s'\n", // nLine, TokenLength(pcLine), pcLine); /* Skip white spaces */ while (*pc == ' ' || *pc == '\t') pc++; /* Skip empty lines, stop at EOF */ if (*pc == ';' || *pc <= '#') continue; if (*pc == 0) return 0; //fprintf(stderr, "info: line %d, token:'%.*s'\n", // nLine, TokenLength(pc), pc); /* Now we should get either an ordinal or @ */ if (*pc == '@') exp.nOrdinal = -1; else exp.nOrdinal = atol(pc); /* Go to next token (type) */ if (!(pc = NextToken(pc))) { fprintf(stderr, "error: line %d, unexpected end of line\n", nLine); return -10; } //fprintf(stderr, "info: Token:'%.10s'\n", pc); /* Now we should get the type */ if (CompareToken(pc, "stdcall")) { exp.nCallingConvention = CC_STDCALL; } else if (CompareToken(pc, "cdecl") || CompareToken(pc, "varargs")) { exp.nCallingConvention = CC_CDECL; } else if (CompareToken(pc, "fastcall")) { exp.nCallingConvention = CC_FASTCALL; } else if (CompareToken(pc, "thiscall")) { exp.nCallingConvention = CC_THISCALL; } else if (CompareToken(pc, "extern")) { exp.nCallingConvention = CC_EXTERN; } else if (CompareToken(pc, "stub")) { exp.nCallingConvention = CC_STUB; } else { fprintf(stderr, "error: line %d, expected type, got '%.*s' %d\n", nLine, TokenLength(pc), pc, *pc); return -11; } //fprintf(stderr, "info: nCallingConvention: %d\n", exp.nCallingConvention); /* Go to next token (options or name) */ if (!(pc = NextToken(pc))) { fprintf(stderr, "fail2\n"); return -12; } /* Handle options */ included = 1; while (*pc == '-') { if (CompareToken(pc, "-arch")) { /* Default to not included */ included = 0; pc += 5; /* Look if we are included */ while (*pc == '=' || *pc == ',') { pc++; if (CompareToken(pc, pszArchString) || CompareToken(pc, pszArchString2)) { included = 1; } /* Skip to next arch or end */ while (*pc > ',') pc++; } } else if (CompareToken(pc, "-i386")) { if (giArch != ARCH_X86) included = 0; } else if (CompareToken(pc, "-private")) { exp.uFlags |= FL_PRIVATE; } else if (CompareToken(pc, "-noname") || CompareToken(pc, "-ordinal")) { exp.uFlags |= FL_NONAME; } else if (CompareToken(pc, "-stub")) { exp.uFlags |= FL_STUB; } else if (CompareToken(pc, "-norelay") || CompareToken(pc, "-register") || CompareToken(pc, "-ret64")) { /* silently ignore these */ } else { fprintf(stderr, "info: ignored option: '%.*s'\n", TokenLength(pc), pc); } /* Go to next token */ pc = NextToken(pc); } //fprintf(stderr, "info: Name:'%.10s'\n", pc); /* If arch didn't match ours, skip this entry */ if (!included) continue; /* Get name */ exp.pcName = pc; exp.nNameLength = TokenLength(pc); /* Handle parameters */ exp.nStackBytes = 0; if (exp.nCallingConvention != CC_EXTERN && exp.nCallingConvention != CC_STUB) { //fprintf(stderr, "info: options:'%.10s'\n", pc); /* Go to next token */ if (!(pc = NextToken(pc))) { fprintf(stderr, "fail4\n"); return -13; } /* Verify syntax */ if (*pc++ != '(') { fprintf(stderr, "error: line %d, expected '('\n", nLine); return -14; } /* Skip whitespaces */ while (*pc == ' ' || *pc == '\t') pc++; exp.nStackBytes = 0; while (*pc >= '0') { if (CompareToken(pc, "long")) { exp.nStackBytes += 4; exp.anArgs[exp.nArgCount] = ARG_LONG; } else if (CompareToken(pc, "double")) { exp.nStackBytes += 8; exp.anArgs[exp.nArgCount] = ARG_DBL; } else if (CompareToken(pc, "ptr") || CompareToken(pc, "str") || CompareToken(pc, "wstr")) { exp.nStackBytes += 4; // sizeof(void*) on x86 exp.anArgs[exp.nArgCount] = ARG_PTR; // FIXME: handle strings } else if (CompareToken(pc, "int64")) { exp.nStackBytes += 8; exp.anArgs[exp.nArgCount] = ARG_INT64; } else if (CompareToken(pc, "int128")) { exp.nStackBytes += 16; exp.anArgs[exp.nArgCount] = ARG_INT128; } else if (CompareToken(pc, "float")) { exp.nStackBytes += 4; exp.anArgs[exp.nArgCount] = ARG_FLOAT; } else fprintf(stderr, "error: line %d, expected type, got: %.10s\n", nLine, pc); exp.nArgCount++; /* Go to next parameter */ if (!(pc = NextToken(pc))) { fprintf(stderr, "fail5\n"); return -15; } } /* Check syntax */ if (*pc++ != ')') { fprintf(stderr, "error: line %d, expected ')'\n", nLine); return -16; } } /* Handle special stub cases */ if (exp.nCallingConvention == CC_STUB) { /* Check for c++ mangled name */ if (pc[0] == '?') { //printf("Found c++ mangled name...\n"); // } else { /* Check for stdcall name */ char *p = strchr(pc, '@'); if (p && ((size_t)(p - pc) < exp.nNameLength)) { int i; exp.nNameLength = p - pc; if (exp.nNameLength < 1) { fprintf(stderr, "error, @ in line %d\n", nLine); return -1; } exp.nStackBytes = atoi(p + 1); exp.nArgCount = exp.nStackBytes / 4; exp.nCallingConvention = CC_STDCALL; exp.uFlags |= FL_STUB; for (i = 0; i < exp.nArgCount; i++) exp.anArgs[i] = ARG_LONG; } } } /* Get optional redirection */ if ((pc = NextToken(pc))) { exp.pcRedirection = pc; exp.nRedirectionLength = TokenLength(pc); /* Check syntax (end of line) */ if (NextToken(pc)) { fprintf(stderr, "error: line %d, additional tokens after ')'\n", nLine); return -17; } } else { exp.pcRedirection = 0; exp.nRedirectionLength = 0; } OutputLine(fileDest, &exp); } return 0; }
void doinit(SYM *sp) { char lbl[200]; int algn; enum e_sg oseg; oseg = noseg; lbl[0] = 0; // Initialize constants into read-only data segment. Constants may be placed // in ROM along with code. if (sp->isConst) { oseg = rodataseg; } if (sp->storage_class == sc_thread) { if (sp->tp->type==bt_struct || sp->tp->type==bt_union) algn = imax(sp->tp->alignment,2); else if (sp->tp->type==bt_pointer && sp->tp->val_flag) algn = imax(sp->tp->GetBtp()->alignment,2); else algn = 2; seg(oseg==noseg ? tlsseg : oseg,algn); nl(); } else if (sp->storage_class == sc_static || lastst==assign) { if (sp->tp->type==bt_struct || sp->tp->type==bt_union) algn = imax(sp->tp->alignment,2); else if (sp->tp->type==bt_pointer && sp->tp->val_flag) algn = imax(sp->tp->GetBtp()->alignment,2); else algn = 2; seg(oseg==noseg ? dataseg : oseg,algn); /* initialize into data segment */ nl(); /* start a new line in object */ } else { if (sp->tp->type==bt_struct || sp->tp->type==bt_union) algn = imax(sp->tp->alignment,2); else if (sp->tp->type==bt_pointer && sp->tp->val_flag) algn = imax(sp->tp->GetBtp()->alignment,2); else algn = 2; seg(oseg==noseg ? bssseg : oseg,algn); /* initialize into data segment */ nl(); /* start a new line in object */ } if(sp->storage_class == sc_static || sp->storage_class == sc_thread) { sp->realname = my_strdup(put_label(sp->value.i, (char *)sp->name->c_str(), GetNamespace(), 'D')); } else { if (sp->storage_class == sc_global) { strcpy_s(lbl, sizeof(lbl), "public "); if (curseg==dataseg) strcat_s(lbl, sizeof(lbl), "data "); else if (curseg==bssseg) strcat_s(lbl, sizeof(lbl), "bss "); else if (curseg==tlsseg) strcat_s(lbl, sizeof(lbl), "tls "); } strcat_s(lbl, sizeof(lbl), sp->name->c_str()); gen_strlab(lbl); } if (lastst == kw_firstcall) { GenerateByte(1); return; } else if( lastst != assign) { genstorage(sp->tp->size); } else { NextToken(); InitializeType(sp->tp); } endinit(); if (sp->storage_class == sc_global) ofs.printf("\nendpublic\n"); }
void PragAux( void ) /******************/ { struct { unsigned f_call : 1; unsigned f_loadds : 1; unsigned f_rdosdev: 1; unsigned f_export : 1; unsigned f_parm : 1; unsigned f_value : 1; unsigned f_modify : 1; unsigned f_frame : 1; unsigned uses_auto: 1; } have; InitAuxInfo(); if( !GetAliasInfo() ) return; if( CurToken != T_ID ) return; SetCurrInfo( Buffer ); NextToken(); PragObjNameInfo( &AuxInfo.objname ); have.f_call = 0; have.f_loadds = 0; have.f_rdosdev = 0; have.f_export = 0; have.f_parm = 0; have.f_value = 0; have.f_modify = 0; have.f_frame = 0; have.uses_auto = 0; /* BBB - Jan 26, 1994 */ for( ;; ) { if( !have.f_call && CurToken == T_EQUAL ) { have.uses_auto = GetByteSeq( &AuxInfo.code ); have.f_call = 1; } else if( !have.f_call && PragRecog( "far" ) ) { AuxInfo.cclass |= FAR; have.f_call = 1; } else if( !have.f_call && PragRecog( "near" ) ) { AuxInfo.cclass &= ~FAR; AuxInfoFlg.f_near = 1; have.f_call = 1; } else if( !have.f_loadds && PragRecog( "loadds" ) ) { AuxInfo.cclass |= LOAD_DS_ON_ENTRY; have.f_loadds = 1; } else if( !have.f_rdosdev && PragRecog( "rdosdev" ) ) { AuxInfo.cclass |= LOAD_RDOSDEV_ON_ENTRY; have.f_rdosdev = 1; } else if( !have.f_export && PragRecog( "export" ) ) { AuxInfo.cclass |= DLL_EXPORT; have.f_export = 1; } else if( !have.f_parm && PragRecog( "parm" ) ) { GetParmInfo(); have.f_parm = 1; } else if( !have.f_value && PragRecog( "value" ) ) { GetRetInfo(); have.f_value = 1; } else if( !have.f_value && PragRecog( "aborts" ) ) { AuxInfo.cclass |= SUICIDAL; have.f_value = 1; } else if( !have.f_modify && PragRecog( "modify" ) ) { GetSaveInfo(); have.f_modify = 1; } else if( !have.f_frame && PragRecog( "frame" ) ) { AuxInfo.cclass |= GENERATE_STACK_FRAME; have.f_frame = 1; } else { break; } } if( have.uses_auto ) { /* We want to force the calling routine to set up a [E]BP frame for the use of this pragma. This is done by saying the pragma modifies the [E]SP register. A kludge, but it works. */ HW_CTurnOn( AuxInfo.save, HW_SP ); } CopyAuxInfo(); PragEnding(); }
local int GetByteSeq( byte_seq **code ) /*************************************/ { unsigned char buff[MAXIMUM_BYTESEQ + 32]; char *name; unsigned long offset; fix_words fixword; int uses_auto; char too_many_bytes; #if _CPU == 8086 bool use_fpu_emu = FALSE; #endif AsmSysInit( buff ); CompFlags.pre_processing = 1; /* enable macros */ NextToken(); too_many_bytes = 0; uses_auto = 0; offset = 0; name = NULL; for( ;; ) { if( CurToken == T_STRING ) { /* 06-sep-91 */ #if _CPU == 8086 AsmLine( Buffer, GET_FPU_EMU( ProcRevision ) ); use_fpu_emu = FALSE; #else AsmLine( Buffer, FALSE ); #endif NextToken(); if( CurToken == T_COMMA ) { NextToken(); } } else if( CurToken == T_CONSTANT ) { #if _CPU == 8086 if( use_fpu_emu ) { AddAFix( AsmCodeAddress, NULL, FIX_SEG, 0 ); use_fpu_emu = FALSE; } #endif AsmCodeBuffer[AsmCodeAddress++] = Constant; NextToken(); } else { #if _CPU == 8086 use_fpu_emu = FALSE; #endif fixword = FixupKeyword(); if( fixword == FIXWORD_NONE ) break; if( fixword == FIXWORD_FLOAT ) { #if _CPU == 8086 if( GET_FPU_EMU( ProcRevision ) ) { use_fpu_emu = TRUE; } #endif } else { /* seg or offset */ if( CurToken != T_ID ) { CErr1( ERR_EXPECTING_ID ); } else { name = CStrSave( Buffer ); NextToken(); if( CurToken == T_PLUS ) { NextToken(); if( CurToken == T_CONSTANT ) { offset = Constant; NextToken(); } } else if( CurToken == T_MINUS ) { NextToken(); if( CurToken == T_CONSTANT ) { offset = -Constant; NextToken(); } } } switch( fixword ) { case FIXWORD_RELOFF: #if _CPU == 8086 AddAFix( AsmCodeAddress, name, FIX_RELOFF16, offset ); AsmCodeAddress += 2; #else AddAFix( AsmCodeAddress, name, FIX_RELOFF32, offset ); AsmCodeAddress += 4; #endif break; case FIXWORD_OFFSET: #if _CPU == 8086 AddAFix( AsmCodeAddress, name, FIX_OFF16, offset ); AsmCodeAddress += 2; #else AddAFix( AsmCodeAddress, name, FIX_OFF32, offset ); AsmCodeAddress += 4; #endif break; case FIXWORD_SEGMENT: AddAFix( AsmCodeAddress, name, FIX_SEG, 0 ); AsmCodeAddress += 2; break; } } } if( AsmCodeAddress > MAXIMUM_BYTESEQ ) { if( ! too_many_bytes ) { CErr1( ERR_TOO_MANY_BYTES_IN_PRAGMA ); too_many_bytes = 1; } AsmCodeAddress = 0; // reset index to we don't overrun buffer } } if( too_many_bytes ) { FreeAsmFixups(); uses_auto = 0; } else { uses_auto = InsertFixups( buff, AsmCodeAddress, code ); } CompFlags.pre_processing = 2; AsmSysFini(); return( uses_auto ); }
/* ************************************************************************************** * ReadDetail: * Read the position detail for all the position definitions in the position definition * file. Store the values in the POSITIONS table. ************************************************************************************* */ void ReadDetail() { int p = 0; char *nextName, *ptr; int HPOffset, HPTable, HPCount; int screenOffset, screenTable, screenCount; int ScriptOffset, ScriptTable, ScriptCount; int AFPOffset, AFPTable, AFPCount; ALIAS *alias; char *shareName; infof("Reading position definition detail..."); while (NextLine()) { if (strncmp(IOBuff,"DEFINE POSITION ",16)) { if (!strncmp(IOBuff,"DEFINE ",7)) errorfp("Invalid DEFINE statement at line %d",CurrentLine); continue; } ptr = IOBuff + 16; nextName = NextToken(&ptr,STATIC_STRING); if (nextName == NULL || strcmp(nextName,Positions[p].name.name)) continue; HPCount = screenCount = ScriptCount = AFPCount = 0; while (NextLine()) { ptr = IOBuff; if (!NextToken(&ptr,STATIC_STRING)) break; if (sscanf(IOBuff,"HP OFFSET %d = %d",&HPTable,&HPOffset) == 2) { if (HPTable > TotalLanguages || HPTable < 1) { errorfp("Invalid HP table number %d at line %d", HPTable,CurrentLine); HPTable = 1; } Positions[p].HPOffset[HPTable-1] = HPOffset; HPCount++; } else if (sscanf(IOBuff,"SCREEN OFFSET %d = %d",&screenTable,&screenOffset) == 2) { if (screenTable > TotalLanguages || screenTable < 1) { errorfp("Invalid screen table number %d at line %d", screenTable,CurrentLine); screenTable = 1; } Positions[p].screenOffset[screenTable-1] = screenOffset; screenCount++; } else if (sscanf(IOBuff,"SCRIPT OFFSET %d = %d",&ScriptTable,&ScriptOffset) == 2) { if (ScriptTable > TotalLanguages || ScriptTable < 1) { errorfp("Invalid Script table number %d at line %d", ScriptTable,CurrentLine); ScriptTable = 1; } Positions[p].ScriptOffset[ScriptTable-1] = ScriptOffset; ScriptCount++; } else if (sscanf(IOBuff,"AFP OFFSET %d = %d", &AFPTable, &AFPOffset) == 2) { if (AFPTable > TotalLanguages || AFPTable < 1) { errorfp("Invalid AFP table number %d at line %d", AFPTable, CurrentLine); AFPTable = 1; } Positions[p].AFPOffset[AFPTable-1] = AFPOffset; AFPCount++; } else if (!strncmp(IOBuff,"ALIAS = ",8)) { ptr = IOBuff + 8; while (shareName = NextToken(&ptr,DYNAMIC_STRING)) { if (LookupName(shareName) > 0) { errorfp("Alias %s at line %d has already been defined", shareName,CurrentLine); continue; } alias = (ALIAS *)malloc(sizeof(ALIAS)); if (alias == NULL) fatalf("Failure allocating %d alias bytes",sizeof(ALIAS)); alias->name = shareName; alias->next = Positions[p].alias; Positions[p].alias = alias; } } } if (HPCount && HPCount != TotalLanguages) errorfp("Invalid HP offset count for %s, line %d", Positions[p].name,CurrentLine); if (screenCount && screenCount != TotalLanguages) errorfp("Invalid screen offset count for %s, line %d", Positions[p].name,CurrentLine); if (ScriptCount && ScriptCount != TotalLanguages) errorfp("Invalid Script offset count for %s, line %d", Positions[p].name,CurrentLine); if (AFPCount && AFPCount != TotalLanguages) errorfp("Invalid AFP offset count for %s, line %d", Positions[p].name, CurrentLine); p++; } if (p != TotalPositions) errorfp("Expected %d details, found %d",TotalPositions,p); }
extern void CommandExportPositionText(char *sz) { FILE *pf; int fHistory; moverecord *pmr; int iMove; GString *gsz; sz = NextToken(&sz); if (ms.gs == GAME_NONE) { outputl(_("No game in progress (type `new game' to start one).")); return; } if (!sz || !*sz) { outputl(_("You must specify a file to export to (see `help export " "position text').")); return; } pmr = get_current_moverecord(&fHistory); if (!confirmOverwrite(sz, fConfirmSave)) return; if (!strcmp(sz, "-")) pf = stdout; else if ((pf = g_fopen(sz, "w")) == 0) { outputerr(sz); return; } gsz = g_string_new(NULL); TextPrologue(gsz, &ms, getGameNumber(plGame)); fputs(gsz->str, pf); g_string_free(gsz, TRUE); if (exsExport.fIncludeMatchInfo) TextMatchInfo(pf, &mi); if (fHistory) iMove = getMoveNumber(plGame, pmr) - 1; else if (plLastMove) iMove = getMoveNumber(plGame, plLastMove->p); else iMove = -1; gsz = g_string_new(NULL); TextBoardHeader(gsz, &ms, getGameNumber(plGame), iMove); fputs(gsz->str, pf); g_string_free(gsz, TRUE); printTextBoard(pf, &ms); if (pmr) { gsz = g_string_new(NULL); TextAnalysis(gsz, &ms, pmr); fputs(gsz->str, pf); g_string_free(gsz, TRUE); if (exsExport.fIncludeAnnotation) TextPrintComment(pf, pmr); } TextEpilogue(pf, &ms); if (pf != stdout) fclose(pf); setDefaultFileName(sz); }
// recursive parsing of menu file static Menu* ParseMenu(struct menu_src *src, const char *title, const char *IDString) { char line[4000]; char data[4000]; char buffer[4000]; char command[40]; char label[MAX_PATH]; Menu *pMenu, *pSub; MenuItem *pItem; int f, e_cmd; const char *p_label, *p_data, *cp, *p_cmd; pMenu = NULL; for(;;) { p_label = NULL; p_data = data; if (0 == src->level) { // read default menu from string NextToken(line, &src->default_menu, "\n"); } else { f = ReadNextCommand(src->fp[src->level-1], line, sizeof(line)); if (!f) { if (src->level > 1) { dec_inc_level(src); continue; // continue from included file } e_cmd = e_no_end; goto skip; } } cp = replace_environment_strings(line, sizeof line); //dbg_printf("Menu %08x line:%s", pMenu, line); // get the command if (false == get_string_within(command, sizeof command, &cp, "[]")) continue; // search the command e_cmd = get_string_index(command, menu_cmds); if (get_string_within(label, sizeof label, &cp, "()")) p_label = label; if (false == get_string_within(data, sizeof data, &cp, "{}")) p_data = label; skip: if (NULL == pMenu) { if (e_begin == e_cmd) { // If the line contains [begin] we create the menu // If no menu title has been defined, display Blackbox version... #ifdef BBXMENU if (src->default_menu) strcpy(label, "bbXMenu"); else #endif if (0 == label[0] && src->default_menu) p_label = GetBBVersion(); pMenu = MakeNamedMenu(p_label, IDString, src->popup); continue; } if (NULL == title) title = NLS0("missing [begin]"); pMenu = MakeNamedMenu(title, IDString, src->popup); } pItem = NULL; switch (e_cmd) { //==================== // [begin] is like [submenu] when within the menu case e_begin: case e_submenu: sprintf(buffer, "%s_%s", IDString, label); strlwr(buffer + strlen(IDString)); pSub = ParseMenu(src, p_data, buffer); if (pSub) pItem = MakeSubmenu(pMenu, pSub, label); else pItem = MakeMenuNOP(pMenu, label); break; //==================== case e_no_end: MakeMenuNOP(pMenu, NLS0("missing [end]")); case e_end: MenuOption(pMenu, BBMENU_ISDROPTARGET); return pMenu; //==================== case e_include: { char dir[MAX_PATH]; file_directory(dir, src->path[src->level-1]); replace_shellfolders_from_base(buffer, p_data, false, dir); if (false == add_inc_level(src, buffer)) { replace_shellfolders(buffer, p_data, false); if (false == add_inc_level(src, buffer)) MakeMenuNOP(pMenu, NLS0("[include] failed")); } continue; } //==================== // a [nop] item will insert an inactive item with optional text case e_nop: pItem = MakeMenuNOP(pMenu, label); break; // a insert separator, we treat [sep] like [nop] with no label case e_sep1: case e_sep2: pItem = MakeMenuNOP(pMenu, NULL); break; //==================== // a [path] item is pointing to a dynamic folder... case e_path: p_cmd = get_special_command(&p_data, buffer, sizeof buffer); pItem = MakeMenuItemPath(pMenu, label, p_data, p_cmd); break; // a [insertpath] item will insert items from a folder... case e_insertpath: p_cmd = get_special_command(&p_data, buffer, sizeof buffer); pItem = MakeMenuItemPath(pMenu, NULL, p_data, p_cmd); break; // a [stylemenu] item is pointing to a dynamic style folder... case e_stylesmenu: pItem = MakeMenuItemPath(pMenu, label, p_data, MM_STYLE_BROAM); break; // a [styledir] item will insert styles from a folder... case e_stylesdir: pItem = MakeMenuItemPath(pMenu, NULL, p_data, MM_STYLE_BROAM); break; // a [rcmenu] item is pointing to a dynamic rc files folder... case e_rcmenu: pItem = MakeMenuItemPath(pMenu, label, p_data, MM_EDIT_BROAM); break; case e_themesmenu: pItem = MakeMenuItemPath(pMenu, label, p_data, MM_THEME_BROAM); break; //==================== // special items... case e_workspaces: pItem = MakeSubmenu(pMenu, MakeDesktopMenu(0, src->popup), p_label); break; case e_icons: pItem = MakeSubmenu(pMenu, MakeDesktopMenu(1, src->popup), p_label); break; case e_tasks: pItem = MakeSubmenu(pMenu, MakeDesktopMenu(2, src->popup), p_label); break; case e_config: pItem = MakeSubmenu(pMenu, MakeConfigMenu(src->popup), p_label); break; //==================== case e_exec: if ('@' == data[0]) { pItem = MakeMenuItem(pMenu, label, data, false); MenuItemOption(pItem, BBMENUITEM_UPDCHECK); } else { goto core_broam; } break; //==================== case e_other: f = get_workspace_number(command); // check for 'workspace1..' if (-1 != f) { pItem = MakeSubmenu(pMenu, MakeTaskFolder(f, src->popup), p_label); } else { p_data = data; goto core_broam; } break; //==================== // everything else is converted to a '@BBCore.xxx' broam core_broam: f = sprintf(buffer, "@bbCore.%s", command); strlwr(buffer+8); if (p_data[0]) sprintf(buffer + f, " %s", p_data); pItem = MakeMenuItem(pMenu, label[0]?label:command, buffer, false); break; } //#ifdef BBOPT_MENUICONS if ( Settings_menu.iconSize ) { if (pItem && get_string_within(label, sizeof label, &cp, "<>")) MenuItemOption(pItem, BBMENUITEM_SETICON, label); } //#endif } }
int CGameConfigFlag::LoadFlagFile() { FILE *fp; int size; byte *buffer; char *token; char filename[128]; sprintf( filename, "flag%s.cfg", g_lTableToken[g_config.languageType] ); fp = fopen(filename, "rb" ); if( !fp ) { MessageBox(NULL, "does not exist 'flag.cfg' file", "Error", MB_ICONHAND|MB_OK); return false; } fseek(fp,0,SEEK_END); size = ftell(fp); buffer = new byte[size+1]; fseek(fp,0,SEEK_SET); fread(buffer,size,1,fp); fclose(fp); curpos = (char *)buffer; endpos = curpos + size; while ((token = NextToken()) != NULL) { if( !stricmp( token, "CHARACTER_STORAGE" ) ) { token = NextArg(); if(!stricmp( token, "TRUE" )) gGameConfigFlag.m_bCharacter_Storage = TRUE; else if (!stricmp( token, "FALSE" )) gGameConfigFlag.m_bCharacter_Storage = FALSE; } else if( !stricmp( token, "PRECOCITY_TIME" ) ) { token = NextArg(); if(!stricmp( token, "TRUE" )) gGameConfigFlag.m_bPrecocity_Time = TRUE; else if (!stricmp( token, "FALSE" )) gGameConfigFlag.m_bPrecocity_Time = FALSE; } else if( !stricmp( token, "DIE_REDUCE_PANALTY" ) ) { token = NextArg(); if(!stricmp( token, "TRUE" )) gGameConfigFlag.m_bDie_Reduce_panality = TRUE; else if (!stricmp( token, "FALSE" )) gGameConfigFlag.m_bDie_Reduce_panality = FALSE; } else if( !stricmp( token, "MAP_ATTR_RATIO" ) ) { token = NextArg(); if(!stricmp( token, "TRUE" )) gGameConfigFlag.m_bMap_Attr_Ratio = TRUE; else if (!stricmp( token, "FALSE" )) gGameConfigFlag.m_bMap_Attr_Ratio = FALSE; } else if( !stricmp( token, "ITEM_UPGRADE_LIMIT" ) ) { token = NextArg(); if(!stricmp( token, "TRUE" )) gGameConfigFlag.m_bItem_Upgrade_Limit = TRUE; else if (!stricmp( token, "FALSE" )) gGameConfigFlag.m_bItem_Upgrade_Limit = FALSE; } else if( !stricmp( token, "ITEM_CRAFT_LIMIT" ) ) { token = NextArg(); if(!stricmp( token, "TRUE" )) gGameConfigFlag.m_bItem_Craft_Limit = TRUE; else if (!stricmp( token, "FALSE" )) gGameConfigFlag.m_bItem_Craft_Limit = FALSE; } else if( !stricmp( token, "WORLD_CHAT_LIMIT" ) ) { token = NextArg(); if(!stricmp( token, "TRUE" )) gGameConfigFlag.m_bWorld_Chat_Limit = TRUE; else if (!stricmp( token, "FALSE" )) gGameConfigFlag.m_bWorld_Chat_Limit = FALSE; } } fclose(fp); SetFlag(); if(NULL != buffer){ delete []buffer; buffer=NULL; } return true; }
// // --------------------------------------------------------------------------- // // --------------------------------------------------------------------------- TPtrC TStringTokenizer::NextToken() { return NextToken( iDelim ); }
extern void CommandExternal(char *sz) { #if !HAVE_SOCKETS outputl(_("This installation of GNU Backgammon was compiled without\n" "socket support, and does not implement external controllers.")); #else int h, hPeer, cb; struct sockaddr *psa; char szCommand[256]; char *szResponse = NULL; struct sockaddr_in saRemote; socklen_t saLen; scancontext scanctx; int fExit; int fRestart = TRUE; int retval; sz = NextToken(&sz); if (!sz || !*sz) { outputl(_("You must specify the name of the socket to the external controller.")); return; } memset(&scanctx, 0, sizeof(scanctx)); ExtInitParse(&scanctx.scanner); listenloop: { fExit = FALSE; scanctx.fDebug = FALSE; scanctx.fNewInterface = FALSE; if ((h = ExternalSocket(&psa, &cb, sz)) < 0) { SockErr(sz); ExtDestroyParse(scanctx.scanner); return; } if (bind(h, psa, cb) < 0) { SockErr(sz); closesocket(h); free(psa); ExtDestroyParse(scanctx.scanner); return; } free(psa); if (listen(h, 1) < 0) { SockErr("listen"); closesocket(h); ExternalUnbind(sz); ExtDestroyParse(scanctx.scanner); return; } outputf(_("Waiting for a connection from %s...\n"), sz); outputx(); ProcessEvents(); /* Must set length when using windows */ saLen = sizeof(struct sockaddr); while ((hPeer = accept(h, (struct sockaddr *) &saRemote, &saLen)) < 0) { if (errno == EINTR) { ProcessEvents(); if (fInterrupt) { closesocket(h); ExternalUnbind(sz); ExtDestroyParse(scanctx.scanner); return; } continue; } SockErr("accept"); closesocket(h); ExternalUnbind(sz); ExtDestroyParse(scanctx.scanner); return; } closesocket(h); ExternalUnbind(sz); /* print info about remove client */ outputf(_("Accepted connection from %s.\n"), inet_ntoa(saRemote.sin_addr)); outputx(); ProcessEvents(); while (!fExit && !(retval = ExternalRead(hPeer, szCommand, sizeof(szCommand)))) { if ((ExtParse(&scanctx, szCommand)) == 0) { /* parse error */ szResponse = scanctx.szError; } else { ProcessedFIBSBoard processedBoard; GValue *optionsmapgv; GValue *boarddatagv; GString *dbgStr; int anScore[2]; int fCrawford, fJacoby; char *asz[7] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL }; char szBoard[10000]; char **aszLines; char **aszLinesOrig; char *szMatchID; gchar *szOptStr; switch (scanctx.ct) { case COMMAND_HELP: szResponse = g_strdup("\tNo help information available\n"); break; case COMMAND_SET: szOptStr = g_value_get_gstring_gchar(g_list_nth_data(scanctx.pCmdData, 0)); if (g_ascii_strcasecmp(szOptStr, KEY_STR_DEBUG) == 0) { scanctx.fDebug = g_value_get_int(g_list_nth_data(scanctx.pCmdData, 1)); szResponse = g_strdup_printf("Debug output %s\n", scanctx.fDebug ? "ON" : "OFF"); } else if (g_ascii_strcasecmp(szOptStr, KEY_STR_NEWINTERFACE) == 0) { scanctx.fNewInterface = g_value_get_int(g_list_nth_data(scanctx.pCmdData, 1)); szResponse = g_strdup_printf("New interface %s\n", scanctx.fNewInterface ? "ON" : "OFF"); } else { szResponse = g_strdup_printf("Error: set option '%s' not supported\n", szOptStr); } g_list_gv_boxed_free(scanctx.pCmdData); break; case COMMAND_VERSION: szResponse = g_strdup("Interface: " EXTERNAL_INTERFACE_VERSION "\n" "RFBF: " RFBF_VERSION_SUPPORTED "\n" "Engine: " WEIGHTS_VERSION "\n" "Software: " VERSION "\n"); break; case COMMAND_NONE: szResponse = g_strdup("Error: no command given\n"); break; case COMMAND_FIBSBOARD: case COMMAND_EVALUATION: if (scanctx.fDebug) { optionsmapgv = (GValue *) g_list_nth_data(g_value_get_boxed(scanctx.pCmdData), 1); boarddatagv = (GValue *) g_list_nth_data(g_value_get_boxed(scanctx.pCmdData), 0); dbgStr = g_string_new(DEBUG_PREFIX); g_value_tostring(dbgStr, optionsmapgv, 0); g_string_append(dbgStr, "\n" DEBUG_PREFIX); g_value_tostring(dbgStr, boarddatagv, 0); g_string_append(dbgStr, "\n" DEBUG_PREFIX "\n"); ExternalWrite(hPeer, dbgStr->str, strlen(dbgStr->str)); ProcessFIBSBoardInfo(&scanctx.bi, &processedBoard); anScore[0] = processedBoard.nScoreOpp; anScore[1] = processedBoard.nScore; /* If the session isn't using Crawford rule, set crawford flag to false */ fCrawford = scanctx.fCrawfordRule ? processedBoard.fCrawford : FALSE; /* Set the Jacoby flag appropriately from the external interface settings */ fJacoby = scanctx.fJacobyRule; szMatchID = MatchID((unsigned int *) processedBoard.anDice, 1, processedBoard.nResignation, processedBoard.fDoubled, 1, processedBoard.fCubeOwner, fCrawford, processedBoard.nMatchTo, anScore, processedBoard.nCube, fJacoby, GAME_PLAYING); DrawBoard(szBoard, (ConstTanBoard) & processedBoard.anBoard, 1, asz, szMatchID, 15); aszLines = g_strsplit(&szBoard[0], "\n", 32); aszLinesOrig = aszLines; while (*aszLines) { ExternalWrite(hPeer, DEBUG_PREFIX, strlen(DEBUG_PREFIX)); ExternalWrite(hPeer, *aszLines, strlen(*aszLines)); ExternalWrite(hPeer, "\n", 1); aszLines++; } dbgStr = g_string_assign(dbgStr, ""); g_string_append_printf(dbgStr, DEBUG_PREFIX "X is %s, O is %s\n", processedBoard.szPlayer, processedBoard.szOpp); if (processedBoard.nMatchTo) { g_string_append_printf(dbgStr, DEBUG_PREFIX "Match Play %s Crawford Rule\n", scanctx.fCrawfordRule ? "with" : "without"); g_string_append_printf(dbgStr, DEBUG_PREFIX "Score: %d-%d/%d%s, ", processedBoard.nScore, processedBoard.nScoreOpp, processedBoard.nMatchTo, fCrawford ? "*" : ""); } else { g_string_append_printf(dbgStr, DEBUG_PREFIX "Money Session %s Jacoby Rule, %s Beavers\n", scanctx.fJacobyRule ? "with" : "without", scanctx.fBeavers ? "with" : "without"); g_string_append_printf(dbgStr, DEBUG_PREFIX "Score: %d-%d, ", processedBoard.nScore, processedBoard.nScoreOpp); } g_string_append_printf(dbgStr, "Roll: %d%d\n", processedBoard.anDice[0], processedBoard.anDice[1]); g_string_append_printf(dbgStr, DEBUG_PREFIX "CubeOwner: %d, Cube: %d, Turn: %c, Doubled: %d, Resignation: %d\n", processedBoard.fCubeOwner, processedBoard.nCube, 'X', processedBoard.fDoubled, processedBoard.nResignation); g_string_append(dbgStr, DEBUG_PREFIX "\n"); ExternalWrite(hPeer, dbgStr->str, strlen(dbgStr->str)); g_string_free(dbgStr, TRUE); g_strfreev(aszLinesOrig); } g_value_unsetfree(scanctx.pCmdData); if (scanctx.ct == COMMAND_EVALUATION) szResponse = ExtEvaluation(&scanctx); else szResponse = ExtFIBSBoard(&scanctx); break; case COMMAND_EXIT: closesocket(hPeer); fExit = TRUE; break; default: szResponse = g_strdup("Unsupported Command\n"); } unset_scan_context(&scanctx, FALSE); } if (szResponse) { if (ExternalWrite(hPeer, szResponse, strlen(szResponse))) break; g_free(szResponse); szResponse = NULL; } } /* Interrupted : get out of listen loop */ if (retval == -2) { ProcessEvents(); fRestart = FALSE; } closesocket(hPeer); if (szResponse) g_free(szResponse); szResponse = NULL; scanctx.szError = NULL; } if (fRestart) goto listenloop; unset_scan_context(&scanctx, TRUE); #endif }
MoonAppRecord * MoonAppRecordIterator::Next () { char *uid, *origin = NULL; MoonAppRecord *app; time_t mtime = 0; char c; if (inptr == inend && !Fill ()) return NULL; if (!EatWhiteSpace (true)) return NULL; // first, try decoding the uid if (!(uid = ParseUid ())) return NULL; // make sure the next token is an '=' if (NextToken () != '=') goto error; inptr++; // make sure the next token is '{' if (NextToken () != '{') goto error; inptr++; // make sure the next token is '\n' if (NextToken () != '\n') goto error; inptr++; // now we parse the properties (like origin and mtime), 1 property per line while ((c = NextToken ()) != '}') { switch (c) { case 'o': /* origin? */ if (origin) { // already have origin, error goto error; } // make sure we have enough data for strncmp while ((inend - inptr) < 6) { if (!Fill ()) goto error; } if (strncmp (inptr, "origin", 6) != 0) goto error; inptr += 6; // make sure next token is '=' if (NextToken () != '=') goto error; inptr++; // parse the origin if (!(origin = ParseOrigin ())) goto error; // Note: ParseOrigin() gobbles the trailing '\n' for us break; case 'm': /* mtime? */ if (mtime != 0) { // already have mtime, error goto error; } // make sure we have enough data for strncmp while ((inend - inptr) < 5) { if (!Fill ()) goto error; } if (strncmp (inptr, "mtime", 5) != 0) goto error; inptr += 5; // make sure next token is '=' if (NextToken () != '=') goto error; inptr++; // parse the mtime if (!(mtime = ParseMTime ())) goto error; // make sure the next token is '\n' if (NextToken () != '\n') goto error; inptr++; break; default: /* error */ goto error; } } inptr++; if (NextToken () != '\n') goto error; inptr++; app = new MoonAppRecord (); app->origin = origin; app->mtime = mtime; app->uid = uid; return app; error: g_free (origin); g_free (uid); return NULL; }
/* * funcbody starts with the current symbol being either * the first parameter id or the begin for the local * block. If begin is the current symbol then funcbody * assumes that the function has no parameters. */ void ParseFunction(SYM *sp) { int poffset, i; int oldglobal; SYM *sp1, *sp2, *makeint(); oldglobal = global_flag; global_flag = 0; poffset = 24; /* size of return block */ nparms = 0; if(lastst == id || 1) { /* declare parameters */ //while(lastst == id) { // names[nparms++] = litlate(lastid); // NextToken(); // if( lastst == comma) // NextToken(); // else // break; // } //needpunc(closepa); // dodecl(sc_member); /* declare parameters */ sp->parms = NULL; ParseParameterDeclarations(1); for(i = 0;i < nparms;++i) { if( (sp1 = search(names[i],&lsyms)) == NULL) sp1 = makeint(names[i]); //if( sp1->tp->size < 8 ) //{ // sp1->value.i = poffset;// + (8 - sp1->tp->size); // poffset += 8; //} //else //{ // sp1->value.i = poffset; // poffset += sp1->tp->size; //} sp1->value.i = poffset; poffset += 8; sp1->storage_class = sc_auto; sp1->nextparm = NULL; // record parameter list if (sp->parms == NULL) { sp->parms = sp1; } else { sp1->nextparm = sp->parms; sp->parms = sp1; } } } if (lastst == closepa) NextToken(); if (lastst == semicolon) { // Function prototype sp->IsPrototype = 1; sp->IsNocall = isNocall; sp->IsPascal = isPascal; sp->IsInterrupt = isInterrupt; sp->NumParms = nparms; isPascal = FALSE; isOscall = FALSE; isInterrupt = FALSE; isNocall = FALSE; ReleaseLocalMemory(); /* release local symbols (parameters)*/ } else if(lastst != begin) { NextToken(); ParseParameterDeclarations(2); sp->IsNocall = isNocall; sp->IsPascal = isPascal; sp->IsInterrupt = isInterrupt; sp->NumParms = nparms; ParseFunctionBody(sp); funcbottom(); } // error(ERR_BLOCK); else { sp->IsNocall = isNocall; sp->IsPascal = isPascal; sp->IsInterrupt = isInterrupt; sp->NumParms = nparms; ParseFunctionBody(sp); funcbottom(); } global_flag = oldglobal; }
//------------------------------------------------------------------------------ int NextThenAcceptTokenType(READFILE Stream,TokenType Type) { NextToken(Stream); return(AcceptTokenType(Stream,Type)); }
ST bool is_bsetroot_command(const char **cptr) { char token[MAX_PATH]; *(char*)file_extension(NextToken(token, cptr, NULL)) = 0; return 0 == stricmp(token, "bsetroot") || 0 == stricmp(token, "bsetbg"); }
static void parseRequestLine(char *const requestLine, TMethod *const httpMethodP, httpVersion *const httpVersionP, const char **const hostP, unsigned short *const portP, const char **const pathP, const char **const queryP, bool *const moreLinesP, uint16_t *const httpErrorCodeP) { /*---------------------------------------------------------------------------- Modifies *requestLine! -----------------------------------------------------------------------------*/ const char *httpMethodName; char *p; p = requestLine; /* Jump over spaces */ NextToken((const char **) &p); httpMethodName = GetToken(&p); if (!httpMethodName) *httpErrorCodeP = 400; /* Bad Request */ else { char *requestUri; if (xmlrpc_streq(httpMethodName, "GET")) *httpMethodP = m_get; else if (xmlrpc_streq(httpMethodName, "PUT")) *httpMethodP = m_put; else if (xmlrpc_streq(httpMethodName, "OPTIONS")) *httpMethodP = m_options; else if (xmlrpc_streq(httpMethodName, "DELETE")) *httpMethodP = m_delete; else if (xmlrpc_streq(httpMethodName, "POST")) *httpMethodP = m_post; else if (xmlrpc_streq(httpMethodName, "TRACE")) *httpMethodP = m_trace; else if (xmlrpc_streq(httpMethodName, "HEAD")) *httpMethodP = m_head; else *httpMethodP = m_unknown; /* URI and Query Decoding */ NextToken((const char **) &p); requestUri = GetToken(&p); if (!requestUri) *httpErrorCodeP = 400; /* Bad Request */ else { const char *host; unsigned short port; const char *path; const char *query; const char *error; parseRequestUri(requestUri, &host, &port, &path, &query, &error); if (error) { *httpErrorCodeP = 400; /* Bad Request */ xmlrpc_strfree(error); /* Someday we should do something with this */ } else { const char *httpVersion; NextToken((const char **) &p); /* HTTP Version Decoding */ httpVersion = GetToken(&p); if (httpVersion) { uint32_t vmin, vmaj; if (sscanf(httpVersion, "HTTP/%d.%d", &vmaj, &vmin) != 2) *httpErrorCodeP = 400; /* Bad Request */ else { httpVersionP->major = vmaj; httpVersionP->minor = vmin; *httpErrorCodeP = 0; /* no error */ } *moreLinesP = TRUE; } else { /* There is no HTTP version, so this is a single line request. */ *httpErrorCodeP = 0; /* no error */ *moreLinesP = FALSE; } if (*httpErrorCodeP) { xmlrpc_strfree(host); xmlrpc_strfree(path); xmlrpc_strfree(query); } *hostP = host; *portP = port; *pathP = path; *queryP = query; } } } }
void CPragma( void ) // PROCESS A PRAGMA { bool check_end = true; SrcFileGuardStateSig(); CompFlags.in_pragma = 1; NextToken(); if( PragRecog( "include_alias" ) ) { pragIncludeAlias(); } else if( CompFlags.cpp_output ) { PPCTL_ENABLE_MACROS(); fprintf( CppFile, "#pragma " ); for( ; CurToken != T_NULL; ) { PrtToken(); GetNextToken(); } PPCTL_DISABLE_MACROS(); } else if( IS_ID_OR_KEYWORD( CurToken ) ) { if( PragIdRecog( "on" ) ) { pragFlag( true ); } else if( PragIdRecog( "off" ) ) { pragFlag( false ); } else if( PragIdRecog( "aux" ) || PragIdRecog( "linkage" ) ) { PragAux(); } else if( PragIdRecog( "library" ) ) { pragLibs(); } else if( PragIdRecog( "once" ) ) { pragOnce(); } else if( PragIdRecog( "extref" ) ) { pragExtRef(); } else if( PragIdRecog( "comment" ) ) { pragComment(); } else if( PragIdRecog( "pack" ) ) { pragPack(); } else if( PragIdRecog( "warning" ) ) { if( pragWarning() ) { /* ignore #pragma warning */ check_end = false; /* skip rest of line */ } } else if( PragIdRecog( "enable_message" ) ) { pragEnableMessage(); } else if( PragIdRecog( "disable_message" ) ) { pragDisableMessage(); } else if( PragIdRecog( "code_seg" ) ) { pragCodeSeg(); } else if( PragIdRecog( "data_seg" ) ) { pragDataSeg(); } else if( PragIdRecog( "initialize" ) ) { pragInitialize(); } else if( PragIdRecog( "init_seg" ) ) { pragInitSeg(); } else if( PragIdRecog( "inline_depth" ) ) { pragInlineDepth(); } else if( PragIdRecog( "template_depth" ) ) { pragTemplateDepth(); } else if( PragIdRecog( "inline_recursion" ) ) { pragInlineRecursion(); } else if( PragIdRecog( "intrinsic" ) ) { pragIntrinsic( true ); } else if( PragIdRecog( "function" ) ) { pragIntrinsic( false ); } else if( PragIdRecog( "destruct" ) ) { pragDestruct(); } else if( PragIdRecog( "enum" ) ) { pragEnum(); } else if( PragIdRecog( "dump_object_model" ) ) { pragDumpObjectModel(); } else if( startPragRecog( "read_only_file" ) ) { pragReadOnlyFile(); } else if( startPragRecog( "read_only_directory" ) ) { pragReadOnlyDir(); } else if( PragIdRecog( "include_alias" ) ) { pragIncludeAlias(); } else if( PragIdRecog( "message" ) ) { pragMessage(); } else if( PragIdRecog( "error" ) ) { pragError(); #ifndef NDEBUG } else if( PragIdRecog( "break" ) ) { pragBreak(); #endif } else { /* unknown pragma */ check_end = false; /* skip rest of line */ } } else { /* unknown pragma */ check_end = false; /* skip rest of line */ } if( check_end ) { endOfPragma(); } CompFlags.in_pragma = 0; }
BOOL CLRTypeName::TypeNameParser::START() { NextToken(); NextToken(); return AQN(); }
static void pragDestruct( // SPECIFY DESTRUCTION MECHANISM void ) { DT_METHOD method; // - method DT_METHOD next; // - next method spec if( CurToken == T_LEFT_PAREN ) { NextToken(); method = DTM_COUNT; for( ; ; ) { if( CurToken == T_RIGHT_PAREN ) { NextToken(); break; } next = parseDtorMethod(); switch( next ) { default : method = DTM_COUNT; break; case DTM_DIRECT : switch( method ) { case DTM_TABLE : method = DTM_DIRECT_TABLE; continue; case DTM_TABLE_SMALL : method = DTM_DIRECT_SMALL; continue; case DTM_COUNT : method = next; continue; default : continue; } case DTM_TABLE : switch( method ) { case DTM_DIRECT : method = DTM_DIRECT_TABLE; continue; case DTM_COUNT : method = next; continue; default : continue; } case DTM_TABLE_SMALL : switch( method ) { case DTM_DIRECT : method = DTM_DIRECT_SMALL; continue; case DTM_DIRECT_TABLE : case DTM_TABLE : method = DTM_TABLE_SMALL; continue; case DTM_COUNT : method = next; continue; default : continue; } } break; } } else { method = parseDtorMethod(); } if( method != DTM_COUNT ) { CompInfo.dt_method_speced = method; CompFlags.dt_method_pragma = true; } }
int Statement (int* PendingToken) /* Statement parser. Returns 1 if the statement does a return/break, returns * 0 otherwise. If the PendingToken pointer is not NULL, the function will * not skip the terminating token of the statement (closing brace or * semicolon), but store true if there is a pending token, and false if there * is none. The token is always checked, so there is no need for the caller to * check this token, it must be skipped, however. If the argument pointer is * NULL, the function will skip the token. */ { ExprDesc Expr; int GotBreak; CodeMark Start, End; /* Assume no pending token */ if (PendingToken) { *PendingToken = 0; } /* Check for a label. A label is always part of a statement, it does not * replace one. */ while (CurTok.Tok == TOK_IDENT && NextTok.Tok == TOK_COLON) { /* Handle the label */ DoLabel (); CheckLabelWithoutStatement (); } switch (CurTok.Tok) { case TOK_LCURLY: NextToken (); GotBreak = CompoundStatement (); CheckTok (TOK_RCURLY, "`{' expected", PendingToken); return GotBreak; case TOK_IF: return IfStatement (); case TOK_WHILE: WhileStatement (); break; case TOK_DO: DoStatement (); break; case TOK_SWITCH: SwitchStatement (); break; case TOK_RETURN: ReturnStatement (); CheckSemi (PendingToken); return 1; case TOK_BREAK: BreakStatement (); CheckSemi (PendingToken); return 1; case TOK_CONTINUE: ContinueStatement (); CheckSemi (PendingToken); return 1; case TOK_FOR: ForStatement (); break; case TOK_GOTO: GotoStatement (); CheckSemi (PendingToken); return 1; case TOK_SEMI: /* Ignore it */ CheckSemi (PendingToken); break; case TOK_PRAGMA: DoPragma (); break; case TOK_CASE: CaseLabel (); CheckLabelWithoutStatement (); break; case TOK_DEFAULT: DefaultLabel (); CheckLabelWithoutStatement (); break; default: /* Remember the current code position */ GetCodePos (&Start); /* Actual statement */ ExprWithCheck (hie0, &Expr); /* Load the result only if it is an lvalue and the type is * marked as volatile. Otherwise the load is useless. */ if (ED_IsLVal (&Expr) && IsQualVolatile (Expr.Type)) { LoadExpr (CF_NONE, &Expr); } /* If the statement didn't generate code, and is not of type * void, emit a warning. */ GetCodePos (&End); if (CodeRangeIsEmpty (&Start, &End) && !IsTypeVoid (Expr.Type)) { Warning ("Statement has no effect"); } CheckSemi (PendingToken); } return 0; }
PTREE AsmStmt( void ) /*******************/ { boolean uses_auto; AUX_INFO *aux_info; unsigned skip_token; unsigned skip_alt_token; PTREE expr; TYPE fn_type; TYPE ret_type; SYMBOL sym; char *fn_name; auto VBUF code_buffer; ppstate_t save_ppstate; save_ppstate = PPState; PPState = PPS_EOL; PPStateAsm = TRUE; VbufInit( &code_buffer ); NextTokenSkipEOL(); AsmSysInit(); if( ( CurToken == T_LEFT_BRACE ) || ( CurToken == T_ALT_LEFT_BRACE ) ) { NextTokenSkipEOL(); for(;;) { getAsmLine( &code_buffer ); if( CurToken == T_RIGHT_BRACE ) break; if( CurToken == T_ALT_RIGHT_BRACE ) break; if( CurToken == T_EOF ) break; NextTokenSkipEOL(); } skip_token = T_RIGHT_BRACE; skip_alt_token = T_ALT_RIGHT_BRACE; } else { getAsmLine( &code_buffer ); skip_token = skip_alt_token = T_NULL; } PPStateAsm = FALSE; PPState = save_ppstate; if( ( CurToken == skip_token ) || ( CurToken == skip_alt_token ) ) { NextToken(); } if( AsmCodeAddress != 0 ) { fn_name = NameDummy(); aux_info = AsmSysCreateAux( fn_name ); uses_auto = AsmSysInsertFixups( &code_buffer ); if( uses_auto ) { AsmSysUsesAuto(); } AsmSysDone(); ret_type = GetBasicType( TYP_VOID ); fn_type = MakeModifiableFunction( ret_type, NULL ); fn_type->u.f.pragma = aux_info; fn_type = CheckDupType( fn_type ); sym = SymCreateFileScope( fn_type, SC_NULL, SF_NULL, fn_name ); LinkageSet( sym, "C" ); expr = genFnCall( fn_name ); } else { expr = NULL; } AsmSysFini(); VbufFree( &code_buffer ); return( expr ); }