Exemplo n.º 1
0
// _____________________________________________________________________________
void QueryPlanner::getVarTripleMap(
    const ParsedQuery& pq,
    unordered_map<string, vector<SparqlTriple>>& varToTrip,
    unordered_set<string>& contextVars) const {
  for (auto& t: pq._whereClauseTriples) {
    if (isVariable(t._s)) {
      varToTrip[t._s].push_back(t);
    }
    if (isVariable(t._p)) {
      varToTrip[t._p].push_back(t);
    }
    if (isVariable(t._o)) {
      varToTrip[t._o].push_back(t);
    }

    if (t._p == IN_CONTEXT_RELATION) {
      if (isVariable(t._s) || isWords(t._o)) {
        contextVars.insert(t._s);
      }
      if (isVariable(t._o) || isWords(t._s)) {
        contextVars.insert(t._o);
      }
    }
  }
}
Exemplo n.º 2
0
/** Calculates a number-operator-number sequence.
  * operatorLine is the line in the middle.
  * Replaces the three lines with a single Line containing the result of the calculation.
  */
 void Calculator::calculateSubExpression(QStringList & expressionParts, int operatorLine)
 {
    double number1 = 0.0;
    double number2 = 0.0;
    double result = 0.0;
    bool ok = true;

    //check expression syntax
    if(operatorLine == 0 || operatorLine >= expressionParts.size())
        throw ExExpressionError(tr("Invalid expression. Wrong operator position."));
    QString op = expressionParts[operatorLine];

    // check numbers
    QString operand1 = expressionParts[operatorLine -1];
    if(isVariable(operand1))
        number1 = getVariableValue(operand1);
    else number1 = operand1.toDouble( &ok );
    if(!ok)
        throw ExExpressionError(tr("Invalid number format:") + " " + expressionParts[operatorLine - 1]);

    QString operand2 = expressionParts[operatorLine + 1];
    if(isVariable(operand2))
        number2 = getVariableValue(operand2);
    else number2 = operand2.toDouble( &ok );
    if(!ok)
        throw ExExpressionError(tr("Invalid number format:") + " " + expressionParts[operatorLine + 1]);

    //perform calculation
    if(op == "+")
        result = number1 + number2;
    else if(op == "-")
        result = number1 - number2;
    else if(op == "-")
        result = number1 - number2;
    else if(op == "*")
        result = number1 * number2;
    else if(op == "/")
    {
        if(number2 == 0.0)
           throw ExExpressionError(tr("Can not divide by zero."));
        else result = number1 / number2;
        if(abs(result) > 1e12)
            throw ExExpressionError(tr("Can not divide by zero."));
    }
    else if(op == "^")
       result = pow(number1, number2);
    //convert to string, copy to first line and remove line 2 and 3
    QString sResult = QString::number(result, 'G');
    expressionParts[operatorLine - 1] = sResult;
    expressionParts.removeAt(operatorLine);
    expressionParts.removeAt(operatorLine);
 }
Exemplo n.º 3
0
void Parser::processAssignment(std::pair<int,string> pair, list<int>& modifiesList, list<int>& usesList) {
	string str = pair.second;
	int stmtNumber = pair.first;
	string::iterator it;
	string variable = "";

	modifiesList.clear();
	usesList.clear();

	for (it = str.begin(); it != str.end(); ++it) {
		if (isMathSymbol(*it) || isSemicolon(*it)) {
			if (isVariable(variable)) {
				VarTable& varTable = pkb.getVarTable();
				int varID = varTable.get_ID(variable);
				
				if (modifiesList.empty()) {
					modifiesList.push_back(varID);
				}
				else {
					usesList.push_back(varID);
				}
			}
			variable = "";
		}
		else {
			variable += *it;
		}
	}
}
Exemplo n.º 4
0
void SymbolCheckVisitor::visit(ASTExpression& ast)
{
   mCurrentType.clear();

   ast.getLeft().accept(*this);

   if ( ast.hasRight() )
   {
      ASTType lefttype = mCurrentType;

      mCurrentType.clear();

      if ( isVariable(ast.getLeft()) )
      {
         ast.getRight().accept(*this);

         if ( !mCurrentType.greater(lefttype) )
         {
            error(E0020, UTEXT("Invalid type for assignment. Can not assign ") + mCurrentType.toString() + UTEXT(" to ") + lefttype.toString(), ast);
         }
      }
      else
      {
         error(E0021, UTEXT("Can only assign to variables."), ast);
      }
   }
}
Exemplo n.º 5
0
int getop(char s [])
{
	int c, res;
	while ((s[0] = c = getch()) == ' ' || c == '\t');

	s[1] = '\0';

	if (isCommand(s))
		return COMMAND;
	res = isNumber(s);
	if (res)
		return res;
	if (isAssigner(s))
		return ASSIGNER;
	if (isVariable(s))
		return VARIABLE;
	if (isOperator(s))
		return OPERATOR;
	res = isFunction(s);
	if (res)
		return res;
	if (s[0] == '\n')
		return '\n';
	if (c == EOF)
		return EOF;
	return ERROR;
}
Exemplo n.º 6
0
void analyzeTerm(tree t, char *string, int tree_number){
	int p = findParenthesis(string);
	bool upper = upperCase(string[0]);
	tree child;
	int i;
	
	//capitalized function name
	if(p != -1 && upper)
		analyzePredicate(t, string, tree_number);
	
	//constant name or lowercase variable name
	else{
		//insert on the array if it is a variable
		if(isVariable(string)){
			//variables of second clause starts with ends with 2c
			if(tree_number == 1)
				strcat(string, "2c");
			
			i = findVar(string);
			
			//add to the variables array
			if(i == -1){
				strcpy(variables[n_vars].string, string);
				variables[n_vars].t = NULL;
				n_vars++;
			}
		}
		
		//insert on the tree
		insertChild(t, string, strlen(string), false);
	}
}
Exemplo n.º 7
0
 std::string Expression::orderedString()const
 {
   std::string res = m_name;
   if (isVariable()) return res;
   std::multiset<std::string> str;
   if (isBinary())
   {
     for(auto t = begin(); t != end(); ++t)
     {
       std::string op = (**t).m_op;
       if (op.empty())
       {
         op = m_name;
       }
       str.insert(op+(**t).orderedString());
     }
     res += "(";
     for(auto s = str.begin(); s != str.end(); ++s)
     {
       res += *s;
     }
     res += ")";
   }
   else
   {
     res += "(";
     for(auto t = begin(); t != end(); ++t)
     {
       res += (**t).orderedString() + ",";
     }
     res += ")";
   }
   return res;
 }
Exemplo n.º 8
0
void
SymbolTreeBuilder::visit(VariableAccessNode& node)
{
    node.setScope(currentScope());
    const char* symbol_name = node.variableName();
    auto sym = _curScope->resolveSymbol(symbol_name);
    if (!sym)
    {
        std::stringstream stream;
        stream << "Symbol '" << symbol_name
               << "' is undefined"
               << std::endl;
        throw SemanticException(stream.str(), node);
    }

    if (!sym->isVariable())
    {
        std::stringstream stream;
        stream << "Symbol '" << symbol_name
               << "' is not a variable"
               << std::endl;
        throw SemanticException(stream.str(), node);
    }

    _expResult = ExpressionResult(sym->symbolType(), sym);
    node.setNodeType(_expResult.type);
    node.setExpressionResult(_expResult);
    sym->touchRead();
}
Exemplo n.º 9
0
/** Parse the expression in m_ExpressionText
  * and calculate result.
  * Return the result as a double.
  * If quiet ist true, no signals will be emitted and m_Expressiontext will not be modified.
  * If quiet is false, Log will be updated and m_Expressiontext will be set to the result of the calculation.
  * A logTextChanged and an expressionTextChanged signal will be emitted.
  */
double Calculator::parseExpression(bool quiet)
{
    QStringList expressionParts = m_ExpressionParts; //work on a copy, keep the original
    int partCount = expressionParts.size();
    double result = 0.0;
    try{
        //Parse the expression
        while(partCount >  1)
        {
            parseSubexpression(expressionParts);
            partCount = expressionParts.size();
        }
        if(expressionParts.size() == 0)
            throw ExExpressionError(tr("Expression could not be evaluated."));
        if( ! quiet)
        {
            m_ExpressionText = m_ExpressionParts.join("") + ( "= " + expressionParts[0]);
            //Log the expression and its result
            m_LogText += m_ExpressionText + "\n";
            emit logTextChanged(m_LogText);
            //replace the expression with its result
            m_ExpressionParts.clear();
            m_ExpressionParts.append(expressionParts[0]);
            m_ExpressionText = expressionParts[0];
            emit expressionTextChanged(m_ExpressionText);
            result = m_ExpressionText.toDouble();
        }
        else //keep m_ExpressionParts and m_Expressiontext as they are
        {
            if(isVariable(expressionParts[0]))
                result = getVariableValue(expressionParts[0]);
           else result = expressionParts[0].toDouble();
        }
    }    
    catch(ExExpressionError & e)
    {
        qDebug("Calculator::parseExpression caught ExExpressionError: %s", e.what());
        if(quiet)
            throw e;
        else emit errorMessage(tr("Error"), e.what());
    }
    catch(std::exception &e)
    {
        qDebug("Calculator::parseExpression caught std::exception: %s", e.what());
        if(quiet)
            throw e;
        else emit errorMessage(tr("Error"), e.what());
    }
    catch(...)
    {
        qDebug("Calculator::parseExpression caught unknown exception.");
        if(quiet)
            throw std::exception();
        else emit errorMessage(tr("Error"),"Calculator::parseExpression caught unknown exception.");
    }
    return result;
}
Exemplo n.º 10
0
/**
  * Returns true, if expression contains a variable.
  */
bool Calculator::expressionContainsVariable()
{
 bool result = false;

 for(int pos = 0; pos < m_ExpressionParts.size(); pos ++)
     if(isVariable(m_ExpressionParts[pos]) && !isConstant(m_ExpressionParts[pos]))
             result = true;

 return result;
}
Exemplo n.º 11
0
ATbool toLiftTerm(ATerm term){
	ATerm sort;
	if(isParameter(term) || isVariable(term)){
		sort = getTermSort(term);		
		return isLifted(sort) || isAbstracted(sort);
	}	
	else { /* is a function */
		return toLiftFunc(term);
	}
}
Exemplo n.º 12
0
const char* Properties::getString(const char* name, const char* defaultValue) const
{
    char variable[256];
    const char* value = NULL;

    if (name)
    {
        // If 'name' is a variable, return the variable value
        if (isVariable(name, variable, 256))
        {
            return getVariable(variable, defaultValue);
        }

        for (std::vector<Property>::const_iterator itr = _properties.begin(); itr != _properties.end(); ++itr)
        {
            if (itr->name == name)
            {
                value = itr->value.c_str();
                break;
            }
        }
    }
    else
    {
        // No name provided - get the value at the current iterator position
        if (_propertiesItr != _properties.end())
        {
            value = _propertiesItr->value.c_str();
        }
    }

    if (value)
    {
        // If the value references a variable, return the variable value
        if (isVariable(value, variable, 256))
            return getVariable(variable, defaultValue);

        return value;
    }

    return defaultValue;
}
Exemplo n.º 13
0
void Analyser::detectVariables()
{
    variables = "";
    for(int i=0;i<s.length(); ++i)
    {
        // now variables detecting is case sensitive,
        // if you want to make case insensitive, use:
        // if(isVariable(s[i]) && !variables.contains(s[i],Qt::CaseInsensitive))
        if(isVariable(s[i]) && !variables.contains(s[i]))
            variables+=s[i];
    }
}
Exemplo n.º 14
0
/**
  * Parse a subexpression and replace it with its result.
  */
void Calculator::parseSubexpression(QStringList & expressionParts)
{
  int operatorLine = 0;
  int prioLine = 0;
  int priority = 0;
  int parenthesisPos = 0;
  int functionLine = 0;
  for(parenthesisPos = 0; parenthesisPos < expressionParts.size(); parenthesisPos++)
      if((expressionParts[parenthesisPos]== "(") || (expressionParts[parenthesisPos]=="-("))
          parseParenthesis(expressionParts, parenthesisPos);
      else if(expressionParts[parenthesisPos]== ")"){
          throw ExExpressionError(tr("Parenthesis syntax error."));
      }
  if(expressionParts.size() < 2) //evaluation is complete, we had a (Expression)
      return;
  //now we have all function arguments directly behind the function name
  if(!(isNumber(expressionParts.last()) || isVariable(expressionParts.last())))
          throw ExExpressionError(tr("Last term of expression must be a number."));
  //evaluate function values from right to left
  for(functionLine = expressionParts.size() - 1; functionLine > -1; functionLine--)
      if(isFunction(expressionParts[functionLine]))
          evaluateFunction(expressionParts, functionLine);
  while(operatorLine < expressionParts.size() &&! isOperator(expressionParts[operatorLine]))
        operatorLine ++;
  if(operatorLine >= expressionParts.size() - 1) //no operator, invalid expression or nothing to be done
      throw ExExpressionError(tr("Missing operator."));

  //we found an operator, now search for the first operator with highest priority
  prioLine = operatorLine;
  priority = operatorPriority(expressionParts[operatorLine]);
  while( prioLine < expressionParts.size() - 1 )
  {
    prioLine ++;
    if(operatorPriority(expressionParts[prioLine]) > priority)
    {
        operatorLine = prioLine;
        priority = operatorPriority(expressionParts[prioLine]);
    }
  }
  //Now lets calculate
  if(operatorLine < 1) //we have a leading operator
  {
   if(expressionParts[operatorLine] == "-" | expressionParts[operatorLine] == "+") //we have a sign
   {
       if(expressionParts[operatorLine] == "-")
         expressionParts[0] = expressionParts[0] + expressionParts[1]; //make a negative number
       expressionParts.removeAt(1); //and delete the sign from list
       return;
   }
   else throw ExExpressionError(tr("No operator allowed in first position."));
  }
  calculateSubExpression(expressionParts, operatorLine);
}
Exemplo n.º 15
0
PointerAnalysisFlow* PointerAnalysis::operation_X_Y(PointerAnalysisFlow* in, Instruction* instruction) {
	LoadInst* load = static_cast<LoadInst*>(instruction);
	PointerAnalysisFlow* f = new PointerAnalysisFlow(in);
	Value* Y = load->getOperand(0); //RO
	Value* X = load->getNextNode()->getOperand(1); //LO

	// X = Y
	// Check if X  Y are pointers.
	if (isPointer(Y) && isPointer(X)) {
		if (isVariable(Y) && isVariable(X)) {

			//x points to what y points to 
			PointerAnalysisFlow* ff = new PointerAnalysisFlow();
			map<string, set<string> > value;
			value[X->getName()] = in->value[Y->getName()];;
			ff->value = value;
			PointerAnalysisFlow* tmp = static_cast<PointerAnalysisFlow*>(ff->join(f));
			delete ff;
			delete f;
			f = tmp;
		}
	}
	return f;
}
Exemplo n.º 16
0
BasicSymbol* BasicScope::resolve(string name){
	if(isVariable(name)){
		return this->variables[name];
	}

	if(isFunction(name)){
		return this->functions[name][0];
	}

	if(isStructure(name)){
		return this->structures[name];
	}

	throw TypeException("What are you trying to resolve!?");
}
Exemplo n.º 17
0
    void GroundConstraint::registerAllVariables(CSPSolver* csps) const
    {
        if (isVariable())
        {
           csps->getVariable(name_);
        }
        else
        if (isOperator())
        {
            for (GroundConstraintVec::const_iterator i = a_.begin(); i != a_.end(); ++i)
                i->registerAllVariables(csps);
        }
        else
            assert(isInteger());

    }
Exemplo n.º 18
0
void
ClParserIdentifier::
debugPrint() const
{
  if      (isFunction())
    fprintf(stderr, " fn");
  else if (isStructPart())
    fprintf(stderr, " str");
  else if (isVariable())
    fprintf(stderr, " var");
  else if (isArgument())
    fprintf(stderr, " arg");
  else
    fprintf(stderr, " ??");

  fprintf(stderr, " %s ", name_.c_str());
}
Exemplo n.º 19
0
PointerAnalysisFlow* PointerAnalysis::operation_X_rY(PointerAnalysisFlow* in, Instruction* instruction) {
	errs()<<"Start x=&y analysis ================================="<<"\n";
	//Check that left operand is not null.
	
	if (isa<ConstantPointerNull>(instruction->getOperand(0))) {
		errs()<<"Null Pointer!!!"<<"\n";
		PointerAnalysisFlow* f = new PointerAnalysisFlow(in);
		Value* X = instruction->getOperand(1);
		if (isPointer(X) && isVariable(X)) {
			errs()<<"Remove  " <<X->getName()<<" from list"<<"\n";
			f->value.erase(X->getName());
		}
		
		//very important if value is empty, then it is a bottom
		if(f->value.size()==0) {
			f->triPoint=BOTTOM;
		}
		return f;
		//return execute_X_equals_NULL(in,instruction);
	}
	errs()<<"Not Null Pointer, move on"<<"\n";
	StoreInst* store = static_cast<StoreInst*>(instruction);
	PointerAnalysisFlow* f = new PointerAnalysisFlow(in);
	
	// X = &Y
	//Check if right  is a pointer
	if (store->getOperand(1)->getType()->isPointerTy()) {
		//Check if x y  names are variable
		if (store->getOperand(0)->getName()!="" && store->getOperand(1)->getName()!="") {

			PointerAnalysisFlow* ff = new PointerAnalysisFlow();
			set<string> s;
			map<string, set<string> >value;
			s.insert(store->getOperand(0)->getName());
			value[store->getOperand(1)->getName()] = s;
			// X now points to Y.
			ff->value = value;
			PointerAnalysisFlow* tmp = static_cast<PointerAnalysisFlow*>(ff->join(f));
			delete ff;
			delete f;
			f = tmp;
		}
	}
	return f;
}
Exemplo n.º 20
0
int checkForVariable()
{
	locationInTemoVariableName=0;
					printf("question mark" );
					getToken();
					tempVariableName[locationInTemoVariableName]=currentToken;
					locationInTemoVariableName++;

					
					if (isVariable())
					{
						printf("%s, %s\n",tempVariableName,variables[0] );
						if (!isThereAVariable(tempVariableName))
					{
						printf("there is a variable %i, %i, %i\n",valuesOfVariables[isThereAVariable(tempVariableName)],isThereAVariable(tempVariableName),valuesOfVariables[0] );
					}
					}
}
Exemplo n.º 21
0
 void GroundConstraint::getAllVariables(std::vector<unsigned int>& vec, CSPSolver* csps) const
 {
     if (isVariable())
     {
         vec.push_back(csps->getVariable(name_));
     }
     else
     if (isOperator())
     {
         for (GroundConstraintVec::const_iterator i = a_.begin(); i != a_.end(); ++i)
             i->getAllVariables(vec,csps);
         /*if (a_!= 0)
             a_->getAllVariables(vec,csps);
         if (b_!= 0)
             b_->getAllVariables(vec,csps);
             */
     }
     else
         assert(isInteger());
 }
Exemplo n.º 22
0
ATerm getTermSort(ATerm term){
	ATerm sort;
	if(isVariable(term)){
		sort = ATtableGet(var_tab, term);
	}
	else if(isParameter(term)){
		sort = ATtableGet(par_tab, term);
	} 	
	else {
		sort =  (ATerm) ATmake("<str>",ATgetName(MCRLgetSort(term)));
	}
	if(!strcmp("\"<int>\"", ATwriteToString(sort))){
		PP("ERROR: ");
		PP(ATgetName(MCRLgetSort(term)));
		fprintf(stderr, " %d ", nSum);
		pTerm(term);
		exit(0);
	}
	return sort;
}
Exemplo n.º 23
0
int enterAValueToAVariable()
{
	locationInTemoVariableName=0;
					tempVariableName[locationInTemoVariableName]=currentToken;
					locationInTemoVariableName++;
					isVariable();
					tempVariableName[locationInTemoVariableName]='\0';
					printf(" variable 0%s\n", variables[0]);
					if (!isThereAVariable(tempVariableName))
					{
						return (isThereAVariable(tempVariableName));
					}else
					{
						stringCopyForMe(locationInVariableArray,tempVariableName);
						printf("%s\n",variables[locationInVariableArray] );
						return locationInVariableArray;
						locationInVariableArray++;
					}
					printf("is alpha" );
}
Exemplo n.º 24
0
ATerm termAbstraction(ATerm term, ATerm dstSort){
	ATerm newCons;
	AFun singTag;
	ATerm termSort, parSort;
	
	
	if(!(isVariable(term) || isParameter(term) || isConstant(term))){
		term = funcAbstraction(term, dstSort);	
		
	}
	termSort = getTermSort(term);
	
	if(isLifted(dstSort)){
		if(isAbstracted(dstSort)){
			if(!isAbstracted(termSort)){
				if(!isLifted(termSort)){
					termSort = liftSort(termSort);
					term = createSingTerm(term, termSort);
				}
				term = createAlphaTerm(term, termSort);
			}
			else{
				if(!isLifted(termSort)){
					termSort = liftSort(abstractSort(termSort));
					term = createSingTerm(term, termSort);		
				}
			}
		}
		else{
			if(!isLifted(termSort)){
				termSort = liftSort(termSort);
				term = createSingTerm(term, termSort);		
			}
		}		
	}
	
	return term;
}
Exemplo n.º 25
0
/* Renvoi de la generation suivante d'une generation donnee pour un L-System donne */
String nextGen(String generation, Lsystem lsystem)
{
    String generation2=(String)malloc((double)strlen(generation)*sizeof(char));
    strcpy (generation2,"");
    double i = 0;
    double lenghtTot = (double)strlen(generation);
    while (i<(double)strlen(generation)){
        int nbVar = isVariable(generation[(int)i],lsystem);
        if (nbVar==-1) strcat(generation2,ctos(generation[(int)i]));
        else {
            int j;
            Rules* l = lsystem.rules;
            for (j=0;j<nbVar;j++){
                    l = l->next;
            }
            lenghtTot = lenghtTot+(double)strlen(l->rule);
            generation2 = (String)realloc(generation2,lenghtTot*sizeof(char));
            strcat(generation2,l->rule);
        }
    i = i+1;
    }
    return generation2;
}
Exemplo n.º 26
0
void Properties::readProperties()
{
    CCASSERT(_data->getSize() >0, "Invalid data");

    char line[2048];
    char variable[256];
    int c;
    char* name;
    char* value;
    char* parentID;
    char* rc;
    char* rcc;
    char* rccc;
    bool comment = false;

    while (true)
    {
        // Skip whitespace at the start of lines
        skipWhiteSpace();

        // Stop when we have reached the end of the file.
        if (eof())
            break;

        // Read the next line.
        rc = readLine(line, 2048);
        if (rc == NULL)
        {
            CCLOGERROR("Error reading line from file.");
            return;
        }

        // Ignore comments
        if (comment)
        {
            // Check for end of multi-line comment at either start or end of line
            if (strncmp(line, "*/", 2) == 0)
                comment = false;
            else
            {
                trimWhiteSpace(line);
                const auto len = strlen(line);
                if (len >= 2 && strncmp(line + (len - 2), "*/", 2) == 0)
                    comment = false;
            }
        }
        else if (strncmp(line, "/*", 2) == 0)
        {
            // Start of multi-line comment (must be at start of line)
            comment = true;
        }
        else if (strncmp(line, "//", 2) != 0)
        {
            // If an '=' appears on this line, parse it as a name/value pair.
            // Note: strchr() has to be called before strtok(), or a backup of line has to be kept.
            rc = strchr(line, '=');
            if (rc != NULL)
            {
                // First token should be the property name.
                name = strtok(line, "=");
                if (name == NULL)
                {
                    CCLOGERROR("Error parsing properties file: attribute without name.");
                    return;
                }

                // Remove white-space from name.
                name = trimWhiteSpace(name);

                // Scan for next token, the property's value.
                value = strtok(NULL, "");
                if (value == NULL)
                {
                    CCLOGERROR("Error parsing properties file: attribute with name ('%s') but no value.", name);
                    return;
                }

                // Remove white-space from value.
                value = trimWhiteSpace(value);

                // Is this a variable assignment?
                if (isVariable(name, variable, 256))
                {
                    setVariable(variable, value);
                }
                else
                {
                    // Normal name/value pair
                    _properties.push_back(Property(name, value));
                }
            }
            else
            {
                parentID = NULL;

                // Get the last character on the line (ignoring whitespace).
                const char* lineEnd = trimWhiteSpace(line) + (strlen(trimWhiteSpace(line)) - 1);

                // This line might begin or end a namespace,
                // or it might be a key/value pair without '='.

                // Check for '{' on same line.
                rc = strchr(line, '{');

                // Check for inheritance: ':'
                rcc = strchr(line, ':');

                // Check for '}' on same line.
                rccc = strchr(line, '}');
            
                // Get the name of the namespace.
                name = strtok(line, " \t\n{");
                name = trimWhiteSpace(name);
                if (name == NULL)
                {
                    CCLOGERROR("Error parsing properties file: failed to determine a valid token for line '%s'.", line);
                    return;
                }
                else if (name[0] == '}')
                {
                    // End of namespace.
                    return;
                }

                // Get its ID if it has one.
                value = strtok(NULL, ":{");
                value = trimWhiteSpace(value);

                // Get its parent ID if it has one.
                if (rcc != NULL)
                {
                    parentID = strtok(NULL, "{");
                    parentID = trimWhiteSpace(parentID);
                }

                if (value != NULL && value[0] == '{')
                {
                    // If the namespace ends on this line, seek back to right before the '}' character.
                    if (rccc && rccc == lineEnd)
                    {
                        if (seekFromCurrent(-1) == false)
                        {
                            CCLOGERROR("Failed to seek back to before a '}' character in properties file.");
                            return;
                        }
                        while (readChar() != '}')
                        {
                            if (seekFromCurrent(-2) == false)
                            {
                                CCLOGERROR("Failed to seek back to before a '}' character in properties file.");
                                return;
                            }
                        }
                        if (seekFromCurrent(-1) == false)
                        {
                            CCLOGERROR("Failed to seek back to before a '}' character in properties file.");
                            return;
                        }
                    }

                    // New namespace without an ID.
                    Properties* space = new (std::nothrow) Properties(_data, _dataIdx, name, NULL, parentID, this);
                    _namespaces.push_back(space);

                    // If the namespace ends on this line, seek to right after the '}' character.
                    if (rccc && rccc == lineEnd)
                    {
                        if (seekFromCurrent(1) == false)
                        {
                            CCLOGERROR("Failed to seek to immediately after a '}' character in properties file.");
                            return;
                        }
                    }
                }
                else
                {
                    // If '{' appears on the same line.
                    if (rc != NULL)
                    {
                        // If the namespace ends on this line, seek back to right before the '}' character.
                        if (rccc && rccc == lineEnd)
                        {
                            if (seekFromCurrent(-1) == false)
                            {
                                CCLOGERROR("Failed to seek back to before a '}' character in properties file.");
                                return;
                            }
                            while (readChar() != '}')
                            {
                                if (seekFromCurrent(-2) == false)
                                {
                                    CCLOGERROR("Failed to seek back to before a '}' character in properties file.");
                                    return;
                                }
                            }
                            if (seekFromCurrent(-1) == false)
                            {
                                CCLOGERROR("Failed to seek back to before a '}' character in properties file.");
                                return;
                            }
                        }

                        // Create new namespace.
                        Properties* space = new (std::nothrow) Properties(_data, _dataIdx, name, value, parentID, this);
                        _namespaces.push_back(space);

                        // If the namespace ends on this line, seek to right after the '}' character.
                        if (rccc && rccc == lineEnd)
                        {
                            if (seekFromCurrent(1) == false)
                            {
                                CCLOGERROR("Failed to seek to immediately after a '}' character in properties file.");
                                return;
                            }
                        }
                    }
                    else
                    {
                        // Find out if the next line starts with "{"
                        skipWhiteSpace();
                        c = readChar();
                        if (c == '{')
                        {
                            // Create new namespace.
                            Properties* space = new (std::nothrow) Properties(_data, _dataIdx, name, value, parentID, this);
                            _namespaces.push_back(space);
                        }
                        else
                        {
                            // Back up from fgetc()
                            if (seekFromCurrent(-1) == false)
                                CCLOGERROR("Failed to seek backwards a single character after testing if the next line starts with '{'.");

                            // Store "name value" as a name/value pair, or even just "name".
                            if (value != NULL)
                            {
                                _properties.push_back(Property(name, value));
                            }
                            else
                            {
                                _properties.push_back(Property(name, ""));
                            }
                        }
                    }
                }
            }
        }
    }
}
Exemplo n.º 27
0
 inline bool       isVariableOrDot() { return isVariable() || subclass == SYMBOL_DOTSYMBOL; };
Exemplo n.º 28
0
void firstFinding(char var)
{
	int index = 0;
	int i = 0, j;
	int num = 0;
	char tempo[NUM_TERM];
	char temp[2];
	struct RHS_productions * ptr_s = NULL;

	if(strlen(V)==0)
		return;

	if(removeFromV(var)!=-1) {
		i=0;
		while(grammar[i]!=NULL) {
			if (grammar[i]->variables == var) {
				index = i;
				break;
			}
			i++;
		}
		
		num = strlen(first[index].firsts);
		ptr_s = grammar[index]->produces;
		while(ptr_s!=NULL) { 
			for(i=0; i<strlen(ptr_s->production); i++) {

//				if(isEpsilon(ptr_s->production[i])) {
					
//				}
				if(isTerminal(ptr_s->production[i])) {
				  temp[0] = ptr_s->production[i];
				  //				  first[index].firsts[num] = ptr_s->production[i];
				  //					num++;
	
					//					first[index].firsts[num] = '\0';
//					printf("\n\nindex  %d  num  %d\n\n  ",index,num);
				  temp[1] = '\0';
				  strcat(first[index].firsts,temp);
					break;	
				}
				if(isVariable(ptr_s->production[i])) {
					firstFinding(ptr_s->production[i]);
					j=0;
					while(first[j].var!='@') {
						if(first[j].var==ptr_s->production[i]) {
							break;
						}
						j++;
					}
					strcpy(tempo,first[j].firsts);
					if(i != strlen(ptr_s->production)-1) {
					removeEpsilon(tempo);
					}
					//					if(index!=j) {
						strcat(first[index].firsts,tempo);
						//					}
					if(first[j].epsilon==1) {
					  /*					  firstFinding(ptr_s->production[i+1]);
					  j = 0;
					  while(first[j].var!='@') {
					    if(first[j].var==ptr_s->production[i]) {
					      break;
					    }
					    j++;
					  }
					  strcat(first[index].firsts,first[j].firsts);
					  */	continue;
					}
					else
						break;
				}

			}

			ptr_s = ptr_s->next;
		}
	}//end if
//	else {

//	}

	
}
Exemplo n.º 29
0
 /** Evaluates a function-number sequence.
   * Replaces the two lines with a single line containing the result of the evaluation.
   */
  void Calculator::evaluateFunction(QStringList & expressionParts, int functionLine)
  {
      double result =0.0;
      bool ok = true;
      QString sArgument = expressionParts[functionLine + 1];
      double argument = 0.0;

      if(isVariable(sArgument))
          argument = getVariableValue(sArgument);
      else argument = sArgument.toDouble(&ok);

      if(!ok)
          throw ExExpressionError(tr("Function name must be followed by a number."));
      QString function = expressionParts[functionLine].toLower();
      if(!isFunction(function))
          throw ExExpressionError(tr("Unknown function:") + function);

      if(function == "sin")
          result = sin(toRad(argument));
      else if(function == "arcsin")
      {
          if(argument < -1.0 || argument > 1.0)
              throw ExExpressionError(tr("Argument of arcsin must be in the range from -1 to 1. Found:") + " "
                                      + expressionParts[functionLine + 1] );
          result = fromRad(asin(argument));
      }
      else if(function == "cos")
          result = cos(toRad(argument));
      else if(function == "arccos")
      {
          if(argument < -1.0 || argument > 1.0)
              throw ExExpressionError(tr("Argument of arccos must be in the range from -1 to 1. Found:") + " "
                                      + expressionParts[functionLine+1] );
          result = fromRad(acos(argument));
      }
      else if(function == "tan")
          result = tan(toRad(argument));
      else if(function == "arctan")
      {
          result = fromRad(atan(argument));
      }
      else if(function == "sinh")
          result = sinh(argument);
      else if(function == "arsinh")
      {
          result = asinh(argument);
      }
      else if(function == "cosh")
          result = cosh(argument);
      else if(function == "arcosh")
      {
          if(argument < 1.0 )
              throw ExExpressionError(tr("Argument of arcosh must be >= 1. Found:") + " "
                                      + QString::number(argument) );
          result = acosh(argument);
      }
      else if(function == "tanh")
          result = tanh(argument);
      else if(function == "artanh")
      {
          if(argument < -1.0 || argument > 1.0 )
              throw ExExpressionError(tr("Argument of artanh must be in the range from -1 to 1. Found:") + " "
                                      + QString::number(argument) );
          result = atanh(argument);
      }
      else if(function == "exp")
          result = exp(argument);
      else if(function == "ln")
      {
          if(argument <= 0.0)
              throw ExExpressionError(tr("Argument of ln must be > 0. Found:") + " "
                                      + QString::number(argument) );
          result = log(argument);
      }
      else if(function == "log")
      {
          if(argument < 0.0)
              throw ExExpressionError(tr("Argument of log must be > 0. Found:") + " "
                                      + QString::number(argument) );
          result = log10(argument);
      }
      else if(function == "sqrt" || function == textSqrt())
      {
          if(argument < 0.0)
              throw ExExpressionError(tr("Argument of sqrt must be > 0. Found:") + " "
                                      + QString::number(argument) );
          result = sqrt(argument);
      }
      if(function != textPi()) //Pi has no argument
         expressionParts.removeAt(functionLine +1);
      expressionParts[functionLine] = QString::number(result, 'G');
  }
Exemplo n.º 30
0
/** Append text to Expression. Overwrites a trailing operator with the new one, if a sequence of
  * two operators is input.
  * Recognizes and executes C, AC and = commands.
  */
void Calculator::addToExpressionText(const QString & buttonText)
{
    QString text = buttonText;
    try{
        if(text == "C")
            clearLast();
        else if(text == "AC")
            clearAll();
        else if(text == "+/-")
            changeSign();
        else if(text == m_TextRad)
            setAngleMode(text);
        else if(text == m_TextDeg)
            setAngleMode(text);
        else if(text == "=")
        {
            if(isPlotExpression())
                createPlot();
            else parseExpression();
        }
        else if(text=="x")
            addVariable(text);
        else if(text.startsWith("Plot"))
                plotter.processPlotCommand(text);
        else{ //we have a digit, operator or function
            //no clear or evaluate command
            if(text == "x^y") //convert to operator
                text = "^";
            if(isNumber(text)){ //No parenthesis, we have a digit or a decimal separator
                addDigit(text);
                emit guiStateSuggested(STATE_STANDARD); //return to std page, if on Fn Page for entering E
            }
            else if(isOperator(text)) //operator or digit
            {
                addOperator(text);
            }
            else if(isParenthesis(text)) //we have a parenthesis
            {
                addParenthesis(text);
            }
            else if(isFunction(text)) //we have a function
            {
                addFunctionCall(text);
            }
            else if(isVariable(text)) //we have a variable
            {
                addVariable(text);
            }
            else throw ExExpressionError(tr("Unknown command:") + text);

        } //end digit operator or function

        m_ExpressionText = m_ExpressionParts.join("");
        if(isPlotExpression())
            emit expressionTextChanged("y=" + m_ExpressionText);
        else emit expressionTextChanged(m_ExpressionText);
    } //end try
    catch(ExExpressionError e)
    {
        emit guiStateSuggested(STATE_STANDARD);
        emit errorMessage(tr("Input Error"),e.what());
    }
    catch(std::exception e)
    {
        emit guiStateSuggested(STATE_STANDARD);
        emit errorMessage(tr("Unknown Input Error"),e.what());
    }
}