<commit_before>#pragma sw require header org.sw.demo.ragel
#pragma sw require header org.sw.demo.lexxmark.winflexbison.bison-master

#pragma sw header on

static void gen_stamp(const DependencyPtr &tools_stamp_gen, NativeExecutedTarget &t)
{
    {
        auto d = t + tools_stamp_gen;
        d->setDummy(true);
    }

    auto out = t.BinaryPrivateDir / "stamp.h.in";

    SW_MAKE_COMMAND_AND_ADD(c, t);
    c->always = true;
    c->setProgram(tools_stamp_gen);
    c->redirectStdout(out);
    c->addOutput(out);
    t += out;
}

static void gen_sqlite2cpp(const DependencyPtr &tools_sqlite2cpp, NativeExecutedTarget &t, const path &sql_file, const path &out_file, const String &ns)
{
    auto c = t.addCommand();
    c << cmd::prog(tools_sqlite2cpp)
        << cmd::in(sql_file)
        << cmd::out(out_file)
        << ns;
}

static void embed(const DependencyPtr &embedder, NativeExecutedTarget &t, const path &in)
{
    struct EmbedCommand : ::sw::driver::Command
    {
        using Command::Command;

        std::shared_ptr<Command> clone() const override
        {
            return std::make_shared<EmbedCommand>(*this);
        }

    private:
        void postProcess1(bool ok) override
        {
            for (auto &line : split_lines(out.text))
            {
                static const auto prefix = "embedding: "s;
                boost::trim(line);
                for (auto &f : outputs)
                    File(f, *fs).addImplicitDependency(line.substr(prefix.size()));
            }
        }
    };

    if (in.is_absolute())
        throw std::runtime_error("embed: in must be relative to SourceDir");

    auto f = t.SourceDir / in;
    auto out = t.BinaryDir / in.parent_path() / in.filename().stem();

    auto c = t.addCommand();
    c.c = std::make_shared<EmbedCommand>(c.c->swctx);
    SW_INTERNAL_INIT_COMMAND(c.c, t);
    c << cmd::prog(embedder)
        << cmd::wdir(f.parent_path())
        << cmd::in(in)
        << cmd::out(out)
        ;
    t += IncludeDirectory(out.parent_path()); // but remove this later
}

static Files syncqt(const DependencyPtr &sqt, NativeExecutedTarget &t, const Strings &modules)
{
    Files out;
    auto i = t.BinaryDir / "include";
    auto v = t.getPackage().version.toString();
    for (auto &m : modules)
    {
        fs::create_directories(i / m / v / m);

        auto c = t.addCommand();
        c << cmd::prog(sqt)
            << "-s" << t.SourceDir
            << "-b" << t.BinaryDir
            << "-m" << m
            << "-v" << v
            << cmd::end()
            << cmd::out(i / m / m)
            ;
        c.c->strict_order = 1; // run before moc
        out.insert(i / m / m);
        //t.Interface += i / m / m; makes cyclic deps

        t.Public += IncludeDirectory(i);
        t.Public += IncludeDirectory(i / m);
        t.Public += IncludeDirectory(i / m / v);
        t.Public += IncludeDirectory(i / m / v / m);
    }
    return out;
}

#pragma sw header off

void configure(Build &s)
{
    if (s.isConfigSelected("cyg2mac"))
        s.loadModule("utils/cc/cygwin2macos.cpp").call<void(Solution&)>("configure", s);
}

void build(Solution &s)
{
    auto &p = s.addProject("primitives", "master");
    p += "https://github.com/egorpugin/primitives"_git;

    auto setup_primitives_no_all_sources = [](auto &t)
    {
        path p = "src";
        auto n = t.getPackage().ppath.slice(t.getPackage().ppath.isAbsolute() ? 3 : 1);
        auto n2 = n;
        while (!n.empty())
        {
            p /= n.front();
            n = n.slice(1);
        }
        t.ApiName = "PRIMITIVES_" + boost::to_upper_copy(n2.toString("_")) + "_API";
        t.CPPVersion = CPPLanguageStandard::CPP17;
        t.PackageDefinitions = true;
        // not all code works with this yet (e.g. hh.date)
        //t.Public.CompileOptions.push_back("-Zc:__cplusplus");
        return p;
    };

    auto setup_primitives = [&setup_primitives_no_all_sources](auto &t)
    {
        auto p = setup_primitives_no_all_sources(t);
        t.setRootDirectory(p);
        // explicit!
        t += "include/.*"_rr;
        t += "src/.*"_rr;
    };

#define ADD_LIBRARY_WITH_NAME(var, name)          \
    auto &var = p.addTarget<LibraryTarget>(name); \
    setup_primitives(var)

#define ADD_LIBRARY(x) ADD_LIBRARY_WITH_NAME(x, #x)

    ADD_LIBRARY(error_handling);

    auto &templates = p.addTarget<StaticLibraryTarget>("templates");
    setup_primitives(templates);
    templates -= "org.sw.demo.boost.stacktrace-1"_dep;
    if (templates.getSettings().Native.ConfigurationType != ConfigurationType::Release &&
        templates.getSettings().Native.ConfigurationType != ConfigurationType::MinimalSizeRelease
        )
    {
        templates += "USE_STACKTRACE"_def;
        templates += "org.sw.demo.boost.stacktrace-1"_dep;
        //if (s.getSettings().TargetOS.Type == OSType::Windows)
            //templates += "dbgeng.lib"_slib;
    }

    ADD_LIBRARY(string);
    string.Public += "org.sw.demo.boost.algorithm-1"_dep;

    ADD_LIBRARY(filesystem);
    filesystem.Public += string, templates,
        "org.sw.demo.boost.filesystem-1"_dep,
        "org.sw.demo.boost.thread-1"_dep,
        "org.sw.demo.grisumbras.enum_flags-master"_dep;

    ADD_LIBRARY(file_monitor);
    file_monitor.Public += filesystem,
        "pub.egorpugin.libuv"_dep;

    ADD_LIBRARY(emitter);
    emitter.Public += filesystem;

    ADD_LIBRARY(executor);
    executor.Public += templates,
        "org.sw.demo.boost.asio-1"_dep,
        "org.sw.demo.boost.system-1"_dep;

    ADD_LIBRARY(command);
    command.Public += file_monitor,
        "org.sw.demo.boost.process-1"_dep;
    if (command.getSettings().TargetOS.Type == OSType::Windows)
        command.Public += "Shell32.lib"_slib;

    ADD_LIBRARY(date_time);
    date_time.Public += string,
        "org.sw.demo.boost.date_time-1"_dep;

    ADD_LIBRARY(lock);
    lock.Public += filesystem,
        "org.sw.demo.boost.interprocess-1"_dep;

    ADD_LIBRARY(log);
    log.Public += "org.sw.demo.boost.log-1"_dep;

    ADD_LIBRARY(cron);
    cron.Public += executor, log;

    ADD_LIBRARY(yaml);
    yaml.Public += string, templates,
        "org.sw.demo.jbeder.yaml_cpp-master"_dep;

    ADD_LIBRARY(pack);
    pack.Public += filesystem, templates,
        "org.sw.demo.libarchive.libarchive-3"_dep;

    ADD_LIBRARY(patch);
    patch.Public += filesystem, templates;

    ADD_LIBRARY(http);
    http.Public += filesystem, templates,
        "org.sw.demo.badger.curl.libcurl-7"_dep;
    if (http.getSettings().TargetOS.Type == OSType::Windows)
        http.Public += "Winhttp.lib"_slib;

    ADD_LIBRARY(hash);
    hash.Public += filesystem,
        "org.sw.demo.aleksey14.rhash-1"_dep,
        "org.sw.demo.openssl.crypto-1.*.*.*"_dep;

    ADD_LIBRARY(win32helpers);
    win32helpers.Public += "BOOST_DLL_USE_STD_FS"_def;
    win32helpers.Public += filesystem,
        "org.sw.demo.boost.dll-1"_dep,
        "org.sw.demo.boost.algorithm-1"_dep;
    if (win32helpers.getSettings().TargetOS.Type == OSType::Windows)
    {
        win32helpers.Public += "UNICODE"_d;
        win32helpers += "Shell32.lib"_slib, "Ole32.lib"_slib, "Advapi32.lib"_slib, "user32.lib"_slib;
    }

    ADD_LIBRARY_WITH_NAME(db_common, "db.common");
    db_common.Public += filesystem, templates,
        "org.sw.demo.imageworks.pystring-1"_dep;

    ADD_LIBRARY_WITH_NAME(db_sqlite3, "db.sqlite3");
    db_sqlite3.Public += db_common, "org.sw.demo.sqlite3"_dep;

    ADD_LIBRARY_WITH_NAME(db_postgresql, "db.postgresql");
    db_postgresql.Public += db_common, "org.sw.demo.jtv.pqxx-*"_dep;

    auto &main = p.addTarget<StaticLibraryTarget>("main");
    setup_primitives(main);
    main.Public += error_handling;

    ADD_LIBRARY(settings);
    settings.Public += "include"_idir;
    settings.Public += yaml, filesystem, templates,
        "pub.egorpugin.llvm_project.llvm.support_lite-master"_dep;
    gen_flex_bison_pair("org.sw.demo.lexxmark.winflexbison-master"_dep, settings, "LALR1_CPP_VARIANT_PARSER", "src/settings");
    gen_flex_bison_pair("org.sw.demo.lexxmark.winflexbison-master"_dep, settings, "LALR1_CPP_VARIANT_PARSER", "src/path");

    ADD_LIBRARY(symbol);
    symbol.Public += "BOOST_DLL_USE_STD_FS"_def;
    symbol.Public += filesystem, "org.sw.demo.boost.dll-1"_dep;

    ADD_LIBRARY_WITH_NAME(sw_settings, "sw.settings");
    sw_settings.Public += settings;
    sw_settings -= "src/sw.settings.program_name.cpp";
    //sw_settings.Interface += "src/sw.settings.program_name.cpp";

    ADD_LIBRARY(version);
    version.Public += "include"_idir;
    //version.Public += "src/version.natvis";
    version += "src/version.natvis";
    version.Public += string, templates,
        "org.sw.demo.fmt-*"_dep,
        "org.sw.demo.boost.container_hash-1"_dep,
        "org.sw.demo.imageworks.pystring-1"_dep;
    gen_ragel("org.sw.demo.ragel-6"_dep, version, "src/version.rl");
    gen_flex_bison_pair("org.sw.demo.lexxmark.winflexbison-master"_dep, version, "GLR_CPP_PARSER", "src/range");

    ADD_LIBRARY(source);
    source.Public += command, hash, http, pack, version, yaml,
        "org.sw.demo.nlohmann.json"_dep;

    //ADD_LIBRARY(object_path);
    //object_path.Public += string, templates;

    auto &sw_main = p.addTarget<StaticLibraryTarget>("sw.main");
    setup_primitives(sw_main);
    sw_main.Public += "BOOST_DLL_USE_STD_FS"_def;
    sw_main.Public += main, sw_settings,
        "org.sw.demo.boost.dll-1"_dep;
    sw_main.Interface.LinkLibraries.push_back(main.getImportLibrary()); // main itself
    sw_main.Interface.LinkLibraries.push_back(sw_main.getImportLibrary()); // then me (self, sw.main)
    sw_main.Interface.LinkLibraries.push_back(sw_settings.getImportLibrary()); // then sw.settings
    if (sw_main.getSettings().TargetOS.Type == OSType::Windows)
    {
        sw_main.Public +=
            "org.sw.demo.google.breakpad.client.windows.handler-master"_dep,
            "org.sw.demo.google.breakpad.client.windows.crash_generation.client-master"_dep,
            "org.sw.demo.google.breakpad.client.windows.crash_generation.server-master"_dep
            ;
    }

    auto &tools_embedder = p.addTarget<ExecutableTarget>("tools.embedder");
    setup_primitives_no_all_sources(tools_embedder);
    tools_embedder += "src/tools/embedder.cpp";
    tools_embedder += filesystem, sw_main;

    auto &tools_sqlite2cpp = p.addTarget<ExecutableTarget>("tools.sqlpp11.sqlite2cpp");
    setup_primitives_no_all_sources(tools_sqlite2cpp);
    tools_sqlite2cpp += "src/tools/sqlpp11.sqlite2cpp.cpp";
    tools_sqlite2cpp += filesystem, emitter, sw_main, "org.sw.demo.sqlite3"_dep;

    auto &tools_syncqt = p.addTarget<ExecutableTarget>("tools.syncqt");
    setup_primitives_no_all_sources(tools_syncqt);
    tools_syncqt += "src/tools/syncqt.cpp";
    tools_syncqt += filesystem, sw_main;

    auto &stamp_gen = p.addTarget<ExecutableTarget>("tools.stamp_gen");
    setup_primitives_no_all_sources(stamp_gen);
    stamp_gen += "src/tools/stamp_gen.cpp";

    return;

    auto &test = p.addDirectory("test");
    test.Scope = TargetScope::Test;

    auto add_test = [&test, &s, &sw_main](const String &name) -> decltype(auto)
    {
        auto &t = test.addTarget<ExecutableTarget>(name);
        t.CPPVersion = CPPLanguageStandard::CPP17;
        t += path("src/" + name + ".cpp");
        t += "org.sw.demo.catchorg.catch2-*"_dep;
        if (t.getCompilerType() == CompilerType::MSVC)
            t.CompileOptions.push_back("-bigobj");
        //else if (t.getCompilerType() == CompilerType::GNU)
            //t.CompileOptions.push_back("-Wa,-mbig-obj");
        t += sw_main;
        return t;
    };

    auto &test_main = add_test("main");
    test_main += command, date_time,
        executor, hash, yaml, emitter, http,
        "org.sw.demo.nlohmann.json-*"_dep;

    auto &test_db = add_test("db");
    test_db += command, db_sqlite3, db_postgresql, date_time,
        executor, hash, yaml;

    auto &test_settings = add_test("settings");
    test_settings.PackageDefinitions = true;
    test_settings += settings;

    auto &test_version = add_test("version");
    test_version += version;

    auto &test_source = add_test("source");
    test_source += source;

    auto &test_patch = add_test("patch");
    test_patch += patch;

    auto tm = s.addTest(test_main);
    tm.c->addPathDirectory(getenv("PATH"));
    /*auto tdb = s.addTest(test_db);
    if (test_db.getSettings().TargetOS.Type == OSType::Windows)
    {
        tdb.c->addLazyAction([&s, c = tdb.c]
        {
            auto &pq = s.getTarget<LibraryTarget>(PackageId{"org.sw.demo.find.libpq", "master"});
            c->addPathDirectory(pq.LinkDirectories.begin()->parent_path() / "bin");
        });
    }*/
    s.addTest(test_patch);
    s.addTest(test_settings);
    s.addTest(test_version);
}
<commit_msg>Add embed command to target.<commit_after>#pragma sw require header org.sw.demo.ragel
#pragma sw require header org.sw.demo.lexxmark.winflexbison.bison-master

#pragma sw header on

static void gen_stamp(const DependencyPtr &tools_stamp_gen, NativeExecutedTarget &t)
{
    auto c = t.addCommand();
    c.c->always = true;
    c << cmd::prog(tools_stamp_gen)
        << cmd::std_out(t.BinaryPrivateDir / "stamp.h.in")
        ;
}

static void gen_sqlite2cpp(const DependencyPtr &tools_sqlite2cpp, NativeExecutedTarget &t, const path &sql_file, const path &out_file, const String &ns)
{
    auto c = t.addCommand();
    c << cmd::prog(tools_sqlite2cpp)
        << cmd::in(sql_file)
        << cmd::out(out_file)
        << ns;
}

static void embed(const DependencyPtr &embedder, NativeExecutedTarget &t, const path &in)
{
    struct EmbedCommand : ::sw::driver::Command
    {
        using Command::Command;

        std::shared_ptr<Command> clone() const override
        {
            return std::make_shared<EmbedCommand>(*this);
        }

    private:
        void postProcess1(bool ok) override
        {
            for (auto &line : split_lines(out.text))
            {
                static const auto prefix = "embedding: "s;
                boost::trim(line);
                for (auto &f : outputs)
                    File(f, *fs).addImplicitDependency(line.substr(prefix.size()));
            }
        }
    };

    if (in.is_absolute())
        throw SW_RUNTIME_ERROR("embed: in must be relative to SourceDir");

    auto f = t.SourceDir / in;
    auto out = t.BinaryDir / in.parent_path() / in.filename().stem();

    auto c = t.addCommand();
    c.c = std::make_shared<EmbedCommand>(c.c->swctx);
    SW_INTERNAL_INIT_COMMAND(c.c, t);
    SW_INTERNAL_ADD_COMMAND(c.c, t);
    c << cmd::prog(embedder)
        << cmd::wdir(f.parent_path())
        << cmd::in(in)
        << cmd::out(out)
        ;
    t += IncludeDirectory(out.parent_path()); // but remove this later
}

static Files syncqt(const DependencyPtr &sqt, NativeExecutedTarget &t, const Strings &modules)
{
    Files out;
    auto i = t.BinaryDir / "include";
    auto v = t.getPackage().version.toString();
    for (auto &m : modules)
    {
        fs::create_directories(i / m / v / m);

        auto c = t.addCommand();
        c << cmd::prog(sqt)
            << "-s" << t.SourceDir
            << "-b" << t.BinaryDir
            << "-m" << m
            << "-v" << v
            << cmd::end()
            << cmd::out(i / m / m)
            ;
        c.c->strict_order = 1; // run before moc
        out.insert(i / m / m);
        //t.Interface += i / m / m; makes cyclic deps

        t.Public += IncludeDirectory(i);
        t.Public += IncludeDirectory(i / m);
        t.Public += IncludeDirectory(i / m / v);
        t.Public += IncludeDirectory(i / m / v / m);
    }
    return out;
}

#pragma sw header off

void configure(Build &s)
{
    if (s.isConfigSelected("cyg2mac"))
        s.loadModule("utils/cc/cygwin2macos.cpp").call<void(Solution&)>("configure", s);
}

void build(Solution &s)
{
    auto &p = s.addProject("primitives", "master");
    p += "https://github.com/egorpugin/primitives"_git;

    auto setup_primitives_no_all_sources = [](auto &t)
    {
        path p = "src";
        auto n = t.getPackage().ppath.slice(t.getPackage().ppath.isAbsolute() ? 3 : 1);
        auto n2 = n;
        while (!n.empty())
        {
            p /= n.front();
            n = n.slice(1);
        }
        t.ApiName = "PRIMITIVES_" + boost::to_upper_copy(n2.toString("_")) + "_API";
        t.CPPVersion = CPPLanguageStandard::CPP17;
        t.PackageDefinitions = true;
        // not all code works with this yet (e.g. hh.date)
        //t.Public.CompileOptions.push_back("-Zc:__cplusplus");
        return p;
    };

    auto setup_primitives = [&setup_primitives_no_all_sources](auto &t)
    {
        auto p = setup_primitives_no_all_sources(t);
        t.setRootDirectory(p);
        // explicit!
        t += "include/.*"_rr;
        t += "src/.*"_rr;
    };

#define ADD_LIBRARY_WITH_NAME(var, name)          \
    auto &var = p.addTarget<LibraryTarget>(name); \
    setup_primitives(var)

#define ADD_LIBRARY(x) ADD_LIBRARY_WITH_NAME(x, #x)

    ADD_LIBRARY(error_handling);

    auto &templates = p.addTarget<StaticLibraryTarget>("templates");
    setup_primitives(templates);
    templates -= "org.sw.demo.boost.stacktrace-1"_dep;
    if (templates.getSettings().Native.ConfigurationType != ConfigurationType::Release &&
        templates.getSettings().Native.ConfigurationType != ConfigurationType::MinimalSizeRelease
        )
    {
        templates += "USE_STACKTRACE"_def;
        templates += "org.sw.demo.boost.stacktrace-1"_dep;
        //if (s.getSettings().TargetOS.Type == OSType::Windows)
            //templates += "dbgeng.lib"_slib;
    }

    ADD_LIBRARY(string);
    string.Public += "org.sw.demo.boost.algorithm-1"_dep;

    ADD_LIBRARY(filesystem);
    filesystem.Public += string, templates,
        "org.sw.demo.boost.filesystem-1"_dep,
        "org.sw.demo.boost.thread-1"_dep,
        "org.sw.demo.grisumbras.enum_flags-master"_dep;

    ADD_LIBRARY(file_monitor);
    file_monitor.Public += filesystem,
        "pub.egorpugin.libuv"_dep;

    ADD_LIBRARY(emitter);
    emitter.Public += filesystem;

    ADD_LIBRARY(executor);
    executor.Public += templates,
        "org.sw.demo.boost.asio-1"_dep,
        "org.sw.demo.boost.system-1"_dep;

    ADD_LIBRARY(command);
    command.Public += file_monitor,
        "org.sw.demo.boost.process-1"_dep;
    if (command.getSettings().TargetOS.Type == OSType::Windows)
        command.Public += "Shell32.lib"_slib;

    ADD_LIBRARY(date_time);
    date_time.Public += string,
        "org.sw.demo.boost.date_time-1"_dep;

    ADD_LIBRARY(lock);
    lock.Public += filesystem,
        "org.sw.demo.boost.interprocess-1"_dep;

    ADD_LIBRARY(log);
    log.Public += "org.sw.demo.boost.log-1"_dep;

    ADD_LIBRARY(cron);
    cron.Public += executor, log;

    ADD_LIBRARY(yaml);
    yaml.Public += string, templates,
        "org.sw.demo.jbeder.yaml_cpp-master"_dep;

    ADD_LIBRARY(pack);
    pack.Public += filesystem, templates,
        "org.sw.demo.libarchive.libarchive-3"_dep;

    ADD_LIBRARY(patch);
    patch.Public += filesystem, templates;

    ADD_LIBRARY(http);
    http.Public += filesystem, templates,
        "org.sw.demo.badger.curl.libcurl-7"_dep;
    if (http.getSettings().TargetOS.Type == OSType::Windows)
        http.Public += "Winhttp.lib"_slib;

    ADD_LIBRARY(hash);
    hash.Public += filesystem,
        "org.sw.demo.aleksey14.rhash-1"_dep,
        "org.sw.demo.openssl.crypto-1.*.*.*"_dep;

    ADD_LIBRARY(win32helpers);
    win32helpers.Public += "BOOST_DLL_USE_STD_FS"_def;
    win32helpers.Public += filesystem,
        "org.sw.demo.boost.dll-1"_dep,
        "org.sw.demo.boost.algorithm-1"_dep;
    if (win32helpers.getSettings().TargetOS.Type == OSType::Windows)
    {
        win32helpers.Public += "UNICODE"_d;
        win32helpers += "Shell32.lib"_slib, "Ole32.lib"_slib, "Advapi32.lib"_slib, "user32.lib"_slib;
    }

    ADD_LIBRARY_WITH_NAME(db_common, "db.common");
    db_common.Public += filesystem, templates,
        "org.sw.demo.imageworks.pystring-1"_dep;

    ADD_LIBRARY_WITH_NAME(db_sqlite3, "db.sqlite3");
    db_sqlite3.Public += db_common, "org.sw.demo.sqlite3"_dep;

    ADD_LIBRARY_WITH_NAME(db_postgresql, "db.postgresql");
    db_postgresql.Public += db_common, "org.sw.demo.jtv.pqxx-*"_dep;

    auto &main = p.addTarget<StaticLibraryTarget>("main");
    setup_primitives(main);
    main.Public += error_handling;

    ADD_LIBRARY(settings);
    settings.Public += "include"_idir;
    settings.Public += yaml, filesystem, templates,
        "pub.egorpugin.llvm_project.llvm.support_lite-master"_dep;
    gen_flex_bison_pair("org.sw.demo.lexxmark.winflexbison-master"_dep, settings, "LALR1_CPP_VARIANT_PARSER", "src/settings");
    gen_flex_bison_pair("org.sw.demo.lexxmark.winflexbison-master"_dep, settings, "LALR1_CPP_VARIANT_PARSER", "src/path");

    ADD_LIBRARY(symbol);
    symbol.Public += "BOOST_DLL_USE_STD_FS"_def;
    symbol.Public += filesystem, "org.sw.demo.boost.dll-1"_dep;

    ADD_LIBRARY_WITH_NAME(sw_settings, "sw.settings");
    sw_settings.Public += settings;
    sw_settings -= "src/sw.settings.program_name.cpp";
    //sw_settings.Interface += "src/sw.settings.program_name.cpp";

    ADD_LIBRARY(version);
    version.Public += "include"_idir;
    //version.Public += "src/version.natvis";
    version += "src/version.natvis";
    version.Public += string, templates,
        "org.sw.demo.fmt-*"_dep,
        "org.sw.demo.boost.container_hash-1"_dep,
        "org.sw.demo.imageworks.pystring-1"_dep;
    gen_ragel("org.sw.demo.ragel-6"_dep, version, "src/version.rl");
    gen_flex_bison_pair("org.sw.demo.lexxmark.winflexbison-master"_dep, version, "GLR_CPP_PARSER", "src/range");

    ADD_LIBRARY(source);
    source.Public += command, hash, http, pack, version, yaml,
        "org.sw.demo.nlohmann.json"_dep;

    //ADD_LIBRARY(object_path);
    //object_path.Public += string, templates;

    auto &sw_main = p.addTarget<StaticLibraryTarget>("sw.main");
    setup_primitives(sw_main);
    sw_main.Public += "BOOST_DLL_USE_STD_FS"_def;
    sw_main.Public += main, sw_settings,
        "org.sw.demo.boost.dll-1"_dep;
    sw_main.Interface.LinkLibraries.push_back(main.getImportLibrary()); // main itself
    sw_main.Interface.LinkLibraries.push_back(sw_main.getImportLibrary()); // then me (self, sw.main)
    sw_main.Interface.LinkLibraries.push_back(sw_settings.getImportLibrary()); // then sw.settings
    if (sw_main.getSettings().TargetOS.Type == OSType::Windows)
    {
        sw_main.Public +=
            "org.sw.demo.google.breakpad.client.windows.handler-master"_dep,
            "org.sw.demo.google.breakpad.client.windows.crash_generation.client-master"_dep,
            "org.sw.demo.google.breakpad.client.windows.crash_generation.server-master"_dep
            ;
    }

    auto &tools_embedder = p.addTarget<ExecutableTarget>("tools.embedder");
    setup_primitives_no_all_sources(tools_embedder);
    tools_embedder += "src/tools/embedder.cpp";
    tools_embedder += filesystem, sw_main;

    auto &tools_sqlite2cpp = p.addTarget<ExecutableTarget>("tools.sqlpp11.sqlite2cpp");
    setup_primitives_no_all_sources(tools_sqlite2cpp);
    tools_sqlite2cpp += "src/tools/sqlpp11.sqlite2cpp.cpp";
    tools_sqlite2cpp += filesystem, emitter, sw_main, "org.sw.demo.sqlite3"_dep;

    auto &tools_syncqt = p.addTarget<ExecutableTarget>("tools.syncqt");
    setup_primitives_no_all_sources(tools_syncqt);
    tools_syncqt += "src/tools/syncqt.cpp";
    tools_syncqt += filesystem, sw_main;

    auto &stamp_gen = p.addTarget<ExecutableTarget>("tools.stamp_gen");
    setup_primitives_no_all_sources(stamp_gen);
    stamp_gen += "src/tools/stamp_gen.cpp";

    return;

    auto &test = p.addDirectory("test");
    test.Scope = TargetScope::Test;

    auto add_test = [&test, &s, &sw_main](const String &name) -> decltype(auto)
    {
        auto &t = test.addTarget<ExecutableTarget>(name);
        t.CPPVersion = CPPLanguageStandard::CPP17;
        t += path("src/" + name + ".cpp");
        t += "org.sw.demo.catchorg.catch2-*"_dep;
        if (t.getCompilerType() == CompilerType::MSVC)
            t.CompileOptions.push_back("-bigobj");
        //else if (t.getCompilerType() == CompilerType::GNU)
            //t.CompileOptions.push_back("-Wa,-mbig-obj");
        t += sw_main;
        return t;
    };

    auto &test_main = add_test("main");
    test_main += command, date_time,
        executor, hash, yaml, emitter, http,
        "org.sw.demo.nlohmann.json-*"_dep;

    auto &test_db = add_test("db");
    test_db += command, db_sqlite3, db_postgresql, date_time,
        executor, hash, yaml;

    auto &test_settings = add_test("settings");
    test_settings.PackageDefinitions = true;
    test_settings += settings;

    auto &test_version = add_test("version");
    test_version += version;

    auto &test_source = add_test("source");
    test_source += source;

    auto &test_patch = add_test("patch");
    test_patch += patch;

    auto tm = s.addTest(test_main);
    tm.c->addPathDirectory(getenv("PATH"));
    /*auto tdb = s.addTest(test_db);
    if (test_db.getSettings().TargetOS.Type == OSType::Windows)
    {
        tdb.c->addLazyAction([&s, c = tdb.c]
        {
            auto &pq = s.getTarget<LibraryTarget>(PackageId{"org.sw.demo.find.libpq", "master"});
            c->addPathDirectory(pq.LinkDirectories.begin()->parent_path() / "bin");
        });
    }*/
    s.addTest(test_patch);
    s.addTest(test_settings);
    s.addTest(test_version);
}
<|endoftext|>


<commit_before>#include "stdafx.h"

#include "Render/DX12/Texture/TextureManagerDX12.h"

#include "Render/DX12/StateDX.h"
#include "Render/DX12/Texture/TextureDX12.h"
#include "Render/Texture/Texture.h"
#include "Render/Texture/TextureSet.h"

namespace Kioto::Renderer
{
namespace
{
constexpr uint16 MaxRenderTargetViews = 256;
}

TextureManagerDX12::TextureManagerDX12()
{
    m_textureQueue.reserve(64);
    m_textureSetUpdateQueue.reserve(256);
}

void TextureManagerDX12::RegisterTexture(Texture* texture)
{
    auto it = m_textures.find(texture->GetHandle());
    if (it != m_textures.end())
    {
        throw "Texture Already Registered";
        return;
    }

    TextureDX12* tex = new TextureDX12();
    tex->Path = StrToWstr(texture->GetAssetPath());
    tex->SetHandle(GetNewHandle());
    tex->SetDescriptor(texture->GetDescriptor());
    tex->SetIsFromMemoryAsset(texture->IsMemoryAsset());
    m_textureQueue.push_back(tex);
    texture->SetHandle(tex->GetHandle());

    m_textures[tex->GetHandle()] = tex;
}

TextureManagerDX12::~TextureManagerDX12()
{
    for (auto& tex : m_textures)
        delete tex.second;
    m_textures.clear();
}

void TextureManagerDX12::InitRtvHeap(const StateDX& state)
{
    D3D12_DESCRIPTOR_HEAP_DESC heapDescr = {};
    heapDescr.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;
    heapDescr.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
    heapDescr.NumDescriptors = MaxRenderTargetViews;
    ThrowIfFailed(state.Device->CreateDescriptorHeap(&heapDescr, IID_PPV_ARGS(&m_rtvHeap)));
}

void TextureManagerDX12::UpdateTextureSetHeap(const StateDX& state, const TextureSet& texSet)
{
    if (m_textureHeaps.find(texSet.GetHandle()) != m_textureHeaps.end())
        m_textureHeaps[texSet.GetHandle()].Reset();

    D3D12_DESCRIPTOR_HEAP_DESC heapDescr = {};
    heapDescr.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
    heapDescr.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
    heapDescr.NumDescriptors = texSet.GetTexturesCount();
    ThrowIfFailed(state.Device->CreateDescriptorHeap(&heapDescr, IID_PPV_ARGS(&m_textureHeaps[texSet.GetHandle()])));

    CD3DX12_CPU_DESCRIPTOR_HANDLE handle(m_textureHeaps[texSet.GetHandle()]->GetCPUDescriptorHandleForHeapStart());
    for (uint32 i = 0; i < texSet.GetTexturesCount(); ++i)
    {
        const Texture* kiotoTex = texSet.GetTexture(i);
        auto it = m_textures.find(kiotoTex->GetHandle());
        if (it == m_textures.end())
            throw "ololo";
        TextureDX12* dxTex = (*it).second;

        D3D12_SHADER_RESOURCE_VIEW_DESC texDescr = {};
        texDescr.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
        texDescr.Format = dxTex->Resource->GetDesc().Format;
        texDescr.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
        texDescr.Texture2D.MipLevels = dxTex->Resource->GetDesc().MipLevels;
        texDescr.Texture2D.MostDetailedMip = 0;
        texDescr.Texture2D.ResourceMinLODClamp = 0.0f;

        state.Device->CreateShaderResourceView(dxTex->Resource.Get(), &texDescr, handle);
        handle.Offset(state.CbvSrvUavDescriptorSize);
    }
}

ID3D12DescriptorHeap* TextureManagerDX12::GetTextureHeap(TextureSetHandle handle) const
{
    auto it = m_textureHeaps.find(handle);
    if (it != m_textureHeaps.cend())
        return it->second.Get();
    return nullptr;
}

TextureDX12* TextureManagerDX12::FindTexture(TextureHandle handle)
{
    auto it = m_textures.find(handle);
    if (it != m_textures.cend())
        return it->second;
    it = m_notOwningTextures.find(handle);
    if (it != m_notOwningTextures.cend())
        return it->second;
    return nullptr;
}

void TextureManagerDX12::RegisterTextureWithoutOwnership(TextureDX12* texture)
{
    auto it = m_notOwningTextures.find(texture->GetHandle());
    if (it != m_notOwningTextures.end())
    {
        throw "Texture Already Registered";
        return;
    }
    m_notOwningTextures[texture->GetHandle()] = texture;
}

void TextureManagerDX12::ProcessRegistationQueue(const StateDX& state)
{
    for (auto& tex : m_textureQueue)
    {
        tex->Create(state.Device.Get(), state.CommandList.Get());
        if (tex->GetIsFromMemoryAsset() && ((tex->GetDx12TextureFlags() & D3D12_RESOURCE_FLAGS::D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) != 0))
        {
            assert(m_rtvHeapOffsets.count(tex->GetHandle()) == 0);
            m_rtvHeapOffsets[tex->GetHandle()] = m_currentRtvOffset;

            CD3DX12_CPU_DESCRIPTOR_HANDLE handle(m_rtvHeap->GetCPUDescriptorHandleForHeapStart());
            handle.Offset(m_currentRtvOffset);

            m_currentRtvOffset += state.RtvDescriptorSize;

            D3D12_SHADER_RESOURCE_VIEW_DESC texDescr = {};
            texDescr.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
            texDescr.Format = tex->Resource->GetDesc().Format;
            texDescr.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
            texDescr.Texture2D.MipLevels = tex->Resource->GetDesc().MipLevels;
            texDescr.Texture2D.MostDetailedMip = 0;
            texDescr.Texture2D.ResourceMinLODClamp = 0.0f;

            state.Device->CreateShaderResourceView(tex->Resource.Get(), &texDescr, handle);
        }
    }
    m_textureQueue.clear();
}

void TextureManagerDX12::QueueTextureSetForUpdate(const TextureSet& texSet)
{
    if (texSet.GetHandle() == InvalidHandle)
        throw "Invalid handle";

    auto it = std::find(m_textureSetUpdateQueue.cbegin(), m_textureSetUpdateQueue.cend(), &texSet);
    if (it != m_textureSetUpdateQueue.cend())
        return;

    m_textureSetUpdateQueue.push_back(&texSet);
}

void TextureManagerDX12::ProcessTextureSetUpdates(const StateDX& state)
{
    for (auto& texSet : m_textureSetUpdateQueue)
        UpdateTextureSetHeap(state, *texSet);
    m_textureSetUpdateQueue.clear();
}

D3D12_CPU_DESCRIPTOR_HANDLE TextureManagerDX12::GetRtvHandle(TextureHandle handle) const
{
    assert(m_rtvHeapOffsets.count(handle) == 1 && "The texture is not registered as a rtv");
    CD3DX12_CPU_DESCRIPTOR_HANDLE rtvHandle(m_rtvHeap->GetCPUDescriptorHandleForHeapStart());
    rtvHandle.Offset(m_rtvHeapOffsets.at(handle));
    return rtvHandle;
}

}<commit_msg>Fix wrong rt creation<commit_after>#include "stdafx.h"

#include "Render/DX12/Texture/TextureManagerDX12.h"

#include "Render/DX12/StateDX.h"
#include "Render/DX12/Texture/TextureDX12.h"
#include "Render/Texture/Texture.h"
#include "Render/Texture/TextureSet.h"

namespace Kioto::Renderer
{
namespace
{
constexpr uint16 MaxRenderTargetViews = 256;
}

TextureManagerDX12::TextureManagerDX12()
{
    m_textureQueue.reserve(64);
    m_textureSetUpdateQueue.reserve(256);
}

void TextureManagerDX12::RegisterTexture(Texture* texture)
{
    auto it = m_textures.find(texture->GetHandle());
    if (it != m_textures.end())
    {
        throw "Texture Already Registered";
        return;
    }

    TextureDX12* tex = new TextureDX12();
    tex->Path = StrToWstr(texture->GetAssetPath());
    tex->SetHandle(GetNewHandle());
    tex->SetDescriptor(texture->GetDescriptor());
    tex->SetIsFromMemoryAsset(texture->IsMemoryAsset());
    m_textureQueue.push_back(tex);
    texture->SetHandle(tex->GetHandle());

    m_textures[tex->GetHandle()] = tex;
}

TextureManagerDX12::~TextureManagerDX12()
{
    for (auto& tex : m_textures)
        delete tex.second;
    m_textures.clear();
}

void TextureManagerDX12::InitRtvHeap(const StateDX& state)
{
    D3D12_DESCRIPTOR_HEAP_DESC heapDescr = {};
    heapDescr.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;
    heapDescr.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
    heapDescr.NumDescriptors = MaxRenderTargetViews;
    ThrowIfFailed(state.Device->CreateDescriptorHeap(&heapDescr, IID_PPV_ARGS(&m_rtvHeap)));
}

void TextureManagerDX12::UpdateTextureSetHeap(const StateDX& state, const TextureSet& texSet)
{
    if (m_textureHeaps.find(texSet.GetHandle()) != m_textureHeaps.end())
        m_textureHeaps[texSet.GetHandle()].Reset();

    D3D12_DESCRIPTOR_HEAP_DESC heapDescr = {};
    heapDescr.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
    heapDescr.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
    heapDescr.NumDescriptors = texSet.GetTexturesCount();
    ThrowIfFailed(state.Device->CreateDescriptorHeap(&heapDescr, IID_PPV_ARGS(&m_textureHeaps[texSet.GetHandle()])));

    CD3DX12_CPU_DESCRIPTOR_HANDLE handle(m_textureHeaps[texSet.GetHandle()]->GetCPUDescriptorHandleForHeapStart());
    for (uint32 i = 0; i < texSet.GetTexturesCount(); ++i)
    {
        const Texture* kiotoTex = texSet.GetTexture(i);
        auto it = m_textures.find(kiotoTex->GetHandle());
        if (it == m_textures.end())
            throw "ololo";
        TextureDX12* dxTex = (*it).second;

        D3D12_SHADER_RESOURCE_VIEW_DESC texDescr = {};
        texDescr.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
        texDescr.Format = dxTex->Resource->GetDesc().Format;
        texDescr.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
        texDescr.Texture2D.MipLevels = dxTex->Resource->GetDesc().MipLevels;
        texDescr.Texture2D.MostDetailedMip = 0;
        texDescr.Texture2D.ResourceMinLODClamp = 0.0f;

        state.Device->CreateShaderResourceView(dxTex->Resource.Get(), &texDescr, handle);
        handle.Offset(state.CbvSrvUavDescriptorSize);
    }
}

ID3D12DescriptorHeap* TextureManagerDX12::GetTextureHeap(TextureSetHandle handle) const
{
    auto it = m_textureHeaps.find(handle);
    if (it != m_textureHeaps.cend())
        return it->second.Get();
    return nullptr;
}

TextureDX12* TextureManagerDX12::FindTexture(TextureHandle handle)
{
    auto it = m_textures.find(handle);
    if (it != m_textures.cend())
        return it->second;
    it = m_notOwningTextures.find(handle);
    if (it != m_notOwningTextures.cend())
        return it->second;
    return nullptr;
}

void TextureManagerDX12::RegisterTextureWithoutOwnership(TextureDX12* texture)
{
    auto it = m_notOwningTextures.find(texture->GetHandle());
    if (it != m_notOwningTextures.end())
    {
        throw "Texture Already Registered";
        return;
    }
    m_notOwningTextures[texture->GetHandle()] = texture;
}

void TextureManagerDX12::ProcessRegistationQueue(const StateDX& state)
{
    for (auto& tex : m_textureQueue)
    {
        tex->Create(state.Device.Get(), state.CommandList.Get());
        if (tex->GetIsFromMemoryAsset() && ((tex->GetDx12TextureFlags() & D3D12_RESOURCE_FLAGS::D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) != 0))
        {
            assert(m_rtvHeapOffsets.count(tex->GetHandle()) == 0);
            m_rtvHeapOffsets[tex->GetHandle()] = m_currentRtvOffset;

            CD3DX12_CPU_DESCRIPTOR_HANDLE handle(m_rtvHeap->GetCPUDescriptorHandleForHeapStart());
            handle.Offset(m_currentRtvOffset);

            m_currentRtvOffset += state.RtvDescriptorSize;

            D3D12_RENDER_TARGET_VIEW_DESC texDescr = {};
            texDescr.Format = tex->Resource->GetDesc().Format;
            texDescr.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D;
            texDescr.Texture2D = { 0, 0};

            state.Device->CreateRenderTargetView(tex->Resource.Get(), &texDescr, handle);
        }
    }
    m_textureQueue.clear();
}

void TextureManagerDX12::QueueTextureSetForUpdate(const TextureSet& texSet)
{
    if (texSet.GetHandle() == InvalidHandle)
        throw "Invalid handle";

    auto it = std::find(m_textureSetUpdateQueue.cbegin(), m_textureSetUpdateQueue.cend(), &texSet);
    if (it != m_textureSetUpdateQueue.cend())
        return;

    m_textureSetUpdateQueue.push_back(&texSet);
}

void TextureManagerDX12::ProcessTextureSetUpdates(const StateDX& state)
{
    for (auto& texSet : m_textureSetUpdateQueue)
        UpdateTextureSetHeap(state, *texSet);
    m_textureSetUpdateQueue.clear();
}

D3D12_CPU_DESCRIPTOR_HANDLE TextureManagerDX12::GetRtvHandle(TextureHandle handle) const
{
    assert(m_rtvHeapOffsets.count(handle) == 1 && "The texture is not registered as a rtv");
    CD3DX12_CPU_DESCRIPTOR_HANDLE rtvHandle(m_rtvHeap->GetCPUDescriptorHandleForHeapStart());
    rtvHandle.Offset(m_rtvHeapOffsets.at(handle));
    return rtvHandle;
}

}<|endoftext|>


<commit_before>#include "encryptionconfigurationdialogimpl.h"
#include "cryptplugwrapper.h"

#include <qbuttongroup.h>
#include <qradiobutton.h>
#include <qcheckbox.h>
#include <qspinbox.h>

#define FULLTEST false

/*
 *  Constructs a EncryptionConfigurationDialogImpl which is a child of 'parent', with the
 *  name 'name' and widget flags set to 'f'
 */
EncryptionConfigurationDialogImpl::EncryptionConfigurationDialogImpl( QWidget* parent,  const char* name, WFlags fl )
    : EncryptionConfigurationDialog( parent, name, fl )
{
}

/*
 *  Destroys the object and frees any allocated resources
 */
EncryptionConfigurationDialogImpl::~EncryptionConfigurationDialogImpl()
{
    // no need to delete child widgets, Qt does it all for us
}

/**
   Enables or disables the widgets in this dialog according to the
   capabilities of the current plugin passed as a parameter.
*/
void EncryptionConfigurationDialogImpl::enableDisable( CryptPlugWrapper* cryptPlug )
{
    // disable the whole page if the plugin does not support encryption
    setEnabled( cryptPlug->hasFeature( Feature_EncryptMessages ) );

    // enable/disable individual components depending on the plugin features
    crlBG->setEnabled( cryptPlug->hasFeature( Feature_EncryptionCRLs ) );
    warnReceiverCertificateExpiresCB->setEnabled( cryptPlug->hasFeature( Feature_WarnEncryptCertificateExpiry ) );
    warnReceiverCertificateExpiresSB->setEnabled( cryptPlug->hasFeature( Feature_WarnEncryptCertificateExpiry ) );
    warnChainCertificateExpiresCB->setEnabled( cryptPlug->hasFeature( Feature_WarnEncryptCertificateExpiry ) );
    warnChainCertificateExpiresSB->setEnabled( cryptPlug->hasFeature( Feature_WarnEncryptCertificateExpiry ) );
    warnReceiverNotInCertificateCB->setEnabled( cryptPlug->hasFeature( Feature_WarnEncryptEmailNotInCertificate ) );
    saveMessagesBG->setEnabled( cryptPlug->hasFeature( Feature_StoreMessagesEncrypted ) );
    certificatePathCheckBG->setEnabled( cryptPlug->hasFeature( Feature_CheckCertificatePath ) );

    if( ! FULLTEST ) {
        askEachPartRB                 ->hide(); // We won't implement that.

        encryptionSettingsBG          ->hide(); // Will implement that later.

        certificatePathCheckBG        ->hide(); // Will implement that later.

        crlBG                         ->hide(); // Will implement that later.

        warnCRLExpireCB               ->hide(); // Will implement that later.
        warnCRLExpireSB               ->hide(); // Will implement that later.

        warnReceiverCertificateExpiresCB->hide();//Will implement that later.
        warnReceiverCertificateExpiresSB->hide();//Will implement that later.

        warnChainCertificateExpiresCB ->hide(); // Will implement that later.
        warnChainCertificateExpiresSB ->hide(); // Will implement that later.
        warnReceiverNotInCertificateCB->hide(); // Will implement that later.

        alwaysCheckRootRB             ->hide(); // Will implement that later.

        /*enable:*/
        pathMayEndLocallyCB           ->setEnabled( true );

    }
}

#include "encryptionconfigurationdialogimpl.moc"
<commit_msg>Bugfix: enable function receiverCertificateDaysLeftToExpiry().<commit_after>#include "encryptionconfigurationdialogimpl.h"
#include "cryptplugwrapper.h"

#include <qbuttongroup.h>
#include <qradiobutton.h>
#include <qcheckbox.h>
#include <qspinbox.h>

#define FULLTEST false

/*
 *  Constructs a EncryptionConfigurationDialogImpl which is a child of 'parent', with the
 *  name 'name' and widget flags set to 'f'
 */
EncryptionConfigurationDialogImpl::EncryptionConfigurationDialogImpl( QWidget* parent,  const char* name, WFlags fl )
    : EncryptionConfigurationDialog( parent, name, fl )
{
}

/*
 *  Destroys the object and frees any allocated resources
 */
EncryptionConfigurationDialogImpl::~EncryptionConfigurationDialogImpl()
{
    // no need to delete child widgets, Qt does it all for us
}

/**
   Enables or disables the widgets in this dialog according to the
   capabilities of the current plugin passed as a parameter.
*/
void EncryptionConfigurationDialogImpl::enableDisable( CryptPlugWrapper* cryptPlug )
{
    // disable the whole page if the plugin does not support encryption
    setEnabled( cryptPlug->hasFeature( Feature_EncryptMessages ) );

    // enable/disable individual components depending on the plugin features
    crlBG->setEnabled( cryptPlug->hasFeature( Feature_EncryptionCRLs ) );
    warnReceiverCertificateExpiresCB->setEnabled( cryptPlug->hasFeature( Feature_WarnEncryptCertificateExpiry ) );
    warnReceiverCertificateExpiresSB->setEnabled( cryptPlug->hasFeature( Feature_WarnEncryptCertificateExpiry ) );
    warnChainCertificateExpiresCB->setEnabled( cryptPlug->hasFeature( Feature_WarnEncryptCertificateExpiry ) );
    warnChainCertificateExpiresSB->setEnabled( cryptPlug->hasFeature( Feature_WarnEncryptCertificateExpiry ) );
    warnReceiverNotInCertificateCB->setEnabled( cryptPlug->hasFeature( Feature_WarnEncryptEmailNotInCertificate ) );
    saveMessagesBG->setEnabled( cryptPlug->hasFeature( Feature_StoreMessagesEncrypted ) );
    certificatePathCheckBG->setEnabled( cryptPlug->hasFeature( Feature_CheckCertificatePath ) );

    if( ! FULLTEST ) {
        askEachPartRB                 ->hide(); // We won't implement that.

//        encryptionSettingsBG          ->hide(); // Will implement that later.

        certificatePathCheckBG        ->hide(); // Will implement that later.

        crlBG                         ->hide(); // Will implement that later.

        warnCRLExpireCB               ->hide(); // Will implement that later.
        warnCRLExpireSB               ->hide(); // Will implement that later.

//        warnReceiverCertificateExpiresCB->hide();//Will implement that later.
//        warnReceiverCertificateExpiresSB->hide();//Will implement that later.

        warnChainCertificateExpiresCB ->hide(); // Will implement that later.
        warnChainCertificateExpiresSB ->hide(); // Will implement that later.
        warnReceiverNotInCertificateCB->hide(); // Will implement that later.

        alwaysCheckRootRB             ->hide(); // Will implement that later.

        /*enable:*/
        pathMayEndLocallyCB           ->setEnabled( true );

    }
}

#include "encryptionconfigurationdialogimpl.moc"
<|endoftext|>


<commit_before>/* -*-Mode: c++;-*-
   Copyright (c) 2003-2008 John Plevyak, All Rights Reserved
*/
#include "ifadefs.h"
#include "ast.h"
#include "if1.h"
#include "fa.h"
#include "builtin.h"

cchar *type_kind_string[] = {
  "NONE", "UNKNOWN", "SUM", "RECORD", "VECTOR", "FUN", "REF", "ENUM", "PRIMITIVE", "APPLICATION", "VARIABLE", "ALIAS"};

BasicSym::BasicSym(void) :
  name(NULL),
  in(NULL),
  type(NULL),
  aspect(NULL),
  must_specialize(NULL),
  must_implement(NULL),
  ast(NULL),
  var(NULL),
  asymbol(NULL),
  nesting_depth(0),
  cg_string(NULL),
  llvm_value(NULL),
  is_builtin(0),
  is_read_only(0),
  is_constant(0),
  is_lvalue(0),
  is_local(0),
  is_default_arg(0),
  is_exact_match(0),
  is_module(0),
  is_fun(0),
  is_symbol(0),
  is_pattern(0),
  is_rest(0),
  is_generic(0),
  is_external(0),
  is_this(0),
  is_fake(0),
  intent(0),
  is_meta_type(0),
  is_unique_type(0),
  is_value_type(0),
  is_system_type(0),
  is_union_type(0),
  is_structure(0),
  fun_returns_value(0),
  live(0),
  type_kind(0),
  num_kind(0),
  num_index(0),
  clone_for_constants(0),
  dispatch_types_built(0),
  type_live(0)
{}

Sym::Sym() :
  constant(NULL),
  size(0),
  alignment(0),
  scope(NULL),
  labelmap(NULL),
  fun(NULL),
  code(NULL),
  self(NULL),
  ret(NULL),
  cont(NULL),
  instantiates(NULL),
  match_type(NULL),
  abstract_type(NULL),
  alias(NULL),
  init(NULL),
  meta_type(NULL),
#ifdef CONSTANT_TYPES
  constant_type(NULL),
#endif
  element(NULL),
  temp(NULL),
  llvm_type(NULL)
{}

cchar *
Sym::pathname() {
  cchar *p = 0;
  if (asymbol)
    p = asymbol->pathname();
  if (!p && ast)
    p = ast->pathname();
  if (p)
    return p;
  return "<unknown>";
}

cchar *
Sym::has_name(int i) {
  if (i < has_names.n)
    return has_names[i];
  return 0;
}

cchar *
Sym::filename() {
  cchar *fn = pathname();
  cchar *r = strrchr(fn, '/');
  if (r) return r+1; else return fn;
}

int
Sym::line() {
  int l = 0;
  if (asymbol)
    l = asymbol->line();
  if (!l && ast)
    l = ast->line();
  return l;
}

int
Sym::source_line() {
  int l = 0;
  if (asymbol)
    l = asymbol->source_line();
  if (!l && ast)
    l = ast->source_line();
  return l;
}

void
Sym::copy_values(Sym *s) {
  int temp_id = id;
  *this = *s;
  id = temp_id;
}

Sym *
Sym::clone() {
  if (asymbol)
    return asymbol->clone();
  Sym *new_sym = copy();
  return new_sym;
}

Sym *
Sym::copy() {
  Sym *s = new_Sym();
  s->copy_values(this);
  if (s->element)
    s->element = s->element->copy();
  return s;
}

int
compar_syms(const void *ai, const void *aj) {
  uint32 i = (*(Sym**)ai)->id;
  uint32 j = (*(Sym**)aj)->id;
  return (i > j) ? 1 : ((i < j) ? -1 : 0);
}

int
Sym::imm_int(int *result) {
  int i = 0;
  switch (type->num_kind) {
    default: return -1;
    case IF1_NUM_KIND_UINT: {
      switch (type->num_index) {
        case IF1_INT_TYPE_8:  i = imm.v_uint8; break;
        case IF1_INT_TYPE_16: i = imm.v_uint16; break;
        case IF1_INT_TYPE_32: i = imm.v_uint32; break;
        case IF1_INT_TYPE_64: i = imm.v_uint64; break;
        default: return -1;
      }
      break;
    }
    case IF1_NUM_KIND_INT: {
      switch (type->num_index) {
        case IF1_INT_TYPE_8:  i = imm.v_int8; break;
        case IF1_INT_TYPE_16: i = imm.v_int16; break;
        case IF1_INT_TYPE_32: i = imm.v_int32; break;
        case IF1_INT_TYPE_64: i = imm.v_int64; break;
        default: return -1;
      }
      break;
    }
  }
  *result = i;
  return 0;
}

Sym *
unalias_type(Sym *s) {
  if (!s)
    return s;
  if (s->type_kind == Type_ALIAS) {
    Vec<Sym *> aliases;
    do {
      if (!s->alias)
        return 0;
      Sym *ss = s->alias;
      if (aliases.set_in(ss))
        fail("circular type alias");
      aliases.set_add(ss);
      s = ss;
    } while (s->type_kind == Type_ALIAS);
  }
  return s;
}

void
if1_set_int_type(IF1 *p, Sym *t, int signd, int size) {
  int ss = 0;
  size >>= 3;
  while (size) { ss++; size >>= 1; }
  p->int_types[ss][signd] = t;
  t->num_kind = signd ? IF1_NUM_KIND_INT : IF1_NUM_KIND_UINT;
  t->num_index = ss;
}

void
if1_set_float_type(IF1 *p, Sym *t, int size) {
  int ss = 0;
  size >>= 4;
  ss = size - 1;
  p->float_types[ss] = t;
  t->num_kind = IF1_NUM_KIND_FLOAT;
  t->num_index = ss;
}

void
if1_set_complex_type(IF1 *p, Sym *t, int size) {
  int ss = 0;
  size >>= 4;
  ss = size - 1;
  p->complex_types[ss] = t;
  t->num_kind = IF1_NUM_KIND_COMPLEX;
  t->num_index = ss;
}

int
if1_numeric_size(IF1 *p, Sym *t) {
  switch (t->num_kind) {
    case IF1_NUM_KIND_NONE: assert(!"bad case"); break;
    case IF1_NUM_KIND_INT:
    case IF1_NUM_KIND_UINT:
      if (!t->num_index) return sizeof(bool);
      return 1 << ((t->num_index ? t->num_index : 1) - 1);
    case IF1_NUM_KIND_FLOAT:
      return 2 + (2 * t->num_index);
    case IF1_NUM_KIND_COMPLEX:
      return 2 * (2 + (2 * t->num_index));
  }
  return 0;
}

#define MAKE_ALIGNOF(_t) \
struct AlignOf##_t {      \
  char a;                \
  _t b;                  \
}

#define ALIGNOF(_t) ((int)(intptr_t)&(((struct AlignOf##_t *)0)->b))

MAKE_ALIGNOF(bool);
MAKE_ALIGNOF(uint8);
MAKE_ALIGNOF(uint16);
MAKE_ALIGNOF(uint32);
MAKE_ALIGNOF(uint64);
MAKE_ALIGNOF(float32);
MAKE_ALIGNOF(float64);
MAKE_ALIGNOF(float128);
MAKE_ALIGNOF(complex32);
MAKE_ALIGNOF(complex64);
typedef char *alignstring;
MAKE_ALIGNOF(alignstring);

int
if1_numeric_alignment(IF1 *p, Sym *t) {
  int res = -1;
  switch (t->num_kind) {
    default: assert(!"case"); break;
    case IF1_NUM_KIND_UINT:
    case IF1_NUM_KIND_INT:
      switch (t->num_index) {
        case IF1_INT_TYPE_1: return ALIGNOF(bool); break;
        case IF1_INT_TYPE_8: return ALIGNOF(uint8); break;
        case IF1_INT_TYPE_16: return ALIGNOF(uint16); break;
        case IF1_INT_TYPE_32: return ALIGNOF(uint32); break;
        case IF1_INT_TYPE_64: return ALIGNOF(uint64); break;
        default: assert(!"case");
      }
      break;
    case IF1_NUM_KIND_FLOAT:
      switch (t->num_index) {
        case IF1_FLOAT_TYPE_32:  return ALIGNOF(float32);
        case IF1_FLOAT_TYPE_64:  return ALIGNOF(float64);
        case IF1_FLOAT_TYPE_128: return ALIGNOF(float128);
        default: assert(!"case");
      }
      break;
    case IF1_NUM_KIND_COMPLEX:
      switch (t->num_index) {
        case IF1_FLOAT_TYPE_32: return ALIGNOF(complex32);
        case IF1_FLOAT_TYPE_64: return ALIGNOF(complex64);
        default: assert(!"case");
      }
      break;
    case IF1_CONST_KIND_STRING: return ALIGNOF(alignstring);
  }
  return res;
}

void
Sym::inherits_add(Sym *s) {
  implements.add(s);
  specializes.add(s);
  includes.add(s);
}

void
Sym::must_implement_and_specialize(Sym *s) {
  assert((!must_implement || must_implement == s) &&
         (!must_specialize || must_specialize == s));
  must_implement = s;
  must_specialize = s;
}

Sym *
Sym::scalar_type() {
  if (type && type->num_kind)
    return type;
  return 0;
}

Sym *
Sym::coerce_to(Sym *to) {
  if (this == to)
    return this;
  Sym *s1 = this->scalar_type(), *s2 = to->scalar_type();
  if (s1 && s2) {
    Sym *t = coerce_num(s1, s2);
    if (t == s2)
      return s2;
    return NULL;
  }
  if (element) {
    Sym *s1 = element->scalar_type(), *s2 = to->scalar_type();
    if (s1 && s2) {
      Sym *t = coerce_num(s1, s2);
      if (t == s2)
        return s2;
      return NULL;
    }
  }
  if (s1) {
    if (to == sym_string)
      return to;
  }
  return NULL;
}

void
Sym::convert_constant_string_to_immediate() {
  if (!is_constant)
    return;
  imm.const_kind = type->num_kind;
  imm.num_index = type->num_index;
  convert_string_to_immediate(constant, &imm);
}

static Sym *
int_constant_internal(IF1 *i, int n, Sym *t) {
  Immediate imm;
  imm.v_int32 = n;
  if (n >= 0 && n < 10) {
    char c[2];
    c[0] = n + '0';
    c[1] = 0;
    return if1_const(i, t, c, &imm);
  } else {
    char str[100];
    sprintf(str, "%d", n);
    return if1_const(i, t, str, &imm);
  }
}

Sym *
int32_constant(int n) {
  return int_constant_internal(if1, n, sym_int32);
}

Sym *
size_constant(int n) {
  return int_constant_internal(if1, n, sym_size);
}

Sym *
imm_constant(Immediate &imm, Sym *t) {
  char str[256];
  sprint_imm(str, imm);
  return if1_const(if1, t, str, &imm);
}

void
pp(Sym *s) {
  printf("(SYM %d ", s->id);
  if1_dump_sym(stdout, s);
  printf(")");
}
<commit_msg>Fix missing initialization.<commit_after>/* -*-Mode: c++;-*-
   Copyright (c) 2003-2008 John Plevyak, All Rights Reserved
*/
#include "ifadefs.h"
#include "ast.h"
#include "if1.h"
#include "fa.h"
#include "builtin.h"

cchar *type_kind_string[] = {
  "NONE", "UNKNOWN", "SUM", "RECORD", "VECTOR", "FUN", "REF", "ENUM", "PRIMITIVE", "APPLICATION", "VARIABLE", "ALIAS"};

BasicSym::BasicSym(void) :
  name(NULL),
  in(NULL),
  type(NULL),
  aspect(NULL),
  must_specialize(NULL),
  must_implement(NULL),
  ast(NULL),
  var(NULL),
  asymbol(NULL),
  nesting_depth(0),
  cg_string(NULL),
  llvm_value(NULL),
  is_builtin(0),
  is_read_only(0),
  is_constant(0),
  is_lvalue(0),
  is_local(0),
  is_default_arg(0),
  is_exact_match(0),
  is_module(0),
  is_fun(0),
  is_symbol(0),
  is_pattern(0),
  is_rest(0),
  is_generic(0),
  is_external(0),
  is_this(0),
  is_fake(0),
  intent(0),
  is_meta_type(0),
  is_unique_type(0),
  is_value_type(0),
  is_system_type(0),
  is_union_type(0),
  is_structure(0),
  is_vector(0),
  fun_returns_value(0),
  live(0),
  type_kind(0),
  num_kind(0),
  num_index(0),
  clone_for_constants(0),
  dispatch_types_built(0),
  type_live(0)
{}

Sym::Sym() :
  constant(NULL),
  size(0),
  alignment(0),
  scope(NULL),
  labelmap(NULL),
  fun(NULL),
  code(NULL),
  self(NULL),
  ret(NULL),
  cont(NULL),
  instantiates(NULL),
  match_type(NULL),
  abstract_type(NULL),
  alias(NULL),
  init(NULL),
  meta_type(NULL),
#ifdef CONSTANT_TYPES
  constant_type(NULL),
#endif
  element(NULL),
  temp(NULL),
  llvm_type(NULL)
{}

cchar *
Sym::pathname() {
  cchar *p = 0;
  if (asymbol)
    p = asymbol->pathname();
  if (!p && ast)
    p = ast->pathname();
  if (p)
    return p;
  return "<unknown>";
}

cchar *
Sym::has_name(int i) {
  if (i < has_names.n)
    return has_names[i];
  return 0;
}

cchar *
Sym::filename() {
  cchar *fn = pathname();
  cchar *r = strrchr(fn, '/');
  if (r) return r+1; else return fn;
}

int
Sym::line() {
  int l = 0;
  if (asymbol)
    l = asymbol->line();
  if (!l && ast)
    l = ast->line();
  return l;
}

int
Sym::source_line() {
  int l = 0;
  if (asymbol)
    l = asymbol->source_line();
  if (!l && ast)
    l = ast->source_line();
  return l;
}

void
Sym::copy_values(Sym *s) {
  int temp_id = id;
  *this = *s;
  id = temp_id;
}

Sym *
Sym::clone() {
  if (asymbol)
    return asymbol->clone();
  Sym *new_sym = copy();
  return new_sym;
}

Sym *
Sym::copy() {
  Sym *s = new_Sym();
  s->copy_values(this);
  if (s->element)
    s->element = s->element->copy();
  return s;
}

int
compar_syms(const void *ai, const void *aj) {
  uint32 i = (*(Sym**)ai)->id;
  uint32 j = (*(Sym**)aj)->id;
  return (i > j) ? 1 : ((i < j) ? -1 : 0);
}

int
Sym::imm_int(int *result) {
  int i = 0;
  switch (type->num_kind) {
    default: return -1;
    case IF1_NUM_KIND_UINT: {
      switch (type->num_index) {
        case IF1_INT_TYPE_8:  i = imm.v_uint8; break;
        case IF1_INT_TYPE_16: i = imm.v_uint16; break;
        case IF1_INT_TYPE_32: i = imm.v_uint32; break;
        case IF1_INT_TYPE_64: i = imm.v_uint64; break;
        default: return -1;
      }
      break;
    }
    case IF1_NUM_KIND_INT: {
      switch (type->num_index) {
        case IF1_INT_TYPE_8:  i = imm.v_int8; break;
        case IF1_INT_TYPE_16: i = imm.v_int16; break;
        case IF1_INT_TYPE_32: i = imm.v_int32; break;
        case IF1_INT_TYPE_64: i = imm.v_int64; break;
        default: return -1;
      }
      break;
    }
  }
  *result = i;
  return 0;
}

Sym *
unalias_type(Sym *s) {
  if (!s)
    return s;
  if (s->type_kind == Type_ALIAS) {
    Vec<Sym *> aliases;
    do {
      if (!s->alias)
        return 0;
      Sym *ss = s->alias;
      if (aliases.set_in(ss))
        fail("circular type alias");
      aliases.set_add(ss);
      s = ss;
    } while (s->type_kind == Type_ALIAS);
  }
  return s;
}

void
if1_set_int_type(IF1 *p, Sym *t, int signd, int size) {
  int ss = 0;
  size >>= 3;
  while (size) { ss++; size >>= 1; }
  p->int_types[ss][signd] = t;
  t->num_kind = signd ? IF1_NUM_KIND_INT : IF1_NUM_KIND_UINT;
  t->num_index = ss;
}

void
if1_set_float_type(IF1 *p, Sym *t, int size) {
  int ss = 0;
  size >>= 4;
  ss = size - 1;
  p->float_types[ss] = t;
  t->num_kind = IF1_NUM_KIND_FLOAT;
  t->num_index = ss;
}

void
if1_set_complex_type(IF1 *p, Sym *t, int size) {
  int ss = 0;
  size >>= 4;
  ss = size - 1;
  p->complex_types[ss] = t;
  t->num_kind = IF1_NUM_KIND_COMPLEX;
  t->num_index = ss;
}

int
if1_numeric_size(IF1 *p, Sym *t) {
  switch (t->num_kind) {
    case IF1_NUM_KIND_NONE: assert(!"bad case"); break;
    case IF1_NUM_KIND_INT:
    case IF1_NUM_KIND_UINT:
      if (!t->num_index) return sizeof(bool);
      return 1 << ((t->num_index ? t->num_index : 1) - 1);
    case IF1_NUM_KIND_FLOAT:
      return 2 + (2 * t->num_index);
    case IF1_NUM_KIND_COMPLEX:
      return 2 * (2 + (2 * t->num_index));
  }
  return 0;
}

#define MAKE_ALIGNOF(_t) \
struct AlignOf##_t {      \
  char a;                \
  _t b;                  \
}

#define ALIGNOF(_t) ((int)(intptr_t)&(((struct AlignOf##_t *)0)->b))

MAKE_ALIGNOF(bool);
MAKE_ALIGNOF(uint8);
MAKE_ALIGNOF(uint16);
MAKE_ALIGNOF(uint32);
MAKE_ALIGNOF(uint64);
MAKE_ALIGNOF(float32);
MAKE_ALIGNOF(float64);
MAKE_ALIGNOF(float128);
MAKE_ALIGNOF(complex32);
MAKE_ALIGNOF(complex64);
typedef char *alignstring;
MAKE_ALIGNOF(alignstring);

int
if1_numeric_alignment(IF1 *p, Sym *t) {
  int res = -1;
  switch (t->num_kind) {
    default: assert(!"case"); break;
    case IF1_NUM_KIND_UINT:
    case IF1_NUM_KIND_INT:
      switch (t->num_index) {
        case IF1_INT_TYPE_1: return ALIGNOF(bool); break;
        case IF1_INT_TYPE_8: return ALIGNOF(uint8); break;
        case IF1_INT_TYPE_16: return ALIGNOF(uint16); break;
        case IF1_INT_TYPE_32: return ALIGNOF(uint32); break;
        case IF1_INT_TYPE_64: return ALIGNOF(uint64); break;
        default: assert(!"case");
      }
      break;
    case IF1_NUM_KIND_FLOAT:
      switch (t->num_index) {
        case IF1_FLOAT_TYPE_32:  return ALIGNOF(float32);
        case IF1_FLOAT_TYPE_64:  return ALIGNOF(float64);
        case IF1_FLOAT_TYPE_128: return ALIGNOF(float128);
        default: assert(!"case");
      }
      break;
    case IF1_NUM_KIND_COMPLEX:
      switch (t->num_index) {
        case IF1_FLOAT_TYPE_32: return ALIGNOF(complex32);
        case IF1_FLOAT_TYPE_64: return ALIGNOF(complex64);
        default: assert(!"case");
      }
      break;
    case IF1_CONST_KIND_STRING: return ALIGNOF(alignstring);
  }
  return res;
}

void
Sym::inherits_add(Sym *s) {
  implements.add(s);
  specializes.add(s);
  includes.add(s);
}

void
Sym::must_implement_and_specialize(Sym *s) {
  assert((!must_implement || must_implement == s) &&
         (!must_specialize || must_specialize == s));
  must_implement = s;
  must_specialize = s;
}

Sym *
Sym::scalar_type() {
  if (type && type->num_kind)
    return type;
  return 0;
}

Sym *
Sym::coerce_to(Sym *to) {
  if (this == to)
    return this;
  Sym *s1 = this->scalar_type(), *s2 = to->scalar_type();
  if (s1 && s2) {
    Sym *t = coerce_num(s1, s2);
    if (t == s2)
      return s2;
    return NULL;
  }
  if (element) {
    Sym *s1 = element->scalar_type(), *s2 = to->scalar_type();
    if (s1 && s2) {
      Sym *t = coerce_num(s1, s2);
      if (t == s2)
        return s2;
      return NULL;
    }
  }
  if (s1) {
    if (to == sym_string)
      return to;
  }
  return NULL;
}

void
Sym::convert_constant_string_to_immediate() {
  if (!is_constant)
    return;
  imm.const_kind = type->num_kind;
  imm.num_index = type->num_index;
  convert_string_to_immediate(constant, &imm);
}

static Sym *
int_constant_internal(IF1 *i, int n, Sym *t) {
  Immediate imm;
  imm.v_int32 = n;
  if (n >= 0 && n < 10) {
    char c[2];
    c[0] = n + '0';
    c[1] = 0;
    return if1_const(i, t, c, &imm);
  } else {
    char str[100];
    sprintf(str, "%d", n);
    return if1_const(i, t, str, &imm);
  }
}

Sym *
int32_constant(int n) {
  return int_constant_internal(if1, n, sym_int32);
}

Sym *
size_constant(int n) {
  return int_constant_internal(if1, n, sym_size);
}

Sym *
imm_constant(Immediate &imm, Sym *t) {
  char str[256];
  sprint_imm(str, imm);
  return if1_const(if1, t, str, &imm);
}

void
pp(Sym *s) {
  printf("(SYM %d ", s->id);
  if1_dump_sym(stdout, s);
  printf(")");
}
<|endoftext|>


<commit_before>// Copyright 2004-present Facebook. All Rights Reserved.

#include <folly/io/async/ScopedEventBaseThread.h>
#include <gmock/gmock.h>
#include <thread>

#include "RSocketTests.h"

#include "test/handlers/HelloServiceHandler.h"

#include "yarpl/flowable/TestSubscriber.h"

using namespace rsocket;
using namespace rsocket::tests;
using namespace testing;
using namespace rsocket::tests::client_server;
using namespace yarpl::flowable;

namespace {

class MockConnEvents : public RSocketConnectionEvents {
 public:
  MOCK_METHOD0(onConnected, void());
  MOCK_METHOD1(onDisconnected, void(const folly::exception_wrapper&));
  MOCK_METHOD0(onStreamsPaused, void());
  MOCK_METHOD0(onStreamsResumed, void());
  MOCK_METHOD1(onClosed, void(const folly::exception_wrapper&));
};

} // anonymous namespace

TEST(ConnectionEventsTest, SimpleStream) {
  folly::ScopedEventBaseThread worker;
  auto serverConnEvents = std::make_shared<StrictMock<MockConnEvents>>();
  auto clientConnEvents = std::make_shared<StrictMock<MockConnEvents>>();

  EXPECT_CALL(*clientConnEvents, onConnected());
  EXPECT_CALL(*serverConnEvents, onConnected());

  // create server supporting resumption
  auto server = makeResumableServer(
      std::make_shared<HelloServiceHandler>(serverConnEvents));

  // create resumable client
  auto client = makeWarmResumableClient(
      worker.getEventBase(), *server->listeningPort(), clientConnEvents);

  // request stream
  auto requester = client->getRequester();
  auto ts = TestSubscriber<std::string>::create(7 /* initialRequestN */);
  requester->requestStream(Payload("Bob"))
      ->map([](auto p) { return p.moveDataToString(); })
      ->subscribe(ts);
  // Wait for a few frames before disconnecting.
  while (ts->getValueCount() < 3) {
    std::this_thread::yield();
  }

  // disconnect
  EXPECT_CALL(*clientConnEvents, onDisconnected(_));
  EXPECT_CALL(*clientConnEvents, onStreamsPaused());
  EXPECT_CALL(*serverConnEvents, onDisconnected(_));
  EXPECT_CALL(*serverConnEvents, onStreamsPaused());
  client->disconnect(std::runtime_error("Test triggered disconnect"));

  // resume
  EXPECT_CALL(*clientConnEvents, onConnected());
  EXPECT_CALL(*clientConnEvents, onStreamsResumed());
  EXPECT_CALL(*serverConnEvents, onConnected());
  EXPECT_CALL(*serverConnEvents, onStreamsResumed());
  EXPECT_NO_THROW(client->resume().get());

  ts->request(3);
  ts->awaitTerminalEvent();
  ts->assertSuccess();
  ts->assertValueCount(10);

  // disconnect
  EXPECT_CALL(*clientConnEvents, onDisconnected(_));
  EXPECT_CALL(*clientConnEvents, onStreamsPaused());
  EXPECT_CALL(*serverConnEvents, onDisconnected(_));
  EXPECT_CALL(*serverConnEvents, onStreamsPaused());
  client->disconnect(std::runtime_error("Test triggered disconnect"));

  // relinquish resources
  EXPECT_CALL(*clientConnEvents, onClosed(_));
  EXPECT_CALL(*serverConnEvents, onClosed(_));
}
<commit_msg>Verify ConnectionEvents are calledback on right EventBase (#811)<commit_after>// Copyright 2004-present Facebook. All Rights Reserved.

#include <folly/io/async/ScopedEventBaseThread.h>
#include <gmock/gmock.h>
#include <thread>

#include "RSocketTests.h"

#include "test/handlers/HelloServiceHandler.h"

#include "yarpl/flowable/TestSubscriber.h"

using namespace rsocket;
using namespace rsocket::tests;
using namespace testing;
using namespace rsocket::tests::client_server;
using namespace yarpl::flowable;

namespace {

class MockConnEvents : public RSocketConnectionEvents {
 public:
  MOCK_METHOD0(onConnected, void());
  MOCK_METHOD1(onDisconnected, void(const folly::exception_wrapper&));
  MOCK_METHOD0(onStreamsPaused, void());
  MOCK_METHOD0(onStreamsResumed, void());
  MOCK_METHOD1(onClosed, void(const folly::exception_wrapper&));
};

} // anonymous namespace

TEST(ConnectionEventsTest, SimpleStream) {
  folly::ScopedEventBaseThread worker;
  auto serverConnEvents = std::make_shared<StrictMock<MockConnEvents>>();
  auto clientConnEvents = std::make_shared<StrictMock<MockConnEvents>>();

  EXPECT_CALL(*clientConnEvents, onConnected());
  EXPECT_CALL(*serverConnEvents, onConnected());

  // create server supporting resumption
  auto server = makeResumableServer(
      std::make_shared<HelloServiceHandler>(serverConnEvents));

  // create resumable client
  auto client = makeWarmResumableClient(
      worker.getEventBase(), *server->listeningPort(), clientConnEvents);

  // request stream
  auto requester = client->getRequester();
  auto ts = TestSubscriber<std::string>::create(7 /* initialRequestN */);
  requester->requestStream(Payload("Bob"))
      ->map([](auto p) { return p.moveDataToString(); })
      ->subscribe(ts);
  // Wait for a few frames before disconnecting.
  while (ts->getValueCount() < 3) {
    std::this_thread::yield();
  }

  // disconnect
  EXPECT_CALL(*clientConnEvents, onDisconnected(_));
  EXPECT_CALL(*clientConnEvents, onStreamsPaused());
  EXPECT_CALL(*serverConnEvents, onDisconnected(_));
  EXPECT_CALL(*serverConnEvents, onStreamsPaused());
  client->disconnect(std::runtime_error("Test triggered disconnect"));

  // resume
  EXPECT_CALL(*clientConnEvents, onConnected());
  EXPECT_CALL(*clientConnEvents, onStreamsResumed());
  EXPECT_CALL(*serverConnEvents, onConnected());
  EXPECT_CALL(*serverConnEvents, onStreamsResumed());
  EXPECT_NO_THROW(client->resume().get());

  ts->request(3);
  ts->awaitTerminalEvent();
  ts->assertSuccess();
  ts->assertValueCount(10);

  // disconnect
  EXPECT_CALL(*clientConnEvents, onDisconnected(_));
  EXPECT_CALL(*clientConnEvents, onStreamsPaused());
  EXPECT_CALL(*serverConnEvents, onDisconnected(_));
  EXPECT_CALL(*serverConnEvents, onStreamsPaused());
  client->disconnect(std::runtime_error("Test triggered disconnect"));

  // relinquish resources
  EXPECT_CALL(*clientConnEvents, onClosed(_));
  EXPECT_CALL(*serverConnEvents, onClosed(_));
}

// Verify the ConnectionEvents are called back on the right EventBase.
TEST(ConnectionEventsTest, DifferentEvb) {
  folly::ScopedEventBaseThread transportWorker{"TransportWkr"};
  folly::ScopedEventBaseThread SMWorker{"SMWorker"};

  auto clientConnEvents = std::make_shared<StrictMock<MockConnEvents>>();

  EXPECT_CALL(*clientConnEvents, onConnected()).WillOnce(
      Invoke([evb = SMWorker.getEventBase()]() {
    EXPECT_TRUE(evb->isInEventBaseThread());
  }));

  // create server supporting resumption
  auto server = makeResumableServer(
      std::make_shared<HelloServiceHandler>());

  // create resumable client
  auto client = makeWarmResumableClient(
      transportWorker.getEventBase(),
      *server->listeningPort(),
      clientConnEvents,
      SMWorker.getEventBase());

  // request stream
  auto requester = client->getRequester();
  auto ts = TestSubscriber<std::string>::create(7 /* initialRequestN */);
  requester->requestStream(Payload("Bob"))
      ->map([](auto p) { return p.moveDataToString(); })
      ->subscribe(ts);
  // Wait for a few frames before disconnecting.
  while (ts->getValueCount() < 3) {
    std::this_thread::yield();
  }

  // disconnect
  EXPECT_CALL(*clientConnEvents, onDisconnected(_)).WillOnce(
      InvokeWithoutArgs([evb = SMWorker.getEventBase()]() {
        EXPECT_TRUE(evb->isInEventBaseThread());
      }));
  EXPECT_CALL(*clientConnEvents, onStreamsPaused()).WillOnce(
      Invoke([evb = SMWorker.getEventBase()]() {
        EXPECT_TRUE(evb->isInEventBaseThread());
      }));
  client->disconnect(std::runtime_error("Test triggered disconnect"));

  // resume
  EXPECT_CALL(*clientConnEvents, onConnected()).WillOnce(
      Invoke([evb = SMWorker.getEventBase()]() {
        EXPECT_TRUE(evb->isInEventBaseThread());
      }));
  EXPECT_CALL(*clientConnEvents, onStreamsResumed()).WillOnce(
      Invoke([evb = SMWorker.getEventBase()]() {
        EXPECT_TRUE(evb->isInEventBaseThread());
      }));
  EXPECT_NO_THROW(client->resume().get());

  ts->request(3);
  ts->awaitTerminalEvent();
  ts->assertSuccess();
  ts->assertValueCount(10);

  // disconnect
  EXPECT_CALL(*clientConnEvents, onDisconnected(_)).WillOnce(
      InvokeWithoutArgs([evb = SMWorker.getEventBase()]() {
        EXPECT_TRUE(evb->isInEventBaseThread());
      }));
  EXPECT_CALL(*clientConnEvents, onStreamsPaused()).WillOnce(
      Invoke([evb = SMWorker.getEventBase()]() {
        EXPECT_TRUE(evb->isInEventBaseThread());
      }));
  client->disconnect(std::runtime_error("Test triggered disconnect"));

  // relinquish resources
  EXPECT_CALL(*clientConnEvents, onClosed(_)).WillOnce(
      InvokeWithoutArgs([evb = SMWorker.getEventBase()]() {
        EXPECT_TRUE(evb->isInEventBaseThread());
      }));
}
<|endoftext|>


<commit_before>//
// Copyright (c) 2011 Kim Walisch, <kim.walisch@gmail.com>.
// All rights reserved.
//
// This file is part of primesieve.
// Visit: http://primesieve.googlecode.com
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
//   * Redistributions of source code must retain the above copyright
//     notice, this list of conditions and the following disclaimer.
//   * Redistributions in binary form must reproduce the above
//     copyright notice, this list of conditions and the following
//     disclaimer in the documentation and/or other materials provided
//     with the distribution.
//   * Neither the name of the author nor the names of its
//     contributors may be used to endorse or promote products derived
//     from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.

#include "ParallelPrimeSieve.h"
#include "PrimeSieve.h"
#include "PrimeNumberFinder.h"
#include "defs.h"
#include "imath.h"

#if defined(_OPENMP)
  #include <omp.h>
#endif

#include <cstdlib>
#include <stdexcept>
#include <algorithm>

ParallelPrimeSieve::ParallelPrimeSieve() :
  numThreads_(USE_IDEAL_NUM_THREADS), shm_(NULL) {
  this->setMinThreadInterval(defs::MIN_THREAD_INTERVAL);
}

/**
 * Get the maximum number of threads allowed for sieving
 * (omp_get_max_threads(), i.e. the number of logical CPU cores).
 */
int ParallelPrimeSieve::getMaxThreads() {
#if defined(_OPENMP)
  return omp_get_max_threads();
#else
  return 1;
#endif
}

/**
 * Get the current set number of threads for sieving.
 */
int ParallelPrimeSieve::getNumThreads() const {
  return (numThreads_ == USE_IDEAL_NUM_THREADS) ? this->getIdealNumThreads()
      : numThreads_;
}

uint64_t ParallelPrimeSieve::getSieveInterval() const {
  return stopNumber_ - startNumber_;
}

/**
 * Get an ideal number of threads for the current set startNumber_,
 * stopNumber_ and flags_.
 */
int ParallelPrimeSieve::getIdealNumThreads() const {
  // 1 thread to print primes in sequential order
  if (flags_ & PRINT_FLAGS)
    return 1;
  // each thread should at least sieve an interval of n^0.5/6 and not
  // smaller than minThreadInterval_ for a performance benefit
  uint64_t threadThreshold = std::max<uint64_t>(
      minThreadInterval_,
      isqrt(stopNumber_) / 6);

  int idealNumThreads = static_cast<int> (
      std::min<uint64_t>(
          this->getSieveInterval() / threadThreshold,
          this->getMaxThreads()));
  // 1 <= idealNumThreads <= getMaxThreads()
  return std::max<int>(1, idealNumThreads);
}

/**
 * Get a sieve interval that ensures a good load balance among
 * threads.
 */
uint64_t ParallelPrimeSieve::getIdealInterval() const {
  int numThreads = this->getNumThreads();
  if (numThreads == 1)
    return this->getSieveInterval();

  // idealInterval = n^0.5*2000 (0.1 percent initialization overhead)
  uint64_t idealInterval = std::max<uint64_t>(
      minThreadInterval_,
      isqrt(stopNumber_) * UINT64_C(2000));

  uint64_t maxThreadInterval = this->getSieveInterval() / numThreads;
  // correct the user's thread settings
  if (maxThreadInterval < minThreadInterval_)
    maxThreadInterval = this->getSieveInterval() / this->getIdealNumThreads();

  // minThreadInterval_ <= idealInterval <= maxThreadInterval
  return std::min(idealInterval, maxThreadInterval);
}

/**
 * Set the number of threads for sieving.
 * If numThreads is invalid (numThreads < 1 or > getMaxThreads()) it
 * is set to numThreads = USE_IDEAL_NUM_THREADS.
 */
void ParallelPrimeSieve::setNumThreads(int numThreads) {
  numThreads_ = (numThreads >= 1 && numThreads <= this->getMaxThreads())
      ? numThreads : USE_IDEAL_NUM_THREADS;
}

void ParallelPrimeSieve::setMinThreadInterval(uint64_t minThreadInterval) {
  // prevents gaps when sieving prime k-tuplets in parallel
  if (minThreadInterval < 100)
    throw std::underflow_error(
        "ParallelPrimeSieve: minThreadInterval must be >= 100");
  minThreadInterval_ = minThreadInterval;
}

/**
 * For use with the Qt primesieve application in ../qt-gui.
 * Initializes this ParallelPrimeSieve object with values from a
 * shared memory segment.
 */
void ParallelPrimeSieve::init(SharedMemory* shm) {
  if (shm == NULL)
    throw std::invalid_argument(
        "ParallelPrimeSieve: shared memory segment must not be NULL");
  shm_ = shm;
  this->setStartNumber(shm_->startNumber);
  this->setStopNumber(shm_->stopNumber);
  this->setSieveSize(shm_->sieveSize);
  this->setFlags(shm_->flags);
  this->setNumThreads(shm_->threads);
}

/**
 * Calculate the current status in percent of sieve().
 * @param processed A sieved interval (segment)
 */
void ParallelPrimeSieve::doStatus(uint32_t processed) {
#if defined(_OPENMP)
  #pragma omp critical (doStatus)
#endif
  {
    PrimeSieve::doStatus(processed);
    // communicate the current status via shared memory
    // to the Qt GUI process
    if (shm_ != NULL)
      shm_->status = status_;
  }
}

/**
 * Sieve the prime numbers and/or prime k-tuplets within the interval
 * [startNumber_, stopNumber_] in parallel using OpenMP.
 */
void ParallelPrimeSieve::sieve() {
  if (stopNumber_ < startNumber_)
    throw std::invalid_argument("STOP must be >= START");

#if defined(_OPENMP)
  double t1 = omp_get_wtime();
  this->reset();
  if (this->getSieveInterval() >= minThreadInterval_) {
    uint64_t idealInterval = this->getIdealInterval();
    uint64_t chunks = this->getSieveInterval() / idealInterval;
    uint64_t maxOffset = chunks * idealInterval;
    uint64_t maxStop = startNumber_ + maxOffset + 32 - maxOffset % 30;
    if (maxStop < stopNumber_)
      chunks++;
    int numThreads = this->getNumThreads();
    // OpenMP parallel sieving
    #pragma omp parallel for num_threads(numThreads) schedule(dynamic)
    for (int64_t i = 0; i < static_cast<int64_t> (chunks); i++) {
      uint64_t start = startNumber_ + idealInterval * i;
      uint64_t stop = startNumber_ + idealInterval * (i+1);
      // the start/stop numbers for PrimeSieve objects must be chosen
      // carefully in order to avoid gaps when sieving prime k-tuplets
      // in parallel
      if (i > 0)
        start += 32 - start % 30;
      stop += 32 - stop % 30;
      // sieve the interval [start, stop]
      PrimeSieve ps(start, std::min<uint64_t>(stop, stopNumber_), this);
      ps.sieve();
      #pragma omp critical (counts)
      for (int j = 0; j < COUNTS_SIZE; j++)
        counts_[j] += ps.getCounts(j);
    }
  } else // single-threaded sieving
    PrimeSieve::sieve();
  timeElapsed_ = omp_get_wtime() - t1;
#else
  PrimeSieve::sieve();
#endif
  // communicate the sieving results via shared memory
  // segment to the Qt GUI process
  if (shm_ != NULL) {
    for (int i = 0; i < COUNTS_SIZE; i++)
      shm_->counts[i] = counts_[i];
    shm_->timeElapsed = timeElapsed_;
  }
}
<commit_msg>improved code readability<commit_after>//
// Copyright (c) 2011 Kim Walisch, <kim.walisch@gmail.com>.
// All rights reserved.
//
// This file is part of primesieve.
// Visit: http://primesieve.googlecode.com
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
//   * Redistributions of source code must retain the above copyright
//     notice, this list of conditions and the following disclaimer.
//   * Redistributions in binary form must reproduce the above
//     copyright notice, this list of conditions and the following
//     disclaimer in the documentation and/or other materials provided
//     with the distribution.
//   * Neither the name of the author nor the names of its
//     contributors may be used to endorse or promote products derived
//     from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.

#include "ParallelPrimeSieve.h"
#include "PrimeSieve.h"
#include "PrimeNumberFinder.h"
#include "defs.h"
#include "imath.h"

#if defined(_OPENMP)
  #include <omp.h>
#endif

#include <cstdlib>
#include <stdexcept>
#include <algorithm>

ParallelPrimeSieve::ParallelPrimeSieve() :
  numThreads_(USE_IDEAL_NUM_THREADS), shm_(NULL) {
  this->setMinThreadInterval(defs::MIN_THREAD_INTERVAL);
}

/**
 * Get the maximum number of threads allowed for sieving
 * (omp_get_max_threads(), i.e. the number of logical CPU cores).
 */
int ParallelPrimeSieve::getMaxThreads() {
#if defined(_OPENMP)
  return omp_get_max_threads();
#else
  return 1;
#endif
}

/**
 * Get the current set number of threads for sieving.
 */
int ParallelPrimeSieve::getNumThreads() const {
  return (numThreads_ == USE_IDEAL_NUM_THREADS) ? this->getIdealNumThreads()
      : numThreads_;
}

uint64_t ParallelPrimeSieve::getSieveInterval() const {
  return stopNumber_ - startNumber_;
}

/**
 * Get an ideal number of threads for the current set startNumber_,
 * stopNumber_ and flags_.
 */
int ParallelPrimeSieve::getIdealNumThreads() const {
  // 1 thread to print primes in sequential order
  if (flags_ & PRINT_FLAGS)
    return 1;
  // each thread should at least sieve an interval of n^0.5/6 and not
  // smaller than minThreadInterval_ for a performance benefit
  uint64_t threadThreshold = std::max<uint64_t>(
      minThreadInterval_, isqrt(stopNumber_) / 6);

  int idealNumThreads = static_cast<int> (
      std::min<uint64_t>(
          this->getSieveInterval() / threadThreshold,
          this->getMaxThreads()));
  // 1 <= idealNumThreads <= getMaxThreads()
  return std::max<int>(1, idealNumThreads);
}

/**
 * Get a sieve interval that ensures a good load balance among
 * threads.
 */
uint64_t ParallelPrimeSieve::getIdealInterval() const {
  int numThreads = this->getNumThreads();
  if (numThreads == 1)
    return this->getSieveInterval();

  // idealInterval = n^0.5*2000 (0.1 percent initialization overhead)
  uint64_t idealInterval = std::max<uint64_t>(
      minThreadInterval_, isqrt(stopNumber_) * UINT64_C(2000));

  uint64_t maxThreadInterval = this->getSieveInterval() / numThreads;
  // correct the user's thread settings
  if (maxThreadInterval < this->getSieveInterval() &&
      maxThreadInterval < minThreadInterval_)
    maxThreadInterval = this->getSieveInterval() / this->getIdealNumThreads();

  assert(maxThreadInterval == this->getSieveInterval() ||
         maxThreadInterval >= minThreadInterval_);
  return std::min<uint64_t>(idealInterval, maxThreadInterval);
}

/**
 * Set the number of threads for sieving.
 * If numThreads is invalid (numThreads < 1 or > getMaxThreads()) it
 * is set to numThreads = USE_IDEAL_NUM_THREADS.
 */
void ParallelPrimeSieve::setNumThreads(int numThreads) {
  numThreads_ = (numThreads >= 1 && numThreads <= this->getMaxThreads())
      ? numThreads : USE_IDEAL_NUM_THREADS;
}

void ParallelPrimeSieve::setMinThreadInterval(uint64_t minThreadInterval) {
  // prevents gaps when sieving prime k-tuplets in parallel
  if (minThreadInterval < 100)
    throw std::underflow_error(
        "ParallelPrimeSieve: minThreadInterval must be >= 100");
  minThreadInterval_ = minThreadInterval;
}

/**
 * For use with the Qt primesieve application in ../qt-gui.
 * Initializes this ParallelPrimeSieve object with values from a
 * shared memory segment.
 */
void ParallelPrimeSieve::init(SharedMemory* shm) {
  if (shm == NULL)
    throw std::invalid_argument(
        "ParallelPrimeSieve: shared memory segment must not be NULL");
  shm_ = shm;
  this->setStartNumber(shm_->startNumber);
  this->setStopNumber(shm_->stopNumber);
  this->setSieveSize(shm_->sieveSize);
  this->setFlags(shm_->flags);
  this->setNumThreads(shm_->threads);
}

/**
 * Calculate the current status in percent of sieve().
 * @param processed A sieved interval (segment)
 */
void ParallelPrimeSieve::doStatus(uint32_t processed) {
#if defined(_OPENMP)
  #pragma omp critical (doStatus)
#endif
  {
    PrimeSieve::doStatus(processed);
    // communicate the current status via shared memory
    // to the Qt GUI process
    if (shm_ != NULL)
      shm_->status = status_;
  }
}

/**
 * Sieve the prime numbers and/or prime k-tuplets within the interval
 * [startNumber_, stopNumber_] in parallel using OpenMP.
 */
void ParallelPrimeSieve::sieve() {
  if (stopNumber_ < startNumber_)
    throw std::invalid_argument("STOP must be >= START");

#if defined(_OPENMP)
  double t1 = omp_get_wtime();
  this->reset();
  uint64_t idealInterval = this->getIdealInterval();
  uint64_t chunks = this->getSieveInterval() / idealInterval;
  uint64_t maxOffset = chunks * idealInterval;
  uint64_t maxStop = startNumber_ + maxOffset + 32 - maxOffset % 30;
  if (maxStop < stopNumber_)
    chunks++;
  int numThreads = this->getNumThreads();
  // OpenMP parallel sieving
  #pragma omp parallel for num_threads(numThreads) schedule(dynamic)
  for (int64_t i = 0; i < static_cast<int64_t> (chunks); i++) {
    uint64_t start = startNumber_ + idealInterval * i;
    uint64_t stop = startNumber_ + idealInterval * (i+1);
    // the start/stop numbers for PrimeSieve objects must be chosen
    // carefully in order to avoid gaps when sieving prime k-tuplets
    // in parallel
    if (i > 0)
      start += 32 - start % 30;
    stop += 32 - stop % 30;
    // sieve the interval [start, stop]
    PrimeSieve ps(start, std::min<uint64_t>(stop, stopNumber_), this);
    ps.sieve();
    #pragma omp critical (counts)
    for (int j = 0; j < COUNTS_SIZE; j++)
      counts_[j] += ps.getCounts(j);
  }
  timeElapsed_ = omp_get_wtime() - t1;
#else
  PrimeSieve::sieve();
#endif
  // communicate the sieving results via shared memory
  // segment to the Qt GUI process
  if (shm_ != NULL) {
    for (int i = 0; i < COUNTS_SIZE; i++)
      shm_->counts[i] = counts_[i];
    shm_->timeElapsed = timeElapsed_;
  }
}
<|endoftext|>


<commit_before>#include <iostream>

#include "Method.h"
#include "../execution/Program.h"
#include "../types/infrastructure/ThingInstance.h"

void Method::execute() {
    Program::create_frame(frame_size);

    for (size_t i = 0; i < arguments; i++) {
        Program::frame()[arguments - i - 1] = Program::pop();
    }

    auto counter_end = symbols.size();

    for (Index counter = 0; counter < counter_end;) {
        auto symbol = symbols[counter];

        Program::status(counter, symbol);

        switch (symbol.opcode) {

            case Opcode::PASS:
                break;

            case Opcode::CALL: {
                Program::types[symbol.target]->call(symbol.secondary);
                break;
            }

            case Opcode::CALL_INTERNAL: {
                auto ret_val = Program::internals[symbol.target]->call(symbol.secondary);
                Program::push(ret_val);
                break;
            }

            case Opcode::INSTANTIATE: {
                Program::frame()[0] = Thing(new ThingInstance);
                break;
            }

            case Opcode::PUSH_LOCAL: {
                Program::push(Program::frame()[symbol.target]);
                break;
            };

            case Opcode::PUSH_STATIC: {
                Program::push(Program::data(symbol.target));
                break;
            }

            case Opcode::PUSH_NULL: {
                Program::push(nullptr);
                break;
            }

            case Opcode::POP: {
                Program::pop();
                break;
            }

            case Opcode::POP_LOCAL: {
                Program::frame()[symbol.target] = Program::pop();
                break;
            }

            case Opcode::SET_LOCAL: {
                Program::frame()[symbol.target] = Program::data(symbol.secondary);
                break;
            }

            case Opcode::RESOLVE: {
                Program::push(Program::pop()->operator[](symbol.target));
            }

            case Opcode::RETURN: {
                counter = counter_end;
                continue;
            }

            case Opcode::JUMP: {
                counter = symbol.target;
                continue;
            }

            case Opcode::JUMP_CONDITIONAL: {
                auto value = Program::pop();

                if (!value || !value->boolean()) {
                    counter = symbol.target;
                    continue;
                }

                break;
            }

            default:
                throw RuntimeError(
                        std::string("Cannot handle symbol ") + describe(symbol.opcode) + " (" + std::to_string((int) symbol.opcode) +
                        ")");

        }

        counter++;
    };

    Program::pop_frame();
}

<commit_msg>Push instantiation result to stack for return<commit_after>#include <iostream>

#include "Method.h"
#include "../execution/Program.h"
#include "../types/infrastructure/ThingInstance.h"

void Method::execute() {
    Program::create_frame(frame_size);

    for (size_t i = 0; i < arguments; i++) {
        Program::frame()[arguments - i - 1] = Program::pop();
    }

    auto counter_end = symbols.size();

    for (Index counter = 0; counter < counter_end;) {
        auto symbol = symbols[counter];

        Program::status(counter, symbol);

        switch (symbol.opcode) {

            case Opcode::PASS:
                break;

            case Opcode::CALL: {
                Program::types[symbol.target]->call(symbol.secondary);
                break;
            }

            case Opcode::CALL_INTERNAL: {
                auto ret_val = Program::internals[symbol.target]->call(symbol.secondary);
                Program::push(ret_val);
                break;
            }

            case Opcode::INSTANTIATE: {
                auto new_thing = Thing(new ThingInstance);
                Program::frame()[0] = new_thing;
                Program::push(new_thing);
                break;
            }

            case Opcode::PUSH_LOCAL: {
                Program::push(Program::frame()[symbol.target]);
                break;
            };

            case Opcode::PUSH_STATIC: {
                Program::push(Program::data(symbol.target));
                break;
            }

            case Opcode::PUSH_NULL: {
                Program::push(nullptr);
                break;
            }

            case Opcode::POP: {
                Program::pop();
                break;
            }

            case Opcode::POP_LOCAL: {
                Program::frame()[symbol.target] = Program::pop();
                break;
            }

            case Opcode::SET_LOCAL: {
                Program::frame()[symbol.target] = Program::data(symbol.secondary);
                break;
            }

            case Opcode::RESOLVE: {
                Program::push(Program::pop()->operator[](symbol.target));
            }

            case Opcode::RETURN: {
                counter = counter_end;
                continue;
            }

            case Opcode::JUMP: {
                counter = symbol.target;
                continue;
            }

            case Opcode::JUMP_CONDITIONAL: {
                auto value = Program::pop();

                if (!value || !value->boolean()) {
                    counter = symbol.target;
                    continue;
                }

                break;
            }

            default:
                throw RuntimeError(
                        std::string("Cannot handle symbol ") + describe(symbol.opcode) + " (" + std::to_string((int) symbol.opcode) +
                        ")");

        }

        counter++;
    };

    Program::pop_frame();
}

<|endoftext|>