Ejemplo n.º 1
0
int main()
{
	AbstractSyntaxTree AST;

	ASTNode Root;
	Root.name = "Root";
	Root.type = "Node";
	Root.startLineCount = 1;
	Root.endLineCount = 0;
	AST.SetRoot(&Root);
	
	ASTNode N1;
	N1.name = "Node 1";
	N1.type = "Node";
	N1.startLineCount = 1;
	N1.endLineCount = 0;
	Root.GetChildren().push_back(&N1);
	
	ASTNode N2;
	N2.name = "Node 2";
	N2.type = "Node";
	N2.startLineCount = 1;
	N2.endLineCount = 0;
	N1.GetChildren().push_back(&N2);


	ASTNode N3;
	N3.name = "Node 3";
	N3.type = "Node";
	N3.startLineCount = 1;
	N3.endLineCount = 0;
	Root.GetChildren().push_back(&N3);	
	AST.TreeWalk(AST.GetRoot());
}
Ejemplo n.º 2
0
void TraceEvaluationTest::RunTest() {
    AbstractSyntaxTree parseResult;
    Parser parser(query);

    if (!parser.parse(parseResult)) {
        MS_throw(multiscale::TestException, ERR_MSG_TEST);
    }

    evaluationResult = parseResult.evaluate(trace, multiscaleArchitectureGraph);
}
Ejemplo n.º 3
0
int main(int argc, char *argv[]) {
  // Setup pretty stack trace printers.
  llvm::PrettyStackTraceProgram X(argc, argv);
  llvm::sys::PrintStackTraceOnErrorSignal();

  // Automatically call llvm_shutdown on exit -- release resources used by
  // ManagedStatic instances.
  llvm::llvm_shutdown_obj Y;

  llvm::cl::ParseCommandLineOptions(argc, argv, "ACSE standalone parser");

  llvm::OwningPtr<llvm::MemoryBuffer> Input;
  llvm::OwningPtr<llvm::tool_output_file> Output;

  llvm::error_code ErrorCode;
  std::string ErrorInfo;

  ErrorCode = llvm::MemoryBuffer::getFileOrSTDIN(InputFileName, Input);
  if(ErrorCode) {
    llvm::errs() << "Error opening input file '" << InputFileName << "'\n";
    return EXIT_FAILURE;
  }

  Output.reset(new llvm::tool_output_file(OutputFileName.c_str(), ErrorInfo));
  if(!ErrorInfo.empty()) {
    llvm::errs() << ErrorInfo << "\n";
    return EXIT_FAILURE;
  }

  llvm::SourceMgr Srcs;
  Srcs.AddNewSourceBuffer(Input.take(), llvm::SMLoc());

  Lexer Lex(Srcs);
  Parser Parse(Lex);

  Parse.Run();

  if(!Parse.Success())
    return EXIT_FAILURE;

  AbstractSyntaxTree *AST = Parse.GetAST();

  if(ViewAST)
    AST->View();
  else
    AST->Dump(Output->os());

  Output->keep();

  return EXIT_SUCCESS;
}
Ejemplo n.º 4
0
void KernelSourceParser::WorkerThread::parseFile(const QString &fileName)
{
    QString file = _parser->_srcDir.absoluteFilePath(fileName);

    if (!_parser->_srcDir.exists(fileName)) {
        _parser->shellErr(QString("File not found: %1").arg(file));
        return;
    }

    AbstractSyntaxTree ast;
    ASTBuilder builder(&ast);
    KernelSourceTypeEvaluator eval(&ast, _parser->_factory);

    try {
        // Parse the file
        if (!_stopExecution && builder.buildFrom(file) > 0) {
            BugReport::reportErr(QString("Could not recover after %1 errors "
                                         "while parsing file:\n%2")
                                 .arg(ast.errorCount())
                                 .arg(file));
            return;
        }

        // Evaluate types
        if (!_stopExecution && !eval.evaluateTypes()) {
            // Only throw exception if evaluation was not interrupted
            if (!_stopExecution && !eval.walkingStopped())
                BugReport::reportErr(QString("Error evaluating types in %1")
                                     .arg(file));
        }
    }
    catch (TypeEvaluatorException& e) {
        // Print the source of the embedding external declaration
        const ASTNode* n = e.ed.srcNode;
        while (n && n->parent && n->type != nt_function_definition)
            n = n->parent;
        eval.reportErr(e, n, &e.ed);
    }
    catch (ExpressionEvalException& e) {
        // Make sure we at least have the full postfix expression
        const ASTNode* n = e.node;
        for (int i = 0;
             i < 3 && n && n->parent && n->type != nt_function_definition;
             ++i)
            n = n->parent;
        eval.reportErr(e, n, 0);
    }
    catch (GenericException& e) {
        eval.reportErr(e, 0, 0);
    }
}
Ejemplo n.º 5
0
//  Main program
int main(int argc, char **argv) {
    std::string test;
    SpatialTemporalTrace trace;
    MultiscaleArchitectureGraph multiscaleArchitectureGraph;
    AbstractSyntaxTree result;

    initializeTrace(trace);

    std::cout << "/////////////////////////////////////////////////////////\n\n";
    std::cout << "\tA multiscale multidimensional logic query parser and evaluator...\n\n";
    std::cout << "/////////////////////////////////////////////////////////\n\n";

    std::cout
        << "Please enter a multiscale multidimensional logic query (or \"q\" to exit):" << std::endl
        << std::endl;


    while (getline(std::cin, test)) {
        if (test.compare("q") == 0) {
            break;
        }

        Parser parser(test);

        try {
            if (parser.parse(result)) {
                std::cout << "-----------------------------------------------------" << std::endl;
                std::cout << " Parsing succeeded"
                          << " and the AST evaluates to " 
                          << (result.evaluate(trace, multiscaleArchitectureGraph) ? "true" : "false")
                          << "!" << std::endl;
                std::cout << "-----------------------------------------------------" << std::endl << std::endl;
            } else {
                std::cout << "-----------------------------------------------------" << std::endl;
                std::cout << " Parsing failed!" << std::endl;
                std::cout << "-----------------------------------------------------" << std::endl << std::endl;
            }
        } catch(const std::exception &e) {
            ExceptionHandler::printDetailedErrorMessage(e);

            return EXEC_ERR_CODE;
        } catch(...) {
            std::cerr << "Exception of unknown type!" << std::endl;
        }
    }

    return -1;
}
Ejemplo n.º 6
0
int main(int argc, char** argv)
{
    vector<int> vt(128);
    vt.clear();
    //vt.shrink_to_fit();
    cout << "vector test: " << vt.capacity() << endl;

    for (int i = 1; i < argc; ++i)
    {
        auto treeFood = ParseFile(argv[i]);

        cout << "parsed " << treeFood.tokens.size() << " tokens\n";

        for (auto value : treeFood.integers)
        {
            cout << "integer value " << value.value << " @ "
                << value.index << endl;
        }

        for (auto text : treeFood.strings)
        {
            cout << "string value [" << text.value << " @ "
                << text.index << ']' << endl;
        }

        for (auto token : treeFood.tokens)
        {
            View<const char> v
                {treeFood.source.data() + token.start, token.length};

            cout << TokenTypeString(token.type) << " @ row " << token.row
                << " col " << token.column << " " << v << '\n';
        }

        AbstractSyntaxTree ast;
        ast.Eat(treeFood);
    }

    if (argc < 2)
    {
        cout << "usage: " << argv[0] << " <path>" << endl;
    }

    return 0;
}
Ejemplo n.º 7
0
void
NumericCsvModelCheckingPerformanceTest::EvaluateLogicProperties(
    const std::vector<std::string> &logicProperties,
    SpatialTemporalTrace &timeSeries
) {
    AbstractSyntaxTree abstractSyntaxTree;
    MultiscaleArchitectureGraph multiscaleArchitectureGraph;

    for (const std::string &logicProperty : logicProperties) {
        // Create a new parser for the provided logic property
        Parser parser(logicProperty);

        // Parse the logic property and create the corresponding abstract syntax tree
        parser.parse(abstractSyntaxTree);

        // Evaluate the abstract syntax tree considering the provided time series data
        abstractSyntaxTree.evaluate(timeSeries, multiscaleArchitectureGraph);
    }
}
Ejemplo n.º 8
0
const BaseType* ExpressionAction::parseTypeStr(
        const QString &xmlFile, const TypeRule *rule, SymFactory *factory,
        const QString& what, const QString& typeStr, QString& id,
        bool *usesTypeId) const
{
    // Did we get a type name or a type ID?
    if (typeStr.startsWith("0x")) {
        if (usesTypeId)
            *usesTypeId = true;
        QStringList typeStrParts = typeStr.split(QRegExp("\\s+"));
        if (typeStrParts.isEmpty() || typeStrParts.size() > 2)
            typeRuleError2(xmlFile, srcLine(), -1,
                           QString("The specified %0 '%1' is invalid (expected "
                                   "a type ID and an identifier, e.g. '0x89ab "
                                   "src').")
                                .arg(what)
                                .arg(typeStr));

        QString typeIdStr = typeStrParts.first();
        bool ok = false;
        int typeId = typeIdStr.right(typeIdStr.size() - 2).toUInt(&ok, 16);
        if (!ok)
            typeRuleError2(xmlFile, srcLine(), -1,
                           QString("The type ID '%0' for the %1 is invalid.")
                                .arg(typeIdStr)
                                .arg(what));

        const BaseType* ret = factory->findBaseTypeById(typeId);
        if (!ret)
            typeRuleError2(xmlFile, srcLine(), -1,
                           QString("The type ID '%0' for the %1 does not exist.")
                                .arg(typeIdStr)
                                .arg(what));
        if (typeStrParts.size() > 1)
            id = typeStrParts.last();
        return ret;
    }
    else if (usesTypeId)
        *usesTypeId = false;

    // We got a type name expression, so parse it with the C parser
    AbstractSyntaxTree ast;
    ASTBuilder builder(&ast, factory);

    // Parse the code
    QByteArray code = QString("void %1(%2);").arg("__FUNCTION__").arg(typeStr).toAscii();
    if (builder.buildFrom(code) != 0)
        typeRuleError3(xmlFile, srcLine(), -1, TypeRuleException::ecSyntaxError,
                       QString("Syntax error in %0: %1")
                            .arg(what)
                            .arg(typeStr));

    QList<const ASTNode*> paramNodes =
            ASTNodeFinder::find(nt_parameter_declaration, &ast);
    // We might have more than one parameter for function pointer types, but the
    // first one is the one in __FUNCTION__()
    assert(paramNodes.size() > 0);
    const ASTNode* paramNode = paramNodes.first();

    // Do we have a declarator with or without an identifier?
    id.clear();
    const ASTNode* d_ad = paramNode->u.parameter_declaration.declarator_list ?
                paramNode->u.parameter_declaration.declarator_list->item : 0;
    if (d_ad && d_ad->type == nt_declarator)  {
        // Find the direct declaratior with identifier
        const ASTNode* dd = d_ad->u.declarator.direct_declarator;
        while (dd && !dd->u.direct_declarator.identifier) {
            dd = dd->u.direct_declarator.declarator
                   ->u.declarator.direct_declarator;
        }
        assert(dd != 0);
        assert(dd->u.direct_declarator.identifier);
        id = ast.antlrTokenToStr(dd->u.direct_declarator.identifier);
    }

    KernelSourceTypeEvaluator t_eval(&ast, factory);

    // Evaluate type of parameter_declaration
    ASTType* astType = t_eval.typeofNode(paramNode);
    if (!astType)
        typeRuleError2(xmlFile, srcLine(), -1,
                       QString("Error parsing expression: %1").arg(QString(code)));

    // Search correspondig BaseType
    FoundBaseTypes found =
            factory->findBaseTypesForAstType(astType, &t_eval, false);
    if (found.types.isEmpty())
        typeRuleError2(xmlFile, srcLine(), -1,
                       QString("Cannot find %1: %2").arg(what).arg(QString(code)));
    else if (found.types.size() > 1) {
        static const int type_ambiguous = -1;
        static const int no_type_found = -2;
        int match_idx = type_ambiguous;

        if (rule) {
            match_idx = no_type_found;
            // Find a unique type that matches the filter
            for (int i = 0; i < found.types.size(); ++i) {
                if (rule->match(found.types.at(i)) ||
                    rule->match(found.typesNonPtr.at(i)))
                {
                    if (match_idx < 0)
                        match_idx = i;
                    else {
                        const BaseType* t1 =
                                found.typesNonPtr.at(match_idx)->dereferencedBaseType(BaseType::trLexical);
                        const BaseType* t2 =
                                found.typesNonPtr.at(i)->dereferencedBaseType(BaseType::trLexical);
                        // Compare the hashes of the non-lexical types, only if
                        // they are different the type is ambiguous.
                        if (t1->hash() != t2->hash()) {
                            match_idx = type_ambiguous;
                            break;
                        }
                        else {
                            // Prefer the type that exactly corresponds to the
                            // ASTType
                            if (found.typesNonPtr.at(i)->type() == found.astTypeNonPtr->type())
                                match_idx = i;
                        }
                    }
                }
            }
        }

        if (match_idx >= 0)
            return found.types.at(match_idx);
        else if (match_idx == type_ambiguous)
            typeRuleError3(xmlFile, srcLine(), -1, TypeRuleException::ecTypeAmbiguous,
                           QString("The %1 is ambiguous, %2 types found for: %3")
                           .arg(what)
                           .arg(found.types.size())
                           .arg(typeStr));
        else
            typeRuleError3(xmlFile, srcLine(), -1, TypeRuleException::ecNotCompatible,
                           QString("Cannot find any compatible type for the %1: %2")
                           .arg(what).arg(typeStr));
    }
    else
        return found.types.first();

    return 0;
}