当前位置: 首页>>代码示例>>C++>>正文


C++ Expression::Evaluate方法代码示例

本文整理汇总了C++中Expression::Evaluate方法的典型用法代码示例。如果您正苦于以下问题:C++ Expression::Evaluate方法的具体用法?C++ Expression::Evaluate怎么用?C++ Expression::Evaluate使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Expression的用法示例。


在下文中一共展示了Expression::Evaluate方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: expression

Value StringParser::expression(SymbolTable* scope, EvalContext& context)
{
    // Create a parser on just this section of the string
    size_t n = str.find('}', pos);

    if(n == string::npos) {
        Error(string("unterminated expression block"),0,0);
        pos = n;
        next();
        return Value();
    }

    string exstr = str.substr(pos, (n-pos));

    Parser parser(exstr);
    parser.SetErrorHandler(this);

    // Parse one expression and evaluate it
    Expression* e = parser.ParseExpression();
    Value result = e->Evaluate(scope, context);

    // Skip the expression block
    pos = n+1;
    next();

    return result;
}
开发者ID:jeffman,项目名称:ccscript_legacy,代码行数:27,代码来源:stringparser.cpp

示例2: UpdateGraph

// Read defintion and graph data, parse and evaluate it
bool AppWindow::UpdateGraph() {
int i;
StringReader *r;
Parser p(new Scanner(r = new StringReader()));
Expression *defs = view->graph->GetDefinitions();
    defs->SetText(program->view->Text());

    ColorMenuItem *c = (ColorMenuItem*)bg_color->FindMarked();
    if (c != NULL) view->graph->bg_color = c->GetColor();
    c = (ColorMenuItem*)axes_color->FindMarked();
    if (c != NULL) view->graph->axes_color = c->GetColor();

    if (!defs->ParseDefs(&p, r)) {
        statusLine->SetText("Syntax error in definitions");
        ShowErrorPosition(program->view, p.GetPos());
        return false;
    }
    
    view->ip->Reset();
    if (!defs->Evaluate(view->ip)) {
        statusLine->SetText("Error interpreting definitions");
        ShowErrorPosition(program->view, 0);
        return false;
    }

    ExprList *g = view->graph->GetGraphExprs();	
    for (i = 0; i <= 5; i++) {
        g->SetText(i, data->gCtrls[i]->Text());
    }

    if (!g->ParseExpr(&p, r, i)) {
        statusLine->SetText("Error parsing expression");
        ShowErrorPosition(data->gCtrls[i]->TextView(), p.GetPos());
        return false;
    }

    if (!g->Evaluate(view->ip, i)) {
        statusLine->SetText("Error evaluating expression");
        ShowErrorPosition(data->gCtrls[i]->TextView(), 0);
        return false;
    }
    return true;
}
开发者ID:HaikuArchives,项目名称:PlottingTools,代码行数:44,代码来源:Application.cpp

示例3: ExecuteStatement

void MethodCallStatement::ExecuteStatement()
{
    if (name=="print"){
            ExpressionList::iterator it = arguments->begin();
            while (it!=arguments->end()){
                    Expression* n = *it;
                    ResultValue nr = n->Evaluate();
                    //Revisar si exite la variable para evitar
                    // imprimir muchos errores
                    switch (nr.type){
                        case Int: cout << nr.value.int_value; break;
                        case String: cout << nr.value.string_value; break;
                        case Boolean: cout << nr.value.bool_value; break;
                        default: cout << "("<<line<<","<<column<<"): Tipo de dato no reconocido." << endl;
                    }
                    it++;
            }
            cout << endl;
    }
    else
            cout << " Test MethodCallStatement: "<<name<<endl;
    // Valor de retorno lo tiene que guardar en methods[name]

}
开发者ID:Liz30,项目名称:2016-CompII,代码行数:24,代码来源:Statement.cpp

示例4: HandleConditional

/// For if- and elsif- statements.
void Script::HandleConditional(String line)
{
    // Remove first part until (
    int index = line.Find('(');
    line = line.Part(index);
    /// Use expressions from the MathLib. First parse for functions to provide their values? Or...
    Expression exp;
    List<Variable> allVars = GameVars.GetAllExpressionVariables() + variables;
    exp.functionEvaluators = functionEvaluators; // Set evaluators.
    bool parseOK = exp.ParseExpression(line);
    if (!parseOK)
    {
        std::cout<<"\nParse error in expression "<<line;
        return;
    }
    ExpressionResult res = exp.Evaluate(allVars);
    bool statementTrue = res.GetBool();
    /// If statement is true, sign this row as finished.
    if (statementTrue)
    {
        // Set line finished to true so the actual content will be processed.
        lineFinished = true;
        // Set if-Processed to true so that no elsif- or else- clause will be handled.
        ScriptLevel & latest = stack.Last();
        latest.evaluatedAtLine = currentLine;
    }
    else 
    {
        // Check stuff.
        ScriptLevel & sl = stack.Last();
        int newRow = -1;
        int ifStack = 0;
        // If the statement is not true, find an else or endif block..!
        for (int i = currentLine+1; i < lines.Size(); ++i)
        {
            String l = lines[i];
            if (sl.type == ScriptLevel::WHILE_LOOP)
            {
                if (l.Contains("endwhile"))
                {
                    // Jump to next after, as regular stopping on endwhile will reboot the loop
                    newRow = i + 1;
                    stack.RemoveLast();
                    break; 
                }
            }
            if (sl.type == ScriptLevel::IF_CLAUSE)
            {
                if (l.Contains("elsif") || l.Contains("else") || l.Contains("endif"))
                {
                    if (ifStack == 0)
                    {
                        newRow = i; 
                        break;
                    }
                    if (l.Contains("endif"))
                        --ifStack;
                }
                else if (l.Contains("if"))
                    ++ifStack;
            }
        }
        assert(newRow > 0);
        // Process it next iteration.
        currentLine = newRow;
        lineProcessed = false;
        lineFinished = false;
        return;

    }
    if (lineFinished == false)
        assert(false && "Line not finished? Something is missing in the if/else/endif block!");	
}
开发者ID:erenik,项目名称:engine,代码行数:74,代码来源:Script.cpp

示例5: EvaluateLine

void Script::EvaluateLine(String & line)
{
    /// Default line processed once?
    lineProcessed = true;

    line.SetComparisonMode(String::NOT_CASE_SENSITIVE);
    // "80Gray50Alpha.png"
#define DEFAULT_TEXTURE_SOURCE	"black50Alpha.png"
#define DEFAULT_TEXT_SIZE_RATIO	0.3f
    
    /// Some state began, take not of it?
    if (line.Contains("Wait("))
    {
        WaitScript * wait = new WaitScript(line, this);
        wait->SetDeleteOnEnd(true);
        ScriptMan.PlayScript(wait);
    }
    else if (line.StartsWith("Key:"))
    {
        String keyStr = line.Tokenize(":")[1];
        keyStr.RemoveSurroundingWhitespaces();
        int keyCode = GetKeyForString(keyStr);
        assert(keyCode != 0);
        InputMan.KeyDown(MainWindow(), keyCode, false);
        InputMan.KeyUp(MainWindow(), keyCode);
        lineFinished = true;
    }
    else if (line.Contains("PlayScript("))
    {
        List<String> tokens = line.Tokenize("(),");
        // Source of script within the parenthesis.
        String source = tokens[1];
        bool wait = true;
        Script * scriptParent = this;
        if (tokens.Size() >= 3)
        {
            wait = tokens[2].ParseBool();
            if (!wait)
            {
                scriptParent = NULL;
                this->lineFinished = true;
            }
        }
        Script * script = new Script(source, scriptParent);
        script->source = source;
        bool loaded = script->Load();
        assert(loaded);
        ScriptMan.PlayScript(script);
    }
    else if (line == "DisableActiveUI")
    {
        InputMan.DisableActiveUI();
        lineFinished = true;
        uiDisabled = true;
    }
    else if (line == "EnableActiveUI")
    {
        InputMan.EnableActiveUI();
        lineFinished = true;
    }
    else if (line.Contains("PreloadTexturesInDirectory("))
    {
        // Fetch the stuff, do the buff
        String dir = line.Tokenize("()")[1];
        List<String> files;
        int num = GetFilesInDirectory(dir, files);
        for (int i = 0; i < files.Size(); ++i)
        {
            String path = dir + "/" + files[i];
            Texture * tex = TexMan.LoadTexture(path);
            Graphics.QueueMessage(new GMBufferTexture(tex));
        }
        lineFinished = true;
    }
    else if (line.Contains("Begin("))
    {
        String stateBeginning = line.Tokenize("()")[1];
        if (stateBeginning == "Cutscene")
        {
            BeginCutscene();
        }
        lineFinished = true;
    }
    else if (line.Contains("End("))
    {
        String stateEnding = line.Tokenize("()")[1];
        if (stateEnding == "Cutscene")
        {
            EndCutscene();
        }
        lineFinished = true;
    }
    else if (line.Contains("EndScript"))
    {
        // End it.
        scriptState = ENDING;
    }
    else if (line.Contains("EnterGameState("))
    {
        String name = line.Tokenize("()")[1];		
//.........这里部分代码省略.........
开发者ID:erenik,项目名称:engine,代码行数:101,代码来源:Script.cpp

示例6: ExecuteScriptHelper

bool ConsoleHandler::ExecuteScriptHelper(HttpRequest& request, HttpResponse& response,
    const String& command, const String& session, bool sandboxed)
{
    Log(LogInformation, "Console")
        << "Executing expression: " << command;

    ApiScriptFrame& lsf = l_ApiScriptFrames[session];
    lsf.Seen = Utility::GetTime();

    if (!lsf.Locals)
        lsf.Locals = new Dictionary();

    String fileName = "<" + Convert::ToString(lsf.NextLine) + ">";
    lsf.NextLine++;

    lsf.Lines[fileName] = command;

    Array::Ptr results = new Array();
    Dictionary::Ptr resultInfo = new Dictionary();
    Expression *expr = NULL;
    Value exprResult;

    try {
        expr = ConfigCompiler::CompileText(fileName, command);

        ScriptFrame frame;
        frame.Locals = lsf.Locals;
        frame.Self = lsf.Locals;
        frame.Sandboxed = sandboxed;

        exprResult = expr->Evaluate(frame);

        resultInfo->Set("code", 200);
        resultInfo->Set("status", "Executed successfully.");
        resultInfo->Set("result", Serialize(exprResult, 0));
    } catch (const ScriptError& ex) {
        DebugInfo di = ex.GetDebugInfo();

        std::ostringstream msgbuf;

        msgbuf << di.Path << ": " << lsf.Lines[di.Path] << "\n"
            << String(di.Path.GetLength() + 2, ' ')
            << String(di.FirstColumn, ' ') << String(di.LastColumn - di.FirstColumn + 1, '^') << "\n"
            << ex.what() << "\n";

        resultInfo->Set("code", 500);
        resultInfo->Set("status", String(msgbuf.str()));
        resultInfo->Set("incomplete_expression", ex.IsIncompleteExpression());

        Dictionary::Ptr debugInfo = new Dictionary();
        debugInfo->Set("path", di.Path);
        debugInfo->Set("first_line", di.FirstLine);
        debugInfo->Set("first_column", di.FirstColumn);
        debugInfo->Set("last_line", di.LastLine);
        debugInfo->Set("last_column", di.LastColumn);
        resultInfo->Set("debug_info", debugInfo);
    } catch (...) {
        delete expr;
        throw;
    }
    delete expr;

    results->Add(resultInfo);

    Dictionary::Ptr result = new Dictionary();
    result->Set("results", results);

    response.SetStatus(200, "OK");
    HttpUtility::SendJsonBody(response, result);

    return true;
}
开发者ID:Thomas-Gelf,项目名称:icinga2,代码行数:72,代码来源:consolehandler.cpp

示例7: CreateObject

bool ConfigObjectUtility::CreateObject(const Type::Ptr& type, const String& fullName,
    const String& config, const Array::Ptr& errors)
{
    if (!ConfigPackageUtility::PackageExists("_api")) {
        ConfigPackageUtility::CreatePackage("_api");

        String stage = ConfigPackageUtility::CreateStage("_api");
        ConfigPackageUtility::ActivateStage("_api", stage);
    }

    String path = GetObjectConfigPath(type, fullName);
    Utility::MkDirP(Utility::DirName(path), 0700);

    if (Utility::PathExists(path)) {
        errors->Add("Configuration file '" + path + "' already exists.");
        return false;
    }

    std::ofstream fp(path.CStr(), std::ofstream::out | std::ostream::trunc);
    fp << config;
    fp.close();

    Expression *expr = ConfigCompiler::CompileFile(path, String(), "_api");

    try {
        ActivationScope ascope;

        ScriptFrame frame;
        expr->Evaluate(frame);
        delete expr;
        expr = NULL;

        WorkQueue upq;
        std::vector<ConfigItem::Ptr> newItems;

        if (!ConfigItem::CommitItems(ascope.GetContext(), upq, newItems) || !ConfigItem::ActivateItems(upq, newItems, true)) {
            if (errors) {
                if (unlink(path.CStr()) < 0 && errno != ENOENT) {
                    BOOST_THROW_EXCEPTION(posix_error()
                        << boost::errinfo_api_function("unlink")
                        << boost::errinfo_errno(errno)
                        << boost::errinfo_file_name(path));
                }

                for (const boost::exception_ptr& ex : upq.GetExceptions()) {
                    errors->Add(DiagnosticInformation(ex));
                }
            }

            return false;
        }

        ApiListener::UpdateObjectAuthority();
    } catch (const std::exception& ex) {
        delete expr;

        if (unlink(path.CStr()) < 0 && errno != ENOENT) {
            BOOST_THROW_EXCEPTION(posix_error()
                << boost::errinfo_api_function("unlink")
                << boost::errinfo_errno(errno)
                << boost::errinfo_file_name(path));
        }

        if (errors)
            errors->Add(DiagnosticInformation(ex));

        return false;
    }

    return true;
}
开发者ID:leeclemens,项目名称:icinga2,代码行数:71,代码来源:configobjectutility.cpp

示例8: DoEvaluate

ExpressionResult IncludeExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const
{
    if (frame.Sandboxed)
        BOOST_THROW_EXCEPTION(ScriptError("Includes are not allowed in sandbox mode.", m_DebugInfo));

    Expression *expr;
    String name, path, pattern;

    switch (m_Type) {
        case IncludeRegular:
            {
                ExpressionResult pathres = m_Path->Evaluate(frame, dhint);
                CHECK_RESULT(pathres);
                path = pathres.GetValue();
            }

            expr = ConfigCompiler::HandleInclude(m_RelativeBase, path, m_SearchIncludes, m_Zone, m_Package, m_DebugInfo);
            break;

        case IncludeRecursive:
            {
                ExpressionResult pathres = m_Path->Evaluate(frame, dhint);
                CHECK_RESULT(pathres);
                path = pathres.GetValue();
            }

            {
                ExpressionResult patternres = m_Pattern->Evaluate(frame, dhint);
                CHECK_RESULT(patternres);
                pattern = patternres.GetValue();
            }

            expr = ConfigCompiler::HandleIncludeRecursive(m_RelativeBase, path, pattern, m_Zone, m_Package, m_DebugInfo);
            break;

        case IncludeZones:
            {
                ExpressionResult nameres = m_Name->Evaluate(frame, dhint);
                CHECK_RESULT(nameres);
                name = nameres.GetValue();
            }

            {
                ExpressionResult pathres = m_Path->Evaluate(frame, dhint);
                CHECK_RESULT(pathres);
                path = pathres.GetValue();
            }

            {
                ExpressionResult patternres = m_Pattern->Evaluate(frame, dhint);
                CHECK_RESULT(patternres);
                pattern = patternres.GetValue();
            }

            expr = ConfigCompiler::HandleIncludeZones(m_RelativeBase, name, path, pattern, m_Package, m_DebugInfo);
            break;
    }

    ExpressionResult res(Empty);

    try {
        res = expr->Evaluate(frame, dhint);
    } catch (const std::exception&) {
        delete expr;
        throw;
    }

    delete expr;

    return res;
}
开发者ID:wopfel,项目名称:icinga2,代码行数:71,代码来源:expression.cpp

示例9: Main


//.........这里部分代码省略.........

    Application::DeclareZonesDir(Application::GetSysconfDir() + "/icinga2/zones.d");
    Application::DeclareRunAsUser(ICINGA_USER);
    Application::DeclareRunAsGroup(ICINGA_GROUP);
    Application::DeclareConcurrency(boost::thread::hardware_concurrency());

    if (!ScriptGlobal::Exists("UseVfork"))
#ifdef __APPLE__
        ScriptGlobal::Set("UseVfork", false);
#else /* __APPLE__ */
        ScriptGlobal::Set("UseVfork", true);
#endif /* __APPLE__ */

    ScriptGlobal::Set("AttachDebugger", false);

    LogSeverity logLevel = Logger::GetConsoleLogSeverity();
    Logger::SetConsoleLogSeverity(LogWarning);

    Loader::LoadExtensionLibrary("cli");

    po::options_description visibleDesc("Global options");

    visibleDesc.add_options()
        ("help,h", "show this help message")
        ("version,V", "show version information")
#ifndef _WIN32
        ("color", "use VT100 color codes even when stdout is not a terminal")
#endif /* _WIN32 */
        ("define,D", po::value<std::vector<std::string> >(), "define a constant")
        ("app,a", po::value<std::string>(), "application library name (default: icinga)")
        ("library,l", po::value<std::vector<std::string> >(), "load a library")
        ("include,I", po::value<std::vector<std::string> >(), "add include search directory")
        ("log-level,x", po::value<std::string>(), "specify the log level for the console log");

    po::options_description hiddenDesc("Hidden options");

    hiddenDesc.add_options()
#ifndef _WIN32
        ("no-stack-rlimit", "used internally, do not specify manually")
#else /* _WIN32 */
        ("no-stack-rlimit", "used internally, do not specify manually")
#endif /* _WIN32 */
        ("arg", po::value<std::vector<std::string> >(), "positional argument");

    po::positional_options_description positionalDesc;
    positionalDesc.add("arg", -1);

    String cmdname;
    CLICommand::Ptr command;
    po::variables_map vm;

    try {
        CLICommand::ParseCommand(argc, argv, visibleDesc, hiddenDesc, positionalDesc,
            vm, cmdname, command, autocomplete);
    } catch (const std::exception& ex) {
        Log(LogCritical, "icinga-app")
            << "Error while parsing command-line options: " << ex.what();
        return EXIT_FAILURE;
    }

    String initconfig = Application::GetSysconfDir() + "/icinga2/init.conf";

    if (Utility::PathExists(initconfig)) {
        Expression *expression;
        try {
            expression = ConfigCompiler::CompileFile(initconfig);

            ScriptFrame frame;
            expression->Evaluate(frame);
        } catch (const std::exception& ex) {
            delete expression;

            Log(LogCritical, "config", DiagnosticInformation(ex));
            return EXIT_FAILURE;
        }

        delete expression;
    }

#ifndef _WIN32
    if (vm.count("color")) {
        Console::SetType(std::cout, Console_VT100);
        Console::SetType(std::cerr, Console_VT100);
    }
#endif /* _WIN32 */

    if (vm.count("define")) {
        BOOST_FOREACH(const String& define, vm["define"].as<std::vector<std::string> >()) {
            String key, value;
            size_t pos = define.FindFirstOf('=');
            if (pos != String::NPos) {
                key = define.SubStr(0, pos);
                value = define.SubStr(pos + 1);
            } else {
                key = define;
                value = "1";
            }
            ScriptGlobal::Set(key, value);
        }
    }
开发者ID:Nadahar,项目名称:icinga2,代码行数:101,代码来源:icinga.cpp


注:本文中的Expression::Evaluate方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。