bool isvalid(string &s){ if(s.size()==0){ return false; } bool hasdot=false; int dotpos=0; for(int i=0; i<s.size(); i++){ if(s[i]=='.'){ hasdot=true; dotpos=i; break; } } if(hasdot){ //s1.s2 string s1=s.substr(0,dotpos); string s2=s.substr(dotpos+1); if(s1.size()==0){ return isPureNumber(s2); } return isSign(s1)&&isPureNumber(s2); } return isSign(s); }
int main() { Node* cur = NULL; int buf = 0; FILE* f = fopen("test.txt", "r"); while (!feof(f)) { char symbol = fgetc(f); if (symbol != '(' && symbol != ' ') { if (isSign(symbol)) cur = addChar(cur, symbol); if (symbol == ')') cur = cur->parent; if (isDigit(symbol)) { ungetc(symbol, f); fscanf(f, "%d", &buf); cur = addValue(cur, buf); } } } while(cur->parent != NULL) cur = cur->parent; List *top = new List(); Stack *stack = new Stack(); stack->top = top; postorderPrint(cur, stack); printf("\n"); printf("result = %d\n", stack->top->next->value); clearStack(stack); }
int ASMParser::cvtNumString2Number(string s) // Converts a string to an integer. Assumes s is something like "-231" and produces -231 { if (!isNumberString(s)) { cerr << "Non-numberic string passed to cvtNumString2Number" << endl; return 0; } int k = 1; int val = 0; for (int i = s.length()-1; i>0; i--) { char c = s.at(i); val = val + k*((int)(c - '0')); k = k*10; } if (isSign(s.at(0))) { if (s.at(0) == '-') val = -1*val; } else { val = val + k*((int)(s.at(0) - '0')); } return val; }
bool Tokenizer::getNumber(const QString &str, int i, QString &numb) { // Examples of valid numbers are: // 1234 // +1234 // -1234 // -1234.99 // .99 // +.99 // -1234. numb.clear(); bool first = true; bool dotFound = false; for (; i < str.size(); ++i) { if (first && isSign(str, i)) { numb.append(str[i]); } else if (isDigit(str, i)) { numb.append(str[i]); } else if (!dotFound && isDot(str, i)) { numb.append(str[i]); dotFound = true; } else { break; } first = false; } return numb.size() > 0; }
int StringCalculator::calculateExpression(char string[]) { StackInterface* stackObject = new PointerStack(); makePolish(string, stackObject); //printf("%s\n", string); int i = 0; int length = strlen(string) + 1; int argument1 = 1; int argument2 = 1; int tmpResult = 0; for (i = 0; i < length; i++) { if (isNumber(string[i])) stackObject->push(convertToInt(string[i])); if (isSign(string[i])) { argument2 = stackObject->pop(); argument1 = stackObject->pop(); tmpResult = makeOperation(string[i], argument1, argument2); stackObject->push(tmpResult); } } int result = stackObject->pop(); delete stackObject; return result; }
int formTreeFromPrefixString(TreeNode* &node,int j,char string[],int reps) { if (reps == 0) { reps++; createNode(node,string[j]); createNode(node->left,0); createNode(node->right,0); j++; j = formTreeFromPrefixString(node->left,j,string,reps); j++; j = formTreeFromPrefixString(node->right,j,string,reps); } else if (isSign(string[j])) { node->value = string[j]; createNode(node->left,0); createNode(node->right,0); j++; j = formTreeFromPrefixString(node->left,j,string,reps); j++; j = formTreeFromPrefixString(node->right,j,string,reps); } else { node->value = string[j]; return j; } }
void parseNumber() { skipWhiteSpace(); while (!eof() && !isWhiteSpace() && (isSign() || isDot() || isDigit())) { put(); next(); } }
int calculateSubtree(TreeNode* &node) { if(isSign(node->value)) { return makeOperation(calculateSubtree(node->left),calculateSubtree(node->right),node->value); } else return node->value; }
bool Parser::isNumber(const QString & value) const { bool was_sign = false; if (value.isEmpty()) return false; if (isSign(value.data()[0])) was_sign = true; if (!was_sign && !isDigit(value.data()[0])) return false; if (was_sign && value.length() == 1) return false; for (int i = 1; i < value.length(); i++) if (!isDigit(value.data()[i])) return false; return true; }
bool isExp(const char* s, const char* e) { if (s>=e) return false; const char* b; for (b=s;b!=e;++b) if (*b=='e' || *b=='E') break; if (b==e) return isReal(s,e); if (!isReal(s,b)) return false; ++b; if (isSign(*b)) ++b; return isInt(b,e); }
/** * @param s the string that represents a number * @return whether the string is a valid number */ bool isNumber(string& s) { // Write your code here int i=0; int len=s.size(); //deal with leading space while(i<len && s[i]==' '){ i++; } if(i==len){ return false; } //deal with trailing space int j=len-1; while(j>=0 && s[j]==' '){ j--; } if(j<i){ return false; } string ss=s.substr(i,j-i+1); //find e pos int epos=0; bool hasE=false; for(int i=0; i<ss.size(); i++){ if(ss[i]=='e'){ hasE=true; epos=i; break; } } if(hasE){ //split over e pos string s1=ss.substr(0,epos); string s2=ss.substr(epos+1); //s1 may have dot but s2 must not have dot return isvalid(s1) && isSign(s2); } return isvalid(ss); }
int isFloatingConstant(unsigned char* s) { int i = 0, iLen; if (isHexadecimalDigit(s)) { i += 2; while (isHexadecimalDigit(s + i)) i++; if (*(s + i) == '.') i++; while (isHexadecimalDigit(s + i)) i++; if (*(s + i) == 'p' || *(s + i) == 'P') { i++; if (isSign(s + i)) i++; while (isDigit(s + i)) i++; } else return 0; } else if (isDigit(s)) { int isFractional = 0; i += 1; while (isDigit(s + i)) i++; if (*(s + i) == '.') { i++; isFractional = 1; } while (isDigit(s + i)) i++; if (*(s + i) == 'e' || *(s + i) == 'E') { i++; if (isSign(s + i)) i++; while (isDigit(s + i)) i++; } else if (!isFractional) return 0; } if (i && (iLen = isFloatingSuffix(s + i))) i += iLen; return i; }
bool ASMParser::isNumberString(string s) // Returns true if s represents a valid decimal integer { int len = s.length(); if (len == 0) return false; if ((isSign(s.at(0)) && len > 1) || isDigit(s.at(0))) { // check remaining characters for (int i=1; i < len; i++) { if (!isdigit(s.at(i))) return false; } return true; } return false; }
/** * ExponentPart: ExponentIndicator SignedInteger * ExponentIndicator: one of e E * SignedInteger: Sign(opt) Digits * Sign: one of + - * Returns the count of chars consumed. */ int LiteralSupport::consumeExponentPart(u32string &ss) { src->mark(); ss += src->getChar(); // consume ExponentIndicator if (isSign(src->peekChar())) { ss += src->getChar(); // consume Sign: '+' or '-' } int digitCount = consumeDigitsPOrUnderscores(ss, isDecimalDigit); if (digitCount > 0) { return digitCount; } // Error, we consumed the exponent indicator, possibly the sign but no digit // was consumed. We restore the source buffer and let the parser handle the // error. src->restore(); return 0; }
bool Parser::bracket() { if (*string == '(') { brCounter++; string++; if (isSign(*string)) string++; if (!addition()) return false; if (*string == 0) return false; if (*string == ')') brCounter--; else return false; string++; return true; } else return isNumber(); }
/** 把字符串转为int型 String to Integer (atoi) */ int myAtoi(char* str) { bool isSign(char c); bool isNum(char c); bool containSign=false; bool isFirst=true; int start=-1; long long result=0; long long maxInt=2147483647; if(strlen(str)==0) return 0; for(int i=0;i<strlen(str);i++){ if(str[i]==' '&&start<0) continue; //字符中的空格 if(isFirst){ //第一个非空格字符 isFirst=false; start=i; if(isSign(str[i])){ //是否是“+”,“-”号 containSign=true; //有符号 continue; } } if(isNum(str[i])) //依次处理每一个字符 result=result*10+(str[i]-48); else //遇到非数字停止 break; if(result>(maxInt+1)) break; //大于int表示的范围 } if(containSign&&str[start]==45){ //判断符号 result=-result; } if(result>maxInt) //比较结果是否在int的表示的范围内 return maxInt; else if(result<-(maxInt+1)) return -(maxInt+1); else return result; }
bool isReal(const char* s, const char* e) { if (s>=e) return false; if (isSign(*s)) ++s; const char* b; for (b=s;b!=e;++b) if (*b=='.') break; if (b==e) return isInt(s,e); const char *prev=(b==s)? b+1: b-1; const char *next=b+1; bool hasDigit = false; if (b!=s) { if (!isInt(s,b)) return false; hasDigit = true; } ++b; if (b!=e) { if (!isInt(b,e)) return false; hasDigit = true; } return hasDigit; }
bool isNumber(const char *s) { if (s == NULL) return false; int state = 0; int i = 0; while (s[i] != '\0') { switch (state) { case 0: // init if (s[i] == ' ') { // do nothing } else if (isSign(s[i])) { state = 1; } else if (isNum(s[i])) { state = 2; } else if (s[i] == '.') { state = 3; } else { return false; } break; case 1: // sign if (isNum(s[i])) { state = 2; } else if (s[i] == '.') { state = 3; } else { return false; } break; case 2: // num if (isNum(s[i])) { // do nothing } else if (s[i] == '.') { state = 4; } else if (s[i] == 'e') { state = 5; } else if (s[i] == ' ') { state = 9; } else { return false; } break; case 3: // start with '.' if (isNum(s[i])) { state = 6; } else { return false; } break; case 4: // num + '.' if (isNum(s[i])) { state = 6; } else if (s[i] == 'e') { state = 5; } else if (s[i] == ' ') { state = 9; } else { return false; } break; case 5: // 'e' if (isSign(s[i])) { state = 7; } else if (isNum(s[i])) { state = 8; } else { return false; } break; case 6: // '.' + num if (isNum(s[i])) { // do nothing } else if (s[i] == 'e') { state = 5; } else if (s[i] == ' ') { state = 9; } else { return false; } break; case 7: // sign after 'e' if (isNum(s[i])) { state = 8; } else { return false; } break; case 8: // num after 'e' if (isNum(s[i])) { // do nothing } else if (s[i] == ' ') { state = 9; } else { return false; } break; case 9: // trailing spaces if (s[i] != ' ') { return false; } break; } i++; } return (state == 2 || state == 4 || state == 6 || state == 8 || state == 9); }
/** reads an objective or constraint with name and coefficients */ static SCIP_RETCODE readCoefficients( SCIP* scip, /**< SCIP data structure */ LPINPUT* lpinput, /**< LP reading data */ SCIP_Bool isobjective, /**< indicates whether we are currently reading the coefficients of the objective */ char* name, /**< pointer to store the name of the line; must be at least of size * LP_MAX_LINELEN */ SCIP_VAR*** vars, /**< pointer to store the array with variables (must be freed by caller) */ SCIP_Real** coefs, /**< pointer to store the array with coefficients (must be freed by caller) */ int* ncoefs, /**< pointer to store the number of coefficients */ SCIP_Bool* newsection /**< pointer to store whether a new section was encountered */ ) { SCIP_Bool havesign; SCIP_Bool havevalue; SCIP_Real coef; int coefsign; int coefssize; assert(lpinput != NULL); assert(name != NULL); assert(vars != NULL); assert(coefs != NULL); assert(ncoefs != NULL); assert(newsection != NULL); *vars = NULL; *coefs = NULL; *name = '\0'; *ncoefs = 0; *newsection = FALSE; /* read the first token, which may be the name of the line */ if( getNextToken(scip, lpinput) ) { /* check if we reached a new section */ if( isNewSection(scip, lpinput) ) { *newsection = TRUE; return SCIP_OKAY; } /* remember the token in the token buffer */ swapTokenBuffer(lpinput); /* get the next token and check, whether it is a colon */ if( getNextToken(scip, lpinput) ) { if( strcmp(lpinput->token, ":") == 0 ) { /* the second token was a colon: the first token is the line name */ (void)SCIPmemccpy(name, lpinput->tokenbuf, '\0', LP_MAX_LINELEN); name[LP_MAX_LINELEN - 1] = '\0'; SCIPdebugMessage("(line %d) read constraint name: '%s'\n", lpinput->linenumber, name); } else { /* the second token was no colon: push the tokens back onto the token stack and parse them as coefficients */ pushToken(lpinput); pushBufferToken(lpinput); } } else { /* there was only one token left: push it back onto the token stack and parse it as coefficient */ pushBufferToken(lpinput); } } /* initialize buffers for storing the coefficients */ coefssize = LP_INIT_COEFSSIZE; SCIP_CALL( SCIPallocMemoryArray(scip, vars, coefssize) ); SCIP_CALL( SCIPallocMemoryArray(scip, coefs, coefssize) ); /* read the coefficients */ coefsign = +1; coef = 1.0; havesign = FALSE; havevalue = FALSE; *ncoefs = 0; while( getNextToken(scip, lpinput) ) { SCIP_VAR* var; /* check if we read a sign */ if( isSign(lpinput, &coefsign) ) { SCIPdebugMessage("(line %d) read coefficient sign: %+d\n", lpinput->linenumber, coefsign); havesign = TRUE; continue; } /* check if we read a value */ if( isValue(scip, lpinput, &coef) ) { SCIPdebugMessage("(line %d) read coefficient value: %g with sign %+d\n", lpinput->linenumber, coef, coefsign); if( havevalue ) { syntaxError(scip, lpinput, "two consecutive values."); return SCIP_OKAY; } havevalue = TRUE; continue; } /* check if we reached an equation sense */ if( isSense(lpinput, NULL) ) { if( isobjective ) { syntaxError(scip, lpinput, "no sense allowed in objective"); return SCIP_OKAY; } /* put the sense back onto the token stack */ pushToken(lpinput); break; } /* check if we reached a new section, that will be only allowed when having no current sign and value and if we * are not in the quadratic part */ if( (isobjective || (!havevalue && !havesign)) && isNewSection(scip, lpinput) ) { if( havesign && !havevalue ) { SCIPwarningMessage(scip, "skipped single sign %c without value or variable in objective\n", coefsign == 1 ? '+' : '-'); } else if( isobjective && havevalue && !SCIPisZero(scip, coef) ) { SCIPwarningMessage(scip, "constant term %+g in objective is skipped\n", coef * coefsign); } *newsection = TRUE; return SCIP_OKAY; } /* check if we start a quadratic part */ if( *lpinput->token == '[' ) { syntaxError(scip, lpinput, "diff reader does not support quadratic objective function."); return SCIP_READERROR; } /* all but the first coefficient need a sign */ if( *ncoefs > 0 && !havesign ) { syntaxError(scip, lpinput, "expected sign ('+' or '-') or sense ('<' or '>')."); return SCIP_OKAY; } /* check if the last variable should be squared */ if( *lpinput->token == '^' ) { syntaxError(scip, lpinput, "diff reader does not support quadratic objective function."); return SCIP_READERROR; } else { /* the token is a variable name: get the corresponding variable */ SCIP_CALL( getVariable(scip, lpinput->token, &var) ); } /* insert the linear coefficient */ SCIPdebugMessage("(line %d) read linear coefficient: %+g<%s>\n", lpinput->linenumber, coefsign * coef, SCIPvarGetName(var)); if( !SCIPisZero(scip, coef) ) { /* resize the vars and coefs array if needed */ if( *ncoefs >= coefssize ) { coefssize *= 2; coefssize = MAX(coefssize, (*ncoefs)+1); SCIP_CALL( SCIPreallocMemoryArray(scip, vars, coefssize) ); SCIP_CALL( SCIPreallocMemoryArray(scip, coefs, coefssize) ); } assert(*ncoefs < coefssize); /* add coefficient */ (*vars)[*ncoefs] = var; (*coefs)[*ncoefs] = coefsign * coef; (*ncoefs)++; } /* reset the flags and coefficient value for the next coefficient */ coefsign = +1; coef = 1.0; havesign = FALSE; havevalue = FALSE; } return SCIP_OKAY; }
/* if prefix is omitted: if PFX_OPT set return NULL, otherwise use longjmp */ extern prefix * read_prefix(unsigned pfx_flags) { bool f_optional = !!(pfx_flags & PFX_OPT); bool fSurvey = !!(pfx_flags & PFX_SURVEY); bool fSuspectTypo = !!(pfx_flags & PFX_SUSPECT_TYPO); prefix *back_ptr, *ptr; char *name; size_t name_len = 32; size_t i; bool fNew; bool fImplicitPrefix = fTrue; int depth = -1; filepos fp_firstsep; skipblanks(); #ifndef NO_DEPRECATED if (isRoot(ch)) { if (!(pfx_flags & PFX_ALLOW_ROOT)) { compile_diagnostic(DIAG_ERR|DIAG_COL, /*ROOT is deprecated*/25); LONGJMP(file.jbSkipLine); } if (root_depr_count < 5) { compile_diagnostic(DIAG_WARN|DIAG_COL, /*ROOT is deprecated*/25); if (++root_depr_count == 5) compile_diagnostic(DIAG_WARN, /*Further uses of this deprecated feature will not be reported*/95); } nextch(); ptr = root; if (!isNames(ch)) { if (!isSep(ch)) return ptr; /* Allow optional SEPARATOR after ROOT */ get_pos(&fp_firstsep); nextch(); } fImplicitPrefix = fFalse; #else if (0) { #endif } else { if ((pfx_flags & PFX_ANON) && (isSep(ch) || (pcs->dash_for_anon_wall_station && ch == '-'))) { int first_ch = ch; filepos here; get_pos(&here); nextch(); if (isBlank(ch) || isEol(ch)) { if (!isSep(first_ch)) goto anon_wall_station; /* A single separator alone ('.' by default) is an anonymous * station which is on a point inside the passage and implies * the leg to it is a splay. */ if (TSTBIT(pcs->flags, FLAGS_ANON_ONE_END)) { set_pos(&here); compile_diagnostic(DIAG_ERR|DIAG_TOKEN, /*Can't have a leg between two anonymous stations*/3); LONGJMP(file.jbSkipLine); } pcs->flags |= BIT(FLAGS_ANON_ONE_END) | BIT(FLAGS_IMPLICIT_SPLAY); return new_anon_station(); } if (isSep(first_ch) && ch == first_ch) { nextch(); if (isBlank(ch) || isEol(ch)) { /* A double separator ('..' by default) is an anonymous station * which is on the wall and implies the leg to it is a splay. */ prefix * pfx; anon_wall_station: if (TSTBIT(pcs->flags, FLAGS_ANON_ONE_END)) { set_pos(&here); compile_diagnostic(DIAG_ERR|DIAG_TOKEN, /*Can't have a leg between two anonymous stations*/3); LONGJMP(file.jbSkipLine); } pcs->flags |= BIT(FLAGS_ANON_ONE_END) | BIT(FLAGS_IMPLICIT_SPLAY); pfx = new_anon_station(); pfx->sflags |= BIT(SFLAGS_WALL); return pfx; } if (ch == first_ch) { nextch(); if (isBlank(ch) || isEol(ch)) { /* A triple separator ('...' by default) is an anonymous * station, but otherwise not handled specially (e.g. for * a single leg down an unexplored side passage to a station * which isn't refindable). */ if (TSTBIT(pcs->flags, FLAGS_ANON_ONE_END)) { set_pos(&here); compile_diagnostic(DIAG_ERR|DIAG_TOKEN, /*Can't have a leg between two anonymous stations*/3); LONGJMP(file.jbSkipLine); } pcs->flags |= BIT(FLAGS_ANON_ONE_END); return new_anon_station(); } } } set_pos(&here); } ptr = pcs->Prefix; } i = 0; name = NULL; do { fNew = fFalse; if (name == NULL) { /* Need a new name buffer */ name = osmalloc(name_len); } /* i==0 iff this is the first pass */ if (i) { i = 0; nextch(); } while (isNames(ch)) { if (i < pcs->Truncate) { /* truncate name */ name[i++] = (pcs->Case == LOWER ? tolower(ch) : (pcs->Case == OFF ? ch : toupper(ch))); if (i >= name_len) { name_len = name_len + name_len; name = osrealloc(name, name_len); } } nextch(); } if (isSep(ch)) { fImplicitPrefix = fFalse; get_pos(&fp_firstsep); } if (i == 0) { osfree(name); if (!f_optional) { if (isEol(ch)) { if (fSurvey) { compile_diagnostic(DIAG_ERR|DIAG_COL, /*Expecting survey name*/89); } else { compile_diagnostic(DIAG_ERR|DIAG_COL, /*Expecting station name*/28); } } else { /* TRANSLATORS: Here "station" is a survey station, not a train station. */ compile_diagnostic(DIAG_ERR|DIAG_COL, /*Character “%c” not allowed in station name (use *SET NAMES to set allowed characters)*/7, ch); } LONGJMP(file.jbSkipLine); } return (prefix *)NULL; } name[i++] = '\0'; back_ptr = ptr; ptr = ptr->down; if (ptr == NULL) { /* Special case first time around at each level */ name = osrealloc(name, i); ptr = osnew(prefix); ptr->ident = name; name = NULL; ptr->right = ptr->down = NULL; ptr->pos = NULL; ptr->shape = 0; ptr->stn = NULL; ptr->up = back_ptr; ptr->filename = file.filename; ptr->line = file.line; ptr->min_export = ptr->max_export = 0; ptr->sflags = BIT(SFLAGS_SURVEY); if (fSuspectTypo && !fImplicitPrefix) ptr->sflags |= BIT(SFLAGS_SUSPECTTYPO); back_ptr->down = ptr; fNew = fTrue; } else { /* Use caching to speed up adding an increasing sequence to a * large survey */ static prefix *cached_survey = NULL, *cached_station = NULL; prefix *ptrPrev = NULL; int cmp = 1; /* result of strcmp ( -ve for <, 0 for =, +ve for > ) */ if (cached_survey == back_ptr) { cmp = strcmp(cached_station->ident, name); if (cmp <= 0) ptr = cached_station; } while (ptr && (cmp = strcmp(ptr->ident, name))<0) { ptrPrev = ptr; ptr = ptr->right; } if (cmp) { /* ie we got to one that was higher, or the end */ prefix *newptr; name = osrealloc(name, i); newptr = osnew(prefix); newptr->ident = name; name = NULL; if (ptrPrev == NULL) back_ptr->down = newptr; else ptrPrev->right = newptr; newptr->right = ptr; newptr->down = NULL; newptr->pos = NULL; newptr->shape = 0; newptr->stn = NULL; newptr->up = back_ptr; newptr->filename = file.filename; newptr->line = file.line; newptr->min_export = newptr->max_export = 0; newptr->sflags = BIT(SFLAGS_SURVEY); if (fSuspectTypo && !fImplicitPrefix) newptr->sflags |= BIT(SFLAGS_SUSPECTTYPO); ptr = newptr; fNew = fTrue; } cached_survey = back_ptr; cached_station = ptr; } depth++; f_optional = fFalse; /* disallow after first level */ if (isSep(ch)) get_pos(&fp_firstsep); } while (isSep(ch)); if (name) osfree(name); /* don't warn about a station that is referred to twice */ if (!fNew) ptr->sflags &= ~BIT(SFLAGS_SUSPECTTYPO); if (fNew) { /* fNew means SFLAGS_SURVEY is currently set */ SVX_ASSERT(TSTBIT(ptr->sflags, SFLAGS_SURVEY)); if (!fSurvey) { ptr->sflags &= ~BIT(SFLAGS_SURVEY); if (TSTBIT(pcs->infer, INFER_EXPORTS)) ptr->min_export = USHRT_MAX; } } else { /* check that the same name isn't being used for a survey and station */ if (fSurvey ^ TSTBIT(ptr->sflags, SFLAGS_SURVEY)) { /* TRANSLATORS: Here "station" is a survey station, not a train station. * * Here "survey" is a "cave map" rather than list of questions - it should be * translated to the terminology that cavers using the language would use. */ compile_diagnostic(DIAG_ERR, /*“%s” can’t be both a station and a survey*/27, sprint_prefix(ptr)); } if (!fSurvey && TSTBIT(pcs->infer, INFER_EXPORTS)) ptr->min_export = USHRT_MAX; } /* check the export level */ #if 0 printf("R min %d max %d depth %d pfx %s\n", ptr->min_export, ptr->max_export, depth, sprint_prefix(ptr)); #endif if (ptr->min_export == 0 || ptr->min_export == USHRT_MAX) { if (depth > ptr->max_export) ptr->max_export = depth; } else if (ptr->max_export < depth) { prefix *survey = ptr; char *s; const char *p; int level; for (level = ptr->max_export + 1; level; level--) { survey = survey->up; SVX_ASSERT(survey); } s = osstrdup(sprint_prefix(survey)); p = sprint_prefix(ptr); if (survey->filename) { compile_diagnostic_pfx(DIAG_ERR, survey, /*Station “%s” not exported from survey “%s”*/26, p, s); } else { compile_diagnostic(DIAG_ERR, /*Station “%s” not exported from survey “%s”*/26, p, s); } osfree(s); #if 0 printf(" *** pfx %s warning not exported enough depth %d " "ptr->max_export %d\n", sprint_prefix(ptr), depth, ptr->max_export); #endif } if (!fImplicitPrefix && (pfx_flags & PFX_WARN_SEPARATOR)) { filepos fp_tmp; get_pos(&fp_tmp); set_pos(&fp_firstsep); compile_diagnostic(DIAG_WARN|DIAG_COL, /*Separator in survey name*/392); set_pos(&fp_tmp); } return ptr; } /* if numeric expr is omitted: if f_optional return HUGE_REAL, else longjmp */ static real read_number(bool f_optional) { bool fPositive, fDigits = fFalse; real n = (real)0.0; filepos fp; int ch_old; get_pos(&fp); ch_old = ch; fPositive = !isMinus(ch); if (isSign(ch)) nextch(); while (isdigit(ch)) { n = n * (real)10.0 + (char)(ch - '0'); nextch(); fDigits = fTrue; } if (isDecimal(ch)) { real mult = (real)1.0; nextch(); while (isdigit(ch)) { mult *= (real).1; n += (char)(ch - '0') * mult; fDigits = fTrue; nextch(); } } /* !'fRead' => !fDigits so fDigits => 'fRead' */ if (fDigits) return (fPositive ? n : -n); /* didn't read a valid number. If it's optional, reset filepos & return */ set_pos(&fp); if (f_optional) { return HUGE_REAL; } if (isOmit(ch_old)) { compile_diagnostic(DIAG_ERR|DIAG_COL, /*Field may not be omitted*/8); } else { compile_diagnostic_token_show(DIAG_ERR, /*Expecting numeric field, found “%s”*/9); } LONGJMP(file.jbSkipLine); return 0.0; /* for brain-fried compilers */ }
bool Parser::isCorrectExpression() { if (isSign(*string)) string++; return addition(); }
bool ExpressionCell::_compute() { if (this->computed) return this->error ? false : true; if (data[0]!='=') { this->error = true; this->computed = true; this->data = "#parce_expr_error"; return false; } enum {EQUAL='=', PLUS='+', MINUS='-', MULTIPLICATION='*', DIVISION='\\'} signState=EQUAL; int leftValue = 0; int rightArgBegin = 1; for (unsigned int i=1; i<data.size()+1; i++) { if ( (i == data.size()-1) || isSign(data[i]) ) { int rightValue = 0; string rightArg = data.substr(rightArgBegin, i-1); if (isNumberString(rightArg)) rightValue = atoi(rightArg.c_str()); else if (isCellString(rightArg)) { pair<int, int> cellCoord = parseCellCoordinate(rightArg); Cell *cell = getCell(cellCoord.first, cellCoord.second); // if cell not found or cell can't be computed => error if (cell == NULL || !cell->compute() || !cell->isNumber()) { this->error = true; this->computed = true; this->data = "#incorrect_cell_"+rightArg; return false; } rightValue = cell->getNumber(); } // Compute operation switch (signState) { case EQUAL: leftValue = rightValue; break; case PLUS: leftValue += rightValue; break; case MINUS: leftValue -= rightValue; break; case MULTIPLICATION: leftValue *= rightValue; break; case DIVISION: if (rightValue == 0) { this->error = true; this->computed = true; this->data = "#division_by_zero"; return false; } leftValue /= rightValue; break; } } if ( i == data.size()-1 ) break; // set next sing if (data[i] == '+') signState = PLUS; if (data[i] == '-') signState = MINUS; if (data[i] == '*') signState = MULTIPLICATION; if (data[i] == '/') signState = DIVISION; } this->error = false; this->computed = true; this->data = std::to_string(leftValue); this->data_int = leftValue; return true; }
/** * The string stream contains the value '0x' or '0X'. * @returns HEX_NUMERAL | * HEX_NUMERAL_WITH_INT_TYPE_SUFFIX | * HEXADECIMAL_FLOATING_POINT_LITERAL | * ERROR */ LiteralToken LiteralSupport::getHexNumeral(u32string &ss) { // We save the start position of the numeral for error diagnosis. int start = src->getCursor() - 2; // Lookahead and confirm that we have valid hex digit. if (!(isHexDigit(src->peekChar()) || src->peekChar() == '.')) { diag->addErr(c4::ERR_NVAL_HEX, start, src->getCursor()); return LiteralToken::ERROR; } bool seenPeriod = false; if (src->peekChar() == '.') { if (!isHexDigit(src->peekChar(1))) { src->ungetChar(2); diag->addErr(c4::ERR_NVAL_HEX, start, src->getCursor()); return LiteralToken::ERROR; } ss += src->getChar(); // consume '.' seenPeriod = true; } // Consume whole or fractional digits consumeDigitsPOrUnderscores(ss, isHexDigit); if (!seenPeriod) { if (src->peekChar() == '.') { ss += src->getChar(); // consume '.' seenPeriod = true; } // Consume fractional digits consumeDigitsPOrUnderscores(ss, isHexDigit); } // If we didn't see '.' and the next char is not a binary exponent indicator // we know that this is an integer. if (!seenPeriod && !isBinaryExponentIndicator(src->peekChar())) { // Check int type suffix char peek = src->peekChar(); if (isIntegerTypeSuffix(peek)) { ss += src->getChar(); // append and consume suffix return LiteralToken::HEX_NUMERAL_WITH_INT_TYPE_SUFFIX; } return LiteralToken::HEX_NUMERAL; } // We have a floating point. // The binary exponent indicator is mandatory. if (!isBinaryExponentIndicator(src->peekChar())) { diag->addErr(c4::ERR_NVAL_HEX, start, src->getCursor()); return LiteralToken::ERROR; } // Consume the binary exponent indicator: 'p' or 'P' ss += src->getChar(); // Sign(opt) if (isSign(src->peekChar())) { ss += src->getChar(); // consume '+' or '-' } // Digits int digitCount = consumeDigitsPOrUnderscores(ss, isDecimalDigit); if (digitCount <= 0) { // Invalid or missing Signed integer diag->addErr(c4::ERR_NVAL_HEX, start, src->getCursor()); return LiteralToken::ERROR; } // FloatTypeSuffix(opt) if (isFloatTypeSuffix(src->peekChar())) { ss += src->getChar(); // consume one of: 'f', 'F', 'd' or 'D' } return LiteralToken::HEXADECIMAL_FLOATING_POINT_LITERAL; }
int scan(){ memset(string_attr,'\0',strlen(string_attr)); num_attr=-1; int trigger[6]={0}; //trigger of {string,number,sign,',/**/,{}} int wordsCount=0; //counter of words in token int resultToken=0; //temp token int check=0; //get "check~"function returns int isSep,isDef,isCom; //get "is~"function returns if (lineCountTrigger==SET){ //when check some word, it feedback new line count lastLineNumber++; lineCountTrigger=RESET; } if(word==EOF){ //EOF return -1; }else if((isSep=isSeparater(word))!=0){ //line, tab or space word=fgetc(fp); return 0; //skip }else if(isprint(word)==0){ //leave out not printable words error("cannot print the word"); }else if(islower(word)!=0||isupper(word)!=0){ //NAME resultToken=TNAME; string_attr[wordsCount++]=word; word=fgetc(fp); trigger[0]=SET; }else if(isdigit(word)!=0){ //Natural Number resultToken=TNUMBER; string_attr[wordsCount++]=word; num_attr=atoi(string_attr); word=fgetc(fp); trigger[1]=SET; }else if((resultToken=isSign(word))!=0){ //Sign string_attr[wordsCount++]=word; word=fgetc(fp); trigger[2]=SET; }else if((isDef=isDefString(word))!=0){ //'___' start resultToken=TSTRING; word=fgetc(fp); //next word is first count trigger[3]=SET; }else if((isCom=isComment(word))=='/'){ //comment out start /*___*/ word=fgetc(fp); //next word is first count trigger[4]=SET; }else if((isCom=isComment(word))=='{'){ //comment out start {___} word=fgetc(fp); //next word is first count trigger[5]=SET; }else{ //except?? fprintf(stderr,"Something Bug words or not define\n"); return -2; } while(1){ if(word==EOF){ //EOF if((check=checkToken(string_attr))<0){ return resultToken; } return check; }else if(trigger[0]==SET){ //NAME or TOKEN if(wordsCount>MAXSTRSIZE-1){ error("syntax err: too long string\n"); }else if(islower(word)!=0||isupper(word)!=0||isdigit(word)!=0){ string_attr[wordsCount++]=word; word=fgetc(fp); }else{ if((check=checkToken(string_attr))<0){ return resultToken; } return check; } }else if(trigger[1]==SET){ //NUMBER if(isdigit(word)!=0){ string_attr[wordsCount++]=word; if((num_attr=atoi(string_attr))>32767){ error("syntax err: number<=32767"); } word=fgetc(fp); }else{ return resultToken; } }else if(trigger[2]==SET){ //sign by two words if(isSign(word)!=0){ string_attr[1]=word; check=checkWSign(string_attr); if(check<0){ string_attr[1]='\0'; return resultToken; }else{ word=fgetc(fp); return check; } }else{ return resultToken; } }else if(trigger[3]==SET){ //string '__' if(isprint(word)==0&&(isSep=isSeparater(word))==0){ error("syntax err: about STRING start"); }else if(isDefString(word)!=0){ if((word=fgetc(fp))!='\''){ return resultToken; }else{ string_attr[wordsCount++]=word; //this is one before "\'" } }else if(isSep<0){ error("not permission new line in STRING"); } string_attr[wordsCount++]=word; word=fgetc(fp); }else if(trigger[4]==SET){ //comment out /**/ if(wordsCount==0){ if(word!='*'){ error("syntax err: about comment out start"); } word=fgetc(fp); } if(word=='*'){ if((word=fgetc(fp))=='/'){ word=fgetc(fp); return 0; //coment out end } string_attr[wordsCount++]='*'; } if(isprint(word)!=0||isSeparater(word)!=0){ string_attr[wordsCount++]=word; word=fgetc(fp); }else if(word==EOF){ fprintf(stdout,"syntax err: comment out not END\n"); return 0; }else{ error("cannot print"); } }else if(trigger[5] == SET){ //comment out {} if(word=='{'){ error("comment out in comment"); }else if(word=='}'){ word=fgetc(fp); return 0; //coment out end } if(isprint(word)!=0||isSeparater(word)!=0){ string_attr[wordsCount++]=word; word=fgetc(fp); }else if(word==EOF){ fprintf(stdout,"syntax err: comment out not END\n"); return 0; }else{ error("cannot print"); } }else{ //except?? error("Something Bug words or not define"); return -2; } } return -2; }
void StringCalculator::makePolish(char normal[], StackInterface* &stack) { int newLength = strlen(normal) + 1; char tmp[newLength]; for (int y = 0 ; y < newLength; y++) { tmp[y] = '\0'; } int u = 0; int v = 0; for (u = 0; u < newLength; u++) { if (isNumber(normal[u])) { tmp[v] = normal[u]; v++; } else { if (isSign(normal[u])) { if (polishPriority(normal[u]) > polishPriority(char(stack->top()))) { stack->push(normal[u]); } else { while (polishPriority(normal[u]) <= polishPriority(char(stack->top()))) { tmp[v] = stack->pop(); v++; } stack->push(normal[u]); } } else { if (polishPriority(normal[u]) == openBracketPrirority) stack->push(normal[u]); else { while ((polishPriority(char(stack->top())) != openBracketPrirority) && ((polishPriority(char(stack->top())) != otherPriority))) { tmp[v] = char(stack->pop()); v++; } //Deleting the opening bracket, because we do not need it stack->pop(); } } } } // Finish the line tmp[v] = '\0'; // Replacing the infix version of the string by the polish one for (int j = 0; j <= v; j++) { normal[j] = tmp[j]; } }
void Tokenizer::shift() { mpCurrent.reset(); if (mBlockComment) { skipEOL(); } else { skipWhiteSpaces(); if (mpInput->eof()) return; } mpCurrent.reset(new Token); mpCurrent->setLine(line()); mpCurrent->setBeginColumn(column()); if (mBlockComment) { consumeCStyleBlockComment(); return; } auto ch = mpInput->get(); if (isLetter(ch) || isUnderscore(ch)) { consumeIdentifier(ch); } else if (isBiwiseOperatorSymbol(ch)) { mpCurrent->setType(Token::TYPE_BITWISE_OPERATOR); absorbed(ch); mpCurrent->addChar(ch); mpCurrent->setEndColumn(column()); } else if (isDot(ch) && consumeDot(ch)) { // nothing } else if ((isDecimalDigit(ch) || isDot(ch) || isSign(ch)) && consumeNumber(ch)) { // nothing } else if (isQuotationMark(ch)) { if (!consumeString(ch)) shift(); } else if (isCStyleInitialCommentChar(ch)) { consumeComment(ch); } else if (isArrowSymbol(ch) && consumeArrow(ch)) { // nothing } else if (isBracket(ch)) { mpCurrent->setType(Token::TYPE_BRACKET); absorbed(ch); mpCurrent->addChar(ch); mpCurrent->setEndColumn(column()); } else if (isAngleBracket(ch)) { mpCurrent->setType(Token::TYPE_ANGLE_BRACKET); absorbed(ch); mpCurrent->addChar(ch); mpCurrent->setEndColumn(column()); } else if (isDelimiter(ch)) { mpCurrent->setType(Token::TYPE_DELIMITER); absorbed(ch); mpCurrent->addChar(ch); mpCurrent->setEndColumn(column()); } else if (isOperator(ch) && consumeEqualOperator(ch)) { // nothing } else if (isOperator(ch)) { mpCurrent->setType(Token::TYPE_OPERATOR); absorbed(ch); mpCurrent->addChar(ch); mpCurrent->setEndColumn(column()); } else if (isAsterisk(ch)) { mpCurrent->setType(Token::TYPE_ASTERISK); absorbed(ch); mpCurrent->addChar(ch); mpCurrent->setEndColumn(column()); } else { mpCurrent.reset(); } }
bool isDouble(char *&ch) { States state = start; while (true) { switch (state) { case start: { if (isSign(*ch)) state = sign; else if (isdigit(*ch)) state = intPart; else return false; break; } case sign:{ if (isdigit(*ch)) state = intPart; else return false; break; } case intPart: { if (isdigit(*ch)) break; else if (*ch == '.') state = point; else if (isExponent(*ch)) state = exponent; else return true; break; } case point: { if (isdigit(*ch)) state = frctPart; else return false; break; } case frctPart: { if (isdigit(*ch)) break; else if (isExponent(*ch)) state = exponent; else return true; break; } case exponent: { if (isSign(*ch)) state = expSign; else if (isdigit(*ch)) state = expValue; else return false; break; } case expSign: { if (isdigit(*ch)) state = expValue; else return false; break; } case expValue: { if (isdigit(*ch)) break; else return true; break; } } ch++; } }
bool Tokenizer::consumeNumber(std::streambuf::int_type ch) { int count = 0; if (isSign(ch)) { bool number = false; while (!eof()) { ++count; auto nch = mpInput->get(); if (isWhitespace(nch)) continue; number = isDecimalDigit(nch); break; } if (count) mpInput->clear(); for (int i = 0; i < count; ++i) mpInput->unget(); if (!number) return false; } absorbed(ch); mpCurrent->addChar(ch); for (int i = 0; i < count; ++i) { auto nch = mpInput->get(); absorbed(nch); mpCurrent->addChar(nch); } bool bDot = false; if (isDot(ch)) { bDot = true; mpCurrent->setType(Token::TYPE_REAL_LITERAL); } else { mpCurrent->setType(Token::TYPE_INTEGER_LITERAL); if (!eof() && isZero(ch)) { ch = mpInput->get(); if (isHexIndicator(ch)) { if (eof()) { mpMessageCollector->addMessage( Message::SEVERITY_ERROR, Message::t_invalidIntegerLiteral, mpSourceId, mpCurrent->line(), mpCurrent->beginColumn()); mpCurrent.reset(); return false; } mpCurrent->addChar(ch); absorbed(ch); while (!eof()) { ch = mpInput->get(); if (isNonHexicalLetter(ch) || isUnderscore(ch) || isDot(ch)) { mpMessageCollector->addMessage(Message::SEVERITY_ERROR, Message::t_invalidIntegerLiteral, mpSourceId, mpCurrent->line(), mpCurrent->beginColumn()); mpCurrent.reset(); return false; } if (!isHexicalDigit(ch)) { mpInput->clear(); mpInput->unget(); break; } absorbed(ch); mpCurrent->addChar(ch); } mpCurrent->setEndColumn(column()); return true; } for (;;) { if ( isLetter(ch) || isDot(ch) || isNonOctalDecimalDigit(ch) || isUnderscore(ch)) { mpMessageCollector->addMessage( Message::SEVERITY_ERROR, Message::t_invalidIntegerLiteral, mpSourceId, mpCurrent->line(), mpCurrent->beginColumn()); mpCurrent.reset(); return false; } if (!isOctalDigit(ch)) { mpInput->clear(); mpInput->unget(); break; } absorbed(ch); mpCurrent->addChar(ch); if (eof()) { break; } ch = mpInput->get(); } mpCurrent->setEndColumn(column()); return true; } } bool bExponent = false; while (!eof()) { ch = mpInput->get(); if (isExponent(ch)) { if (bExponent) { mpMessageCollector->addMessage( Message::SEVERITY_ERROR, Message::t_invalidIntegerLiteral, mpSourceId, mpCurrent->line(), mpCurrent->beginColumn()); mpCurrent.reset(); return false; } bExponent = true; mpCurrent->setType(Token::TYPE_REAL_LITERAL); absorbed(ch); mpCurrent->addChar(ch); ch = mpInput->get(); if (isSign(ch)) { mpCurrent->setType(Token::TYPE_REAL_LITERAL); absorbed(ch); mpCurrent->addChar(ch); } else { mpInput->clear(); mpInput->unget(); } continue; } if (isLetter(ch) || isUnderscore(ch)) { mpMessageCollector->addMessage( Message::SEVERITY_ERROR, Message::t_invalidIntegerLiteral, mpSourceId, mpCurrent->line(), mpCurrent->beginColumn()); mpCurrent.reset(); return false; } if (isDot(ch)) { if (bExponent || bDot) { mpMessageCollector->addMessage( Message::SEVERITY_ERROR, Message::t_invalidIntegerLiteral, mpSourceId, mpCurrent->line(), mpCurrent->beginColumn()); mpCurrent.reset(); return false; } bDot = true; mpCurrent->setType(Token::TYPE_REAL_LITERAL); absorbed(ch); mpCurrent->addChar(ch); continue; } if (!isDecimalDigit(ch)) { mpInput->clear(); mpInput->unget(); break; } absorbed(ch); mpCurrent->addChar(ch); } mpCurrent->setEndColumn(column()); return true; }