void QuantifiedRegexObject::parse(Regex* rgx)
{
	regexObject = new RegexObject;
	regexObject->parse(rgx);
	char c = rgx->src.peek();
	if (c == '+' || c == '*' || c == '?')
	{
		rgx->src.get();
		if (c == '+') type = QuantifierType::KLEENE_PLUS;
		else if (c == '*') type = QuantifierType::KLEENE_STAR;
		else type = QuantifierType::QUESTION_MARK;
		if (rgx->src.peek() == '?')
		{
			greedy = false;
			rgx->src.get();
		}
	}
	else if (c == '{')
	{
		char x;
		int minVal, maxVal;
		minVal = Utility::parseInt(rgx);
		if (rgx->src.get() != ',')
		{
			rgx->src.moveBack();
			maxVal = minVal;
		}
		else
		{
			if (Utility::isDigit(rgx->src.peek()))
			{
				maxVal = Utility::parseInt(rgx);
			}
			else
			{
				maxVal = oo;
			}
		}
		
		if (rgx->src.get() != '}') throw ParseError("");
		if (maxVal < minVal) swap(minVal, maxVal);
		range = make_pair(minVal, maxVal);
		type = QuantifierType::RANGED;
	}
}
Example #2
0
File: xml.cpp Project: dcdelia/mcvm
	/***************************************************************
	* Function: Parser::parseText()
	* Purpose : Parse an XML text region
	* Initial : Maxime Chevalier-Boisvert on October 20, 2008
	****************************************************************
	Revisions and bug fixes:
	*/
	Text* Parser::parseText(const std::string& xmlString, size_t& charIndex, const PosVector& positions)
	{
		// Declare a string to store the text
		std::string text;

		// For each character
		for (;; ++charIndex)
		{
			// If we are past the length of the input stream
			if (charIndex >= xmlString.length())
			{
				// Throw an exception
				throw ParseError("Unexpected end of stream in text region", positions[charIndex]);
			}

			// Extract the current character
			char thisChar = xmlString[charIndex];

			// If this character is the beggining of an escape sequence
			if (thisChar == '&')
			{
				// Parse the escape sequence
				text += parseEscapeSeq(xmlString, charIndex, positions);

				// Move on to the next character
				continue;
			}

			// If this character is the beginning of a tag
			if (thisChar == '<')
			{
				// Move back one character
				charIndex--;

				// Break out of this loop
				break;
			}

			// Add this character to the text
			text += thisChar;
		}

		// Create and returna new text node
		return new Text(text);
	}
Example #3
0
void Read_termstr_rtn(P_WBXML_INFO buffer, char** result)
{

#define STRING_BLOCK_SIZE 256

	int buflen = STRING_BLOCK_SIZE;
	char* strbuf = (char*) malloc(buflen);
	BOOL doubled = FALSE;
	int i = 0;

	if (!result)
		ParseError(ERR_INTERNAL_BAD_PARAM);

	while ( (BytesLeft(buffer) >= 1) && (*(buffer->m_curpos) != 0) )
	{
		if (i>=buflen)
		{
			buflen += STRING_BLOCK_SIZE;
			strbuf = realloc(strbuf, buflen);
		}

		if (*(buffer->m_curpos) != '$' || doubled == TRUE)
		{
			strbuf[i] = *(buffer->m_curpos);
			buffer->m_curpos++;
			i++;
			if (doubled == TRUE)
				doubled = FALSE;
		}
		else
		{
			strbuf[i] = *(buffer->m_curpos);
			i++;
			doubled = TRUE;
		}
	}

	strbuf[i] = 0;
	buffer->m_curpos++;

	if (*result)
		free(*result);

	*result = strbuf;
}
Example #4
0
/* ParseEndIf - parse the 'END IF' statement */
static void ParseEndIf(ParseContext *c)
{
    switch (CurrentBlockType(c)) {
    case BLOCK_IF:
        fixupbranch(c, c->bptr->u.IfBlock.nxt, codeaddr(c));
        fixupbranch(c, c->bptr->u.IfBlock.end, codeaddr(c));
        PopBlock(c);
        break;
    case BLOCK_ELSE:
        fixupbranch(c, c->bptr->u.ElseBlock.end, codeaddr(c));
        PopBlock(c);
        break;
    default:
        ParseError(c, "END IF without a matching IF/ELSE IF/ELSE");
        break;
    }
    FRequire(c, T_EOL);
}
void CodeTranslator::translate(std::string str)
{
	m_grammar.clear();
    std::string::iterator begin = str.begin(), end = str.end();

    bool success = qi::parse(begin, end, m_grammar);


    if(!success || begin != end)
    {
		m_lbls.clear();
		m_command.setOperationType(Command::NONE);
		throw ParseError("stopped at: " + std::string(begin, end));
	}

    if(m_command.getOperationType() != Command::NONE)
    	checkCorrectness();
}
Example #6
0
//   path-absolute = "/" [ segment-nz *( "/" segment ) ]
TextCursor parse_path_absolute(TextCursor cursor)
{
    char c = get_char(cursor);
    if (c != '/')
        throw ParseError();
    else
    {
        try
        {
            TextCursor cursor2(parse_segment_nz(cursor));
            REPEAT_IGNORING(parse_slash_segment, cursor2);
        }
        catch(ParseError)
        {
            return cursor;
        }
    }
}
// ------------------------------------------------------------------------------------------------
const std::string & ColladaModelFactory::FindAndValidateString(std::map<std::string, std::string> * stringMap, const std::string & index)
{
    // if empty, just return another empty string
    if (index.empty())
    {
        return index;
    }

    // look up 'index' in map
    auto it = stringMap->find(index);
    if (it == stringMap->end())
    {
        static const std::string c_emptyString;
        ParseError("could not find '%s'\n", index.c_str());
        return c_emptyString;
    }
    return it->second;
}
Example #8
0
void Configuration::Assign(const string &field, const string &value)
{
	map<string, char *>::const_iterator match;

	match = _str_map.find(field);
	if (match != _str_map.end())
	{
		free(_str_map[field]);
		_str_map[field] = strdup(value.c_str());
	}
	else
	{
		string errmsg = "Unknown field ";
		errmsg += field;

		ParseError(errmsg, 0);
	}
}
Example #9
0
VExpression* VDynamicCast::DoResolve(VEmitContext& ec)
{
	if (op)
		op = op->Resolve(ec);
	if (!op)
	{
		delete this;
		return NULL;
	}

	if (op->Type.Type != TYPE_Reference)
	{
		ParseError(Loc, "Bad expression, class reference required");
		delete this;
		return NULL;
	}
	Type = VFieldType(Class);
	return this;
}
Example #10
0
	Parser(typename Encode<E>::PointerType input, Automata& nfa)
		: reader(input)
	{
		nfa.clear();
		if (reader.peek() == 0)
		{
			return;
		}
		auto ast = parseRE();
		if (reader.peek() != 0)
		{
			throw ParseError();
		}
		State s;
		State e;
		ast->convertToNFA(nfa, s, e);
		nfa.setStart(s);
		nfa.setTerminate(e);
	}
 // Interpret the next argument as a path, and obtain the IShellItem for it to be consumed by the derived class.
 HRESULT v_ProcessLibArguments(PCWSTR *ppszArgs, int cArgs)
 {
     PCWSTR pszFolderPath = CONSUME_NEXT_ARG(ppszArgs, cArgs);
     HRESULT hr = pszFolderPath ? S_OK : E_INVALIDARG;
     if (SUCCEEDED(hr))
     {
         hr = SHStrDupW(pszFolderPath, &_pszFolderPath);
         if (SUCCEEDED(hr))
         {
             hr = SHCreateItemFromParsingName(pszFolderPath, NULL, IID_PPV_ARGS(&_psiFolder));
         }
     }
     else
     {
         ParseError(L"Missing folder path argument.\n");
     }
     // On success, pass any remaining arguments on to the derived class.
     return SUCCEEDED(hr) ? v_ProcessFolderArguments(ppszArgs, cArgs) : hr;
 }
Example #12
0
 const Insert &insert_stmt() {
     if (lookahead == INSERT) {
         // insert_stmt -> INSERT INTO id L_PAREN column_list R_PAREN
         //                VALUES L_PAREN value_list R_PAREN SEMICOLON
         match(INSERT); match(INTO);
         string table_id = id();
         match(L_PAREN);
         vector<string> columns;
         column_list(columns);
         match(R_PAREN);
         vector<int> values;
         value_list(values);
         match(R_PAREN);
         match(SEMICOLON);
         return Insert(table_id, columns, values);
     } else {
         throw ParseError("Syntax error");
     }
 }
Example #13
0
Value load(std::istream& ss) {
// Parse a JSON entity, using the inputstream ss
    parseWhitespace(ss);
    switch (ss.peek()) {
    case '{': return parseObject(ss);
    case '[': return parseArray(ss);
    case '"': return parseString(ss);
    case 't': return parseTrue(ss);
    case 'f': return parseFalse(ss);
    case 'n': return parseNull(ss);
    case '-': return parseNumber(ss);
    default: 
        if(isdigit(ss.peek())) {
            return parseNumber(ss);
        } else {
            throw ParseError(std::string("unexpected token: '")+char(ss.peek())+"'");
        }
    }
}
Example #14
0
/* ParseElseIf - parse the 'ELSE IF' statement */
static void ParseElseIf(ParseContext *c)
{
    switch (CurrentBlockType(c)) {
    case BLOCK_IF:
        putcbyte(c, OP_BR);
        c->bptr->u.IfBlock.end = putcword(c, c->bptr->u.IfBlock.end);
        fixupbranch(c, c->bptr->u.IfBlock.nxt, codeaddr(c));
        c->bptr->u.IfBlock.nxt = 0;
        ParseRValue(c);
        FRequire(c, T_THEN);
        putcbyte(c, OP_BRF);
        c->bptr->u.IfBlock.nxt = putcword(c, 0);
        FRequire(c, T_EOL);
        break;
    default:
        ParseError(c, "ELSE IF without a matching IF");
        break;
    }
}
	void DriveManager::handleGetFileInfo ()
	{
		QNetworkReply *reply = qobject_cast<QNetworkReply*> (sender ());
		if (!reply)
			return;

		reply->deleteLater ();

		bool ok = false;
		const auto& res = QJson::Parser ().parse (reply->readAll (), &ok);
		if (!ok)
		{
			qDebug () << Q_FUNC_INFO
					<< "parse error";
			return;
		}

		const QVariantMap& map = res.toMap ();
		QString access_token = Reply2DownloadAccessToken_.take (reply);

		if (!map.contains ("error"))
		{
			DriveItem it = CreateDriveItem (res);
			if (it.DownloadUrl_.isEmpty ())
			{
				QMessageBox::warning (Core::Instance ().GetProxy ()->GetRootWindowsManager ()->GetPreferredWindow (),
						"LeechCraft",
						tr ("This file cannot be downloaded. Use export instead of Download or Open File action"));
				DownloadsQueue_.removeFirst ();
				return;
			}

			if (!access_token.isEmpty ())
				it.DownloadUrl_.addQueryItem ("access_token", access_token);

			if (!DownloadsQueue_.isEmpty ())
				DownloadsQueue_.dequeue () (it.DownloadUrl_);
			return;
		}

		ParseError (map);
	}
Example #16
0
void Args::accept_arg(Pass1 *pass1, ParseNode *arg)
{
	assert(arg->token == RULE_ARG);
	std::list<ParseNode *>::iterator i = arg->children.begin();
	assert(i != arg->children.end());
	assert((*i)->token == CTokenEnums::TOKEN_IDENT);
	std::string base_size = (*i)->text;
	short scalar = 1;
	++i;	// skip past base type
	assert(i != arg->children.end());
	if((*i)->token == '*')
	{
		++i;	// skip past *
		assert(i != arg->children.end());
		assert((*i)->token == CTokenEnums::TOKEN_NUM);
		scalar = get_short((*i)->text);
		if(scalar <= 1)
		{
			throw ParseError(std::string("Invalid argument type: ") + base_size + "*" + (*i)->text,
				arg->lineNum, arg->fileNum, __LINE__
			);
		}
		++i;	// skip scalar
	}
	assert((*i)->token == CTokenEnums::TOKEN_IDENT);
	std::string arg_name = (*i)->text;
	Arg xarg;
	xarg.arg_name = arg_name;
	xarg.size_name = base_size;
	xarg.scalar = scalar;
	Size tmp = pass1->get_exact_size(base_size);
	///std::cout << "(" << base_size << " " << tmp.base << " " << tmp.scalar << ")";
	if(tmp.scalar == 0)
		xarg.base_size = -1;	// parameterized size
	else
	{
		xarg.base_size = tmp.base;
		assert(xarg.scalar == 1);
	}
	///argnums[arg_name] = args.size();
	args.push_back(xarg);
}
Example #17
0
MailAddress::MailAddress(const QVariantList &input, const QByteArray &line, const int start)
{
    // FIXME: all offsets are wrong here
    if (input.size() != 4)
        throw ParseError("MailAddress: not four items", line, start);

    if (input[0].type() != QVariant::ByteArray)
        throw UnexpectedHere("MailAddress: item#1 not a QByteArray", line, start);
    if (input[1].type() != QVariant::ByteArray)
        throw UnexpectedHere("MailAddress: item#2 not a QByteArray", line, start);
    if (input[2].type() != QVariant::ByteArray)
        throw UnexpectedHere("MailAddress: item#3 not a QByteArray", line, start);
    if (input[3].type() != QVariant::ByteArray)
        throw UnexpectedHere("MailAddress: item#4 not a QByteArray", line, start);

    name = Imap::decodeRFC2047String(input[0].toByteArray());
    adl = Imap::decodeRFC2047String(input[1].toByteArray());
    mailbox = Imap::decodeRFC2047String(input[2].toByteArray());
    host = Imap::decodeRFC2047String(input[3].toByteArray());
}
Example #18
0
Flake* Parser::parse_value(){
	Flake* f;
	if(f=parse_text()){
		return f;
	}

	if(f=parse_tag()){
		return f;
	}

	if(f=parse_section()){
		return f;
	}

	//Error checking

	/*
	Snow errors are very predictable, so check for common
	mistakes. By this point, we know the next character is
	one of the quote characters, ], }, whitespace, a control
	character, or EOF (if not, something is HORRIBLY wrong)
	*/

	if(it==end){
		throw ParseError(TAG_EOF,line,col);
	}

	char c=*it;

	if(c==CLOSE_SECTION){
		throw ParseError(UNEXPECTED_CLOSE_SECTION,line,col-1);
	}

	if(c==CLOSE_TAG){
		throw ParseError(UNNAMED_ATTR,colonline,coloncol);
	}

	if(c==NAMED_ATTR){
		throw ParseError(ILLEGAL_NAMED,line,col-1);
	}

	if(isspace(c)){
		//This should NEVER happen. Guarantees a problem with the parser.
		throw ParseError(UNEXPECTED_SPACE,line,col);
	}

	//Reserved for cosmic ray errors
	throw ParseError(COSMIC_RAY_ERR,line,col);
}
Example #19
0
/**
Parse a source string as an expression
*/
Tuple parseString(const char* str, const char* srcName)
{
    auto input = new Input(
        str,
        srcName
    );

    input->eatWS();

    auto expr = parseExpr(input);

    input->eatWS();

    if (!input->eof())
    {
        throw ParseError(input, "unconsumed input remains");
    }

    return expr;
}
Example #20
0
/**
Parse a let expression
let <ident> = <expr>
*/
Tuple parseLetExpr(Input* input)
{
    input->eatWS();
    auto ident = parseIdentStr(input);

    input->eatWS();
    if (!input->matchCh('='))
    {
        throw ParseError(input, "expected '=' in let expression");
    }

    auto initExpr = parseExpr(input);

    return Tuple{
        Tuple("let"),
        ident,
        initExpr,
        -1
    };
}
Example #21
0
/* ParseNext - parse the 'NEXT' statement */
static void ParseNext(ParseContext *c)
{
    ParseTreeNode *var;
    int inst;
    switch (CurrentBlockType(c)) {
    case BLOCK_FOR:
        FRequire(c, T_IDENTIFIER);
        var = GetSymbolRef(c, c->token);
        /* BUG: check to make sure it matches the symbol used in the FOR */
        inst = putcbyte(c, OP_BR);
        putcword(c, c->bptr->u.ForBlock.nxt - inst - 1 - sizeof(VMUVALUE));
        fixupbranch(c, c->bptr->u.ForBlock.end, codeaddr(c));
        PopBlock(c);
        break;
    default:
        ParseError(c, "NEXT without a matching FOR");
        break;
    }
    FRequire(c, T_EOL);
}
Example #22
0
	void DriveManager::handleGotFiles ()
	{
		QNetworkReply *reply = qobject_cast<QNetworkReply*> (sender ());
		if (!reply)
			return;

		reply->deleteLater ();

		bool ok = false;
		const auto& res = QJson::Parser ().parse (reply->readAll (), &ok);

		if (!ok)
		{
			qDebug () << Q_FUNC_INFO << "parse error";
			return;
		}

		const auto& resMap = res.toMap ();
		if (!resMap.contains ("items"))
		{
			qDebug () << Q_FUNC_INFO << "there are no items";
			return;
		}

		if (resMap.contains ("error"))
		{
			ParseError (res.toMap ());
			return;
		}

		QList<DriveItem> resList;
		Q_FOREACH (const auto& item, resMap ["items"].toList ())
		{
			const auto& driveItem = CreateDriveItem (item);
			if (driveItem.Name_.isEmpty ())
				continue;
			resList << driveItem;
		}

		emit gotFiles (resList);
	}
Example #23
0
/** Parse task list style. */
void ParseTaskListStyle(const TokenNode *tp) {

   const char *temp;
   TokenNode *np;

   temp = FindAttribute(tp->attributes, INSERT_ATTRIBUTE);
   if(temp) {
      if(!strcmp(temp, "right")) {
         settings.taskInsertMode = INSERT_RIGHT;
      } else if(!strcmp(temp, "left")) {
         settings.taskInsertMode = INSERT_LEFT;
      } else {
         ParseError(tp, _("invalid insert mode: \"%s\""), temp);
         settings.taskInsertMode = INSERT_RIGHT;
      }
   }

   for(np = tp->subnodeHead; np; np = np->next) {
      switch(np->type) {
      case TOK_FONT:
         SetFont(FONT_TASK, np->value);
         break;
      case TOK_FOREGROUND:
         SetColor(COLOR_TASK_FG, np->value);
         break;
      case TOK_BACKGROUND:
         ParseGradient(np->value, COLOR_TASK_BG1, COLOR_TASK_BG2);
         break;
      case TOK_ACTIVEFOREGROUND:
         SetColor(COLOR_TASK_ACTIVE_FG, np->value);
         break;
      case TOK_ACTIVEBACKGROUND:
         ParseGradient(np->value, COLOR_TASK_ACTIVE_BG1, COLOR_TASK_ACTIVE_BG2);
         break;
      default:
         InvalidTag(np, TOK_TASKLISTSTYLE);
         break;
      }
   }

}
Example #24
0
void XSDParser::ParseAny(DTDElement& node)
{
    TToken tok = GetRawAttributeSet();
#if 0
    if (GetAttribute("processContents")) {
        if (!IsValue("lax") && !IsValue("skip")) {
            ParseError("lax or skip");
        }
    }
#endif
    node.SetOccurrence( ParseMinOccurs( node.GetOccurrence()));
    node.SetOccurrence( ParseMaxOccurs( node.GetOccurrence()));
    if (GetAttribute("namespace")) {
        node.SetNamespaceName(m_Value);
    }
    SetCommentsIfEmpty(&(node.Comments()));
    if (tok == K_CLOSING) {
        ParseContent(node);
    }
    m_ExpectLastComment = true;
}
Example #25
0
/**
  \brief Reads the value of the given attribute of an xml-node and converts it to a double.
 */
inline Mtbdd
readDoubleAttribute(const TiXmlNode* node, const char* att)
{
    const std::string numberString = readStringAttribute(node, att);
    try {
        size_t pos = 0;
        if ((pos = numberString.find('/')) != std::string::npos) {
            const std::string numerator = numberString.substr(0,pos);
            const std::string denominator = numberString.substr(pos+1);
            double value = boost::lexical_cast<double>(numerator)/boost::lexical_cast<double>(denominator);
            if (value == 0.0) return mtbdd_false;
            return Mtbdd::doubleTerminal(value);
        } else {
            double value = boost::lexical_cast<double>(numberString);
            if (value == 0.0) return mtbdd_false;
            return Mtbdd::doubleTerminal(value);
        }
    } catch(boost::bad_lexical_cast&) {
        throw ParseError("[ERROR] String " + numberString + " is not a number");
    }
}
Example #26
0
WBXML_LENGTH BytesLeft(P_WBXML_INFO buffer)
{
  if (buffer)
  {
    WBXML_LENGTH bytesRead = (buffer->m_curpos - buffer->m_start);
    if (bytesRead >= buffer->m_length)
    {
      return 0;
    }
    else
    {
      return (buffer->m_length - bytesRead);
    }
  }
  else
  {
    ParseError(ERR_INTERNAL_BAD_PARAM);
  }

  return 0;
}
Example #27
0
/* CallHandler - compile a call to a runtime print function */
static void CallHandler(ParseContext *c, char *name, ParseTreeNode *expr)
{
    Symbol *sym;
    
    /* find the built-in function */
    if (!(sym = FindSymbol(&c->globals, name)))
        ParseError(c, "undefined print function: %s", name);
        
    /* compile the function symbol reference */
    putcbyte(c, OP_LIT);
    putcword(c, sym->value);

    /* compile the argument */
    if (expr)
        code_rvalue(c, expr);
    
    /* call the function */
    putcbyte(c, OP_CALL);
    putcbyte(c, (expr ? 1 : 0));
    putcbyte(c, OP_DROP);
}
Example #28
0
bool ParseMap ( char *text, const sOptionTableInfo &info, sRejectOptionRMB *option )
{
    option->Info = &info;

    while ( ! isdigit ( *text )) text--;

    switch ( info.Type ) {
        case OPTION_MAP_1 :
            option->Data [0] = text [-2] - '0';
            option->Data [1] = text [0] - '0';
            break;
        case OPTION_MAP_2 :
            option->Data [0] = ( text [-1] - '0' ) * 10 + ( text [0] - '0' );
            break;
        default :
            ParseError ( "Unable to parse map name" );
            break;
    }

    return true;
}
Example #29
0
/**
Parse a list of expressions
@returns an untagged tuple of expressions
*/
Tuple parseExprList(Input* input, char endCh)
{
    std::vector<Value> exprs;
 
    // Until the end of the list
    for (;;)
    {
        // Read whitespace
        input->eatWS();

        // If this is the end of the list
        if (input->matchCh(endCh))
        {
            break;
        }

        // Parse an expression
        auto expr = parseExpr(input);

        // Add the expression to the array
        exprs.push_back(expr);

        // Read whitespace
        input->eatWS();

        // If this is the end of the list
        if (input->matchCh(endCh))
        {
            break;
        }

        // If this is not the first element, there must be a separator
        if (!input->matchCh(','))
        {
            throw ParseError(input, "expected comma separator in list");
        }
    }

    return Tuple(exprs);
}
Example #30
0
static BOOL
FParseId(LEX * plex,
         int ch)
{
  LEX lex;

  if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ch == '_')
  {
    /*
     * Identifier 
     */
    int cch;

    lex.lt = ltId;
    cch = 0;
    do
    {

      /*
       * if (ch != '"') 
       */
      {
        lex.szId[cch] = (char)ch;                /* gratuitous cast - Unicode alert!!!! */
        cch++;
      }
      ch = *pchLex++;
      if (cch == cchIdMax - 1)
      {
        ParseError("Identifier too long", NULL);
        break;
      }
    }
    while ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')
           || (ch >= '0' && ch <= '9') || ch == '_');
    lex.szId[cch] = '\000';
    *plex = lex;
    return fTrue;
  }
  return fFalse;
}