<commit_before>/* Copyright 2019 Stanford University
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "optimize_tracing_invalidate1.h"

#include "mappers/default_mapper.h"

using namespace Legion;
using namespace Legion::Mapping;

class TracingMapper : public DefaultMapper
{
public:
  TracingMapper(MapperRuntime *rt, Machine machine, Processor local,
                const char *mapper_name);
public:
  virtual void slice_task(const MapperContext      ctx,
                          const Task&              task,
                          const SliceTaskInput&    input,
                                SliceTaskOutput&   output);
  virtual void map_task(const MapperContext ctx,
                        const Task &task,
                        const MapTaskInput &input,
                        MapTaskOutput &output);
private:
  typedef std::map<std::pair<LogicalRegion,FieldID>,PhysicalInstance> Mapping;
  Mapping inc_instances;
  Mapping step_instances;
  Mapping check_instances;
};

TracingMapper::TracingMapper(MapperRuntime *rt, Machine machine, Processor local,
                             const char *mapper_name)
  : DefaultMapper(rt, machine, local, mapper_name)
{
}

void TracingMapper::slice_task(const MapperContext      ctx,
                               const Task&              task,
                               const SliceTaskInput&    input,
                                     SliceTaskOutput&   output)
{
  DomainT<1,coord_t> point_space = input.domain;
  Point<1,coord_t> num_blocks(local_cpus.size());
  default_decompose_points<1>(point_space, local_cpus,
                              num_blocks, false/*recurse*/,
                              stealing_enabled, output.slices);
}

void TracingMapper::map_task(const MapperContext ctx,
                             const Task &task,
                             const MapTaskInput &input,
                             MapTaskOutput &output)
{
  if (strcmp(task.get_task_name(), "inc") == 0 ||
      strcmp(task.get_task_name(), "step") == 0 ||
      strcmp(task.get_task_name(), "check") == 0)
  {
    Mapping &mapping =
       strcmp(task.get_task_name(), "inc") == 0   ? inc_instances :
      (strcmp(task.get_task_name(), "step") == 0  ? step_instances : check_instances);

    Processor::Kind target_kind = task.target_proc.kind();
    VariantInfo chosen = default_find_preferred_variant(task, ctx,
        true/*needs tight bound*/, true/*cache*/, target_kind);
    output.chosen_variant = chosen.variant;
    output.task_priority = default_policy_select_task_priority(ctx, task);
    output.postmap_task = false;
    default_policy_select_target_processors(ctx, task, output.target_procs);

    bool need_acquire = false;
    for (unsigned idx = 0; idx < task.regions.size(); ++idx)
    {
      const RegionRequirement &req = task.regions[idx];
      for (std::set<FieldID>::const_iterator fit = req.privilege_fields.begin();
           fit != req.privilege_fields.end(); ++fit)
      {
        std::pair<LogicalRegion,FieldID> key(req.region, *fit);
        Mapping::iterator finder = mapping.find(key);
        if (finder == mapping.end())
        {
          PhysicalInstance result;
          Machine::MemoryQuery valid_mems(machine);
          valid_mems.has_affinity_to(task.target_proc);
          Memory target_memory = *valid_mems.begin();

          std::vector<LogicalRegion> target_regions(1, req.region);

          LayoutConstraintSet constraints;
          std::vector<FieldID> fields(1, *fit);
          std::vector<DimensionKind> dimension_ordering(1, DIM_X);

          constraints.add_constraint(SpecializedConstraint())
            .add_constraint(MemoryConstraint(target_memory.kind()))
            .add_constraint(FieldConstraint(fields, false, false))
            .add_constraint(OrderingConstraint(dimension_ordering, false));

          assert(runtime->create_physical_instance(ctx, target_memory,
                constraints, target_regions, result));
          mapping[key] = result;
          output.chosen_instances[idx].push_back(result);
        }
        else
        {
          output.chosen_instances[idx].push_back(finder->second);
          need_acquire = true;
        }
      }
    }
    if (need_acquire)
      runtime->acquire_instances(ctx, output.chosen_instances);
  }
  else
    DefaultMapper::map_task(ctx, task, input, output);
}

static void create_mappers(Machine machine, HighLevelRuntime *runtime, const std::set<Processor> &local_procs)
{
  for (std::set<Processor>::const_iterator it = local_procs.begin();
        it != local_procs.end(); it++)
  {
    TracingMapper* mapper = new TracingMapper(runtime->get_mapper_runtime(),
                                              machine, *it, "variant_mapper");
    runtime->replace_default_mapper(mapper, *it);
  }
}

void register_mappers()
{
  HighLevelRuntime::add_registration_callback(create_mappers);
}
<commit_msg>test: More fix for the unsafe mapper<commit_after>/* Copyright 2019 Stanford University
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "optimize_tracing_invalidate1.h"

#include "mappers/default_mapper.h"

using namespace Legion;
using namespace Legion::Mapping;

class TracingMapper : public DefaultMapper
{
public:
  TracingMapper(MapperRuntime *rt, Machine machine, Processor local,
                const char *mapper_name);
public:
  virtual void slice_task(const MapperContext      ctx,
                          const Task&              task,
                          const SliceTaskInput&    input,
                                SliceTaskOutput&   output);
  virtual void map_task(const MapperContext ctx,
                        const Task &task,
                        const MapTaskInput &input,
                        MapTaskOutput &output);
private:
  typedef std::map<std::pair<LogicalRegion,FieldID>,PhysicalInstance> Mapping;
  Mapping inc_instances;
  Mapping step_instances;
  Mapping check_instances;
};

TracingMapper::TracingMapper(MapperRuntime *rt, Machine machine, Processor local,
                             const char *mapper_name)
  : DefaultMapper(rt, machine, local, mapper_name)
{
}

void TracingMapper::slice_task(const MapperContext      ctx,
                               const Task&              task,
                               const SliceTaskInput&    input,
                                     SliceTaskOutput&   output)
{
  DomainT<1,coord_t> point_space = input.domain;
  Point<1,coord_t> num_blocks(local_cpus.size());
  default_decompose_points<1>(point_space, local_cpus,
                              num_blocks, false/*recurse*/,
                              stealing_enabled, output.slices);
}

void TracingMapper::map_task(const MapperContext ctx,
                             const Task &task,
                             const MapTaskInput &input,
                             MapTaskOutput &output)
{
  if (strcmp(task.get_task_name(), "inc") == 0 ||
      strcmp(task.get_task_name(), "step") == 0 ||
      strcmp(task.get_task_name(), "check") == 0)
  {
    Mapping &mapping =
       strcmp(task.get_task_name(), "inc") == 0   ? inc_instances :
      (strcmp(task.get_task_name(), "step") == 0  ? step_instances : check_instances);

    Processor::Kind target_kind = task.target_proc.kind();
    VariantInfo chosen = default_find_preferred_variant(task, ctx,
        true/*needs tight bound*/, true/*cache*/, target_kind);
    output.chosen_variant = chosen.variant;
    output.task_priority = default_policy_select_task_priority(ctx, task);
    output.postmap_task = false;
    default_policy_select_target_processors(ctx, task, output.target_procs);

    bool need_acquire = false;
    for (unsigned idx = 0; idx < task.regions.size(); ++idx)
    {
      const RegionRequirement &req = task.regions[idx];
      for (std::set<FieldID>::const_iterator fit = req.privilege_fields.begin();
           fit != req.privilege_fields.end(); ++fit)
      {
        std::pair<LogicalRegion,FieldID> key(req.region, *fit);
        Mapping::iterator finder = mapping.find(key);
        if (finder == mapping.end())
        {
          PhysicalInstance result;
          Machine::MemoryQuery valid_mems(machine);
          valid_mems.has_affinity_to(task.target_proc);
          valid_mems.only_kind(Memory::SYSTEM_MEM);
          Memory target_memory = *valid_mems.begin();

          std::vector<LogicalRegion> target_regions(1, req.region);

          LayoutConstraintSet constraints;
          std::vector<FieldID> fields(1, *fit);
          std::vector<DimensionKind> dimension_ordering(1, DIM_X);

          constraints.add_constraint(SpecializedConstraint())
            .add_constraint(MemoryConstraint(target_memory.kind()))
            .add_constraint(FieldConstraint(fields, false, false))
            .add_constraint(OrderingConstraint(dimension_ordering, false));

          assert(runtime->create_physical_instance(ctx, target_memory,
                constraints, target_regions, result));
          mapping[key] = result;
          output.chosen_instances[idx].push_back(result);
        }
        else
        {
          output.chosen_instances[idx].push_back(finder->second);
          need_acquire = true;
        }
      }
    }
    if (need_acquire && !runtime->acquire_instances(ctx, output.chosen_instances))
      assert(false);
  }
  else
    DefaultMapper::map_task(ctx, task, input, output);
}

static void create_mappers(Machine machine, HighLevelRuntime *runtime, const std::set<Processor> &local_procs)
{
  for (std::set<Processor>::const_iterator it = local_procs.begin();
        it != local_procs.end(); it++)
  {
    TracingMapper* mapper = new TracingMapper(runtime->get_mapper_runtime(),
                                              machine, *it, "variant_mapper");
    runtime->replace_default_mapper(mapper, *it);
  }
}

void register_mappers()
{
  HighLevelRuntime::add_registration_callback(create_mappers);
}
<|endoftext|>


<commit_before>#define CATCH_CONFIG_MAIN
#include "catch.hpp"

#include "config.h"
#if GAF_TEST_HEADER_ONLY
#define GENERATED_MYGAF_IMPLEMENTATION
#endif

#include "mygaf.h"

TEST_CASE("constructor") {
  const Foo foo;
  REQUIRE(foo.hello == 0);
  REQUIRE(foo.world == 0.0f);
}

TEST_CASE("setter") {
  Foo foo;
  foo.hello = 42;
  foo.world = 4.2f;
  REQUIRE(foo.hello == 42);
  REQUIRE(foo.world == 4.2f);
}
<commit_msg>use approx for floating point checks<commit_after>#define CATCH_CONFIG_MAIN
#include "catch.hpp"

#include "config.h"
#if GAF_TEST_HEADER_ONLY
#define GENERATED_MYGAF_IMPLEMENTATION
#endif

#include "mygaf.h"

TEST_CASE("constructor") {
  Foo foo;
  CHECK(foo.hello == 0);
  CHECK(foo.world == Approx(0.0f));
}

TEST_CASE("setter") {
  Foo foo;
  foo.hello = 42;
  foo.world = 4.2f;
  REQUIRE(foo.hello == 42);
  REQUIRE(foo.world == 4.2f);
}
<|endoftext|>


<commit_before>#include "catch.hpp"
#include "util.h"
#include <iostream>
#include <selector_parser.h>

using namespace shl;

TEST_CASE("Selector Parser Test") {
    SECTION("parse a simple selector") {
        selector::Parser parser("source.c storage.modifier.c keyword.core.control.if highlight.*");

        parser.parse();
    }
}
<commit_msg>add tests for selector parse<commit_after>#include "catch.hpp"
#include "util.h"
#include <iostream>
#include <selector_parser.h>
#include <selector.h>

using namespace shl;
using namespace shl::selector;

TEST_CASE("Selector Parser Test") {
    SECTION("parse a simple selector") {
        selector::Parser parser("R:source.ruby ruby.* | - L:pic.a pic b, source.c storage.modifier.c keyword.core.control.if highlight.*, L:(man.kind man.hello man.last $, B:( ^ test.n test.g, test.a > test.b > test.c $))");

        Selector s = parser.parse();

        REQUIRE( s.selectors.size() == 3);

        CompositeSelctor& first = s.selectors[0];
        REQUIRE( first.operators.size() == 2);
        REQUIRE( first.operators[0] == selector::CompositeSelctor::NONE );
        REQUIRE( first.operators[1] == selector::CompositeSelctor::OR );
        REQUIRE( first.selectors.size() == 2 );
        REQUIRE( first.selectors[0].is_negative == false );
        FilterSelector& first_filter = *(FilterSelector*)first.selectors[0].selector.get();
        REQUIRE( first_filter.side == FilterSelector::Right );
        ScopeSelector& first_filter_scope = *(ScopeSelector*)first_filter.selector.get();
        REQUIRE( first_filter_scope.atoms.size() == 2 );
        REQUIRE( first_filter_scope.atoms[0].components.size() == 2 );
        REQUIRE( first_filter_scope.atoms[0].components[0] == "source" );
        REQUIRE( first_filter_scope.atoms[0].components[1] == "ruby" );
        REQUIRE( first_filter_scope.atoms[1].components.size() == 2 );
        REQUIRE( first_filter_scope.atoms[1].components[0] == "ruby" );
        REQUIRE( first_filter_scope.atoms[1].components[1] == "*" );

        REQUIRE( first.selectors[1].is_negative == true );
        FilterSelector& first_filter2 = *(FilterSelector*)first.selectors[1].selector.get();
        REQUIRE( first_filter2.side == FilterSelector::Left );
        ScopeSelector& first_filter2_scope = *(ScopeSelector*)first_filter2.selector.get();
        REQUIRE( first_filter2_scope.atoms.size() == 3 );
        REQUIRE( first_filter2_scope.atoms[0].components.size() == 2 );
        REQUIRE( first_filter2_scope.atoms[0].components[0] == "pic" );
        REQUIRE( first_filter2_scope.atoms[0].components[1] == "a" );
        REQUIRE( first_filter2_scope.atoms[1].components.size() == 1 );
        REQUIRE( first_filter2_scope.atoms[1].components[0] == "pic" );
        REQUIRE( first_filter2_scope.atoms[2].components.size() == 1 );
        REQUIRE( first_filter2_scope.atoms[2].components[0] == "b" );

        CompositeSelctor& second = s.selectors[1];
        REQUIRE( second.operators.size() == 1 );
        REQUIRE( second.operators[0] == CompositeSelctor::NONE );
        REQUIRE( second.selectors.size() == 1 );
        ScopeSelector& second_scope = *(ScopeSelector*)second.selectors[0].selector.get();
        REQUIRE( second_scope.atoms.size() == 4 );

        CompositeSelctor& third = s.selectors[2];
        REQUIRE( third.operators.size() == 1 );
        FilterSelector& third_filter = *(FilterSelector*)third.selectors[0].selector.get();
        REQUIRE( third_filter.side == FilterSelector::Left );
        Selector& nest = ((GroupSelector*)third_filter.selector.get())->selector;
        REQUIRE( nest.selectors.size() == 2 );
        CompositeSelctor& nest_first = nest.selectors[0];
        REQUIRE( nest_first.selectors.size() == 1 );
        ScopeSelector& nest_first_scope = *(ScopeSelector*)nest_first.selectors[0].selector.get();
        REQUIRE( nest_first_scope.anchor_begin == false );
        REQUIRE( nest_first_scope.anchor_end == true );
        REQUIRE( nest_first_scope.atoms.size() == 3 );

        FilterSelector& nest_second = *(FilterSelector*)nest.selectors[1].selectors[0].selector.get();
        REQUIRE( nest_second.side == FilterSelector::Both );
        GroupSelector& nest_second_group = *(GroupSelector*)nest_second.selector.get();
        Selector& nest_nest = nest_second_group.selector;
        REQUIRE( nest_nest.selectors.size() == 2 );
        ScopeSelector& nest_nest_first = *(ScopeSelector*)nest_nest.selectors[0].selectors[0].selector.get();
        REQUIRE( nest_nest_first.atoms.size() == 2 );
        REQUIRE( nest_nest_first.anchor_begin == true );
        REQUIRE( nest_nest_first.anchor_end == false );

        ScopeSelector& nest_nest_second = *(ScopeSelector*)nest_nest.selectors[1].selectors[0].selector.get();
        REQUIRE( nest_nest_second.atoms.size() == 3 );
        REQUIRE( nest_nest_second.anchor_begin == false );
        REQUIRE( nest_nest_second.anchor_end == true );
        REQUIRE( nest_nest_second.atoms[0].anchor_prev == false );
        REQUIRE( nest_nest_second.atoms[1].anchor_prev == true );
    }
}
<|endoftext|>


<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#pragma once
#ifndef INCLUDE_FD_MAP_HPP
#define INCLUDE_FD_MAP_HPP

#include "fd.hpp"
#include <map>
#include <memory>
#include <stdexcept>
#include <string>

class FD_map_error : public std::runtime_error {
  using std::runtime_error::runtime_error;
};

class FD_not_found : public FD_map_error {
public:
  FD_not_found(int id)
    : FD_map_error(std::string{"ID "} + std::to_string(id) + " not found")
  {}
};

/**
 * @brief File descriptor map
 * @details Singleton class that manages all the file descriptors
 */
class FD_map {
public:
  using id_t = FD::id_t;

  static FD_map& instance()
  {
    static FD_map fd_map;
    return fd_map;
  }

  template <typename T, typename... Args>
  T& open(Args&&... args);

  FD& get(const id_t id) const;

  int close(const id_t id)
  { return (map_.erase(id)) ? 0 : -1; }

  template <typename T, typename... Args>
  static auto&& _open(Args&&... args)
  { return instance().open<T>(std::forward<Args>(args)...); }

  static auto&& _get(const id_t id)
  { return instance().get(id); }

  static int _close(id_t id)
  { return instance().close(id); }

private:
  std::map<id_t, std::unique_ptr<FD>> map_;
  FD_map() {}
};

template <typename T, typename... Args>
T& FD_map::open(Args&&... args)
{
  static_assert(std::is_base_of<FD, T>::value,
    "Template argument is not a File Descriptor (FD)");

  static id_t counter = 5;
  const auto id = counter++;
  auto* fd = new T(id, std::forward<Args>(args)...);
  map_.emplace(std::piecewise_construct, std::forward_as_tuple(id), std::forward_as_tuple(fd));
  return *fd;
}

inline FD& FD_map::get(const id_t id) const
{
  auto it = map_.find(id);
  if(it != map_.end())
    return *it->second;
  throw FD_not_found{id};
}

#endif
<commit_msg>posix: Assert on FD map close<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#pragma once
#ifndef INCLUDE_FD_MAP_HPP
#define INCLUDE_FD_MAP_HPP

#include "fd.hpp"
#include <map>
#include <memory>
#include <stdexcept>
#include <string>

class FD_map_error : public std::runtime_error {
  using std::runtime_error::runtime_error;
};

class FD_not_found : public FD_map_error {
public:
  FD_not_found(int id)
    : FD_map_error(std::string{"ID "} + std::to_string(id) + " not found")
  {}
};

/**
 * @brief File descriptor map
 * @details Singleton class that manages all the file descriptors
 */
class FD_map {
public:
  using id_t = FD::id_t;

  static FD_map& instance()
  {
    static FD_map fd_map;
    return fd_map;
  }

  template <typename T, typename... Args>
  T& open(Args&&... args);

  FD& get(const id_t id) const;

  template <typename T, typename... Args>
  static auto&& _open(Args&&... args)
  { return instance().open<T>(std::forward<Args>(args)...); }

  static auto&& _get(const id_t id)
  { return instance().get(id); }

  static void close(id_t id)
  { instance().internal_close(id); }

private:
  void internal_close(const id_t id)
  {
    auto erased = map_.erase(id);
    assert(erased > 0);
  }

  std::map<id_t, std::unique_ptr<FD>> map_;
  FD_map() {}
};

template <typename T, typename... Args>
T& FD_map::open(Args&&... args)
{
  static_assert(std::is_base_of<FD, T>::value,
    "Template argument is not a File Descriptor (FD)");

  static id_t counter = 5;
  const auto id = counter++;
  auto* fd = new T(id, std::forward<Args>(args)...);
  map_.emplace(std::piecewise_construct, std::forward_as_tuple(id), std::forward_as_tuple(fd));
  return *fd;
}

inline FD& FD_map::get(const id_t id) const
{
  auto it = map_.find(id);
  if(it != map_.end())
    return *it->second;
  throw FD_not_found{id};
}

#endif
<|endoftext|>


<commit_before>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/compiler/tf2xla/xla_jit_compiled_cpu_function.h"

#include <memory>
#include <string>

#include "absl/memory/memory.h"
#include "tensorflow/compiler/tf2xla/tf2xla.pb.h"
#include "tensorflow/compiler/xla/client/local_client.h"
#include "tensorflow/compiler/xla/service/compiler.h"
#include "tensorflow/compiler/xla/service/platform_util.h"
#include "tensorflow/compiler/xla/shape_util.h"
#include "tensorflow/compiler/xla/status_macros.h"
#include "tensorflow/compiler/xla/statusor.h"
#include "tensorflow/compiler/xla/test.h"
#include "tensorflow/compiler/xla/xla_data.pb.h"
#include "tensorflow/core/framework/attr_value.pb.h"
#include "tensorflow/core/framework/attr_value_util.h"
#include "tensorflow/core/framework/graph.pb.h"
#include "tensorflow/core/framework/node_def.pb.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/stream_executor/multi_platform_manager.h"
#include "tensorflow/stream_executor/platform.h"

namespace tensorflow {
namespace {

using ::testing::HasSubstr;

PLATFORM_DEFINE_ID(kFakePlatformId);

AttrValue TypeAttrValue(DataType type) {
  AttrValue attr_value;
  SetAttrValue(type, &attr_value);
  return attr_value;
}

GraphDef SumGraph() {
  GraphDef graph_def;
  NodeDef* x = graph_def.add_node();
  x->set_name("x");
  x->set_op("Placeholder");
  (*x->mutable_attr())["dtype"] = TypeAttrValue(DT_INT32);
  NodeDef* y = graph_def.add_node();
  y->set_name("y");
  y->set_op("Placeholder");
  (*y->mutable_attr())["dtype"] = TypeAttrValue(DT_INT32);
  NodeDef* sum = graph_def.add_node();
  sum->set_name("sum");
  sum->set_op("Add");
  sum->add_input("x");
  sum->add_input("y");
  (*sum->mutable_attr())["T"] = TypeAttrValue(DT_INT32);
  return graph_def;
}

tf2xla::Config SumConfig() {
  tf2xla::Config config;
  tf2xla::Feed* x = config.add_feed();
  x->mutable_id()->set_node_name("x");
  x->set_name("x_name");
  tf2xla::Feed* y = config.add_feed();
  y->mutable_id()->set_node_name("y");
  y->set_name("y_name");
  tf2xla::Fetch* sum = config.add_fetch();
  sum->mutable_id()->set_node_name("sum");
  sum->set_name("sum_name");
  return config;
}

TEST(XlaJitCompiledCpuFunction, Sum) {
  GraphDef graph_def = SumGraph();
  tf2xla::Config config = SumConfig();

  TF_ASSERT_OK_AND_ASSIGN(
      std::unique_ptr<XlaJitCompiledCpuFunction> jit,
      XlaJitCompiledCpuFunction::Compile(graph_def, config,
                                         xla::ExecutableBuildOptions()));
  XlaCompiledCpuFunction function(jit->StaticData());

  // Run the function and check results.
  *static_cast<int32*>(function.arg_data(0)) = 10;
  *static_cast<int32*>(function.arg_data(1)) = 32;
  EXPECT_TRUE(function.Run());
  EXPECT_EQ(function.error_msg(), "");
  EXPECT_EQ(*static_cast<int32*>(function.result_data(0)), 42);

  // Run the function again.
  *static_cast<int32*>(function.arg_data(0)) = 100;
  *static_cast<int32*>(function.arg_data(1)) = 320;
  EXPECT_TRUE(function.Run());
  EXPECT_EQ(function.error_msg(), "");
  EXPECT_EQ(*static_cast<int32*>(function.result_data(0)), 420);

  // Check name to index lookups.
  EXPECT_TRUE(function.HasNameIndices());

  EXPECT_EQ(function.LookupArgIndex("x_name"), 0);
  EXPECT_EQ(function.LookupArgIndex("y_name"), 1);
  EXPECT_EQ(function.LookupArgIndex(""), -1);
  EXPECT_EQ(function.LookupArgIndex("x"), -1);
  EXPECT_EQ(function.LookupArgIndex("y"), -1);
  EXPECT_EQ(function.LookupArgIndex("sum"), -1);
  EXPECT_EQ(function.LookupArgIndex("sum_name"), -1);

  EXPECT_EQ(function.LookupResultIndex("sum_name"), 0);
  EXPECT_EQ(function.LookupResultIndex(""), -1);
  EXPECT_EQ(function.LookupResultIndex("x"), -1);
  EXPECT_EQ(function.LookupResultIndex("y"), -1);
  EXPECT_EQ(function.LookupResultIndex("sum"), -1);
  EXPECT_EQ(function.LookupResultIndex("x_name"), -1);
  EXPECT_EQ(function.LookupResultIndex("y_name"), -1);

  // Check program shape.
  using xla::ShapeUtil;
  const xla::Shape s32 = ShapeUtil::MakeShape(xla::S32, {});
  ASSERT_TRUE(function.ProgramShape() != nullptr);
  const xla::ProgramShape program_shape(*function.ProgramShape());
  ASSERT_EQ(program_shape.parameters_size(), 2);
  EXPECT_TRUE(ShapeUtil::Compatible(program_shape.parameters(0), s32));
  EXPECT_TRUE(ShapeUtil::Compatible(program_shape.parameters(1), s32));

  const xla::Shape& result = program_shape.result();
  ASSERT_EQ(result.element_type(), xla::TUPLE);
  ASSERT_EQ(ShapeUtil::TupleElementCount(result), 1);
  const xla::Shape& result0 = ShapeUtil::GetTupleElementShape(result, 0);
  EXPECT_TRUE(ShapeUtil::Compatible(result0, s32));
}

// Test when a graph compilation terminates early, resources are properly
// reclaimed.
TEST(XlaJitCompiledCpuFunction, SumWithJunkAttr) {
  GraphDef graph_def = SumGraph();

  (*graph_def.mutable_node(2)->mutable_attr())["junk"] =
      TypeAttrValue(DT_INT32);

  tf2xla::Config config = SumConfig();
  EXPECT_FALSE(XlaJitCompiledCpuFunction::Compile(graph_def, config,
                                                  xla::ExecutableBuildOptions())
                   .ok());
}

TEST(XlaJitCompiledCpuFunction, CanCompileWithAdditionalPlatform) {
  class FakePlatform : public se::Platform {
   public:
    FakePlatform() : name_("FakePlatform") {}
    ~FakePlatform() override {}

    se::Platform::Id id() const override { return kFakePlatformId; }

    int VisibleDeviceCount() const override { return 0; }

    const string& Name() const override { return name_; }

    se::port::StatusOr<std::unique_ptr<se::DeviceDescription>>
    DescriptionForDevice(int ordinal) const override {
      return std::unique_ptr<se::DeviceDescription>(nullptr);
    }

    se::port::StatusOr<se::StreamExecutor*> ExecutorForDevice(
        int ordinal) override {
      return nullptr;
    }

    se::port::StatusOr<se::StreamExecutor*> ExecutorForDeviceWithPluginConfig(
        int ordinal, const se::PluginConfig& config) override {
      return nullptr;
    }

    se::port::StatusOr<se::StreamExecutor*> GetExecutor(
        const se::StreamExecutorConfig& config) override {
      return nullptr;
    }

    se::port::StatusOr<std::unique_ptr<se::StreamExecutor>> GetUncachedExecutor(
        const se::StreamExecutorConfig& config) override {
      return std::unique_ptr<se::StreamExecutor>(nullptr);
    }

    void RegisterTraceListener(
        std::unique_ptr<se::TraceListener> listener) override {}

    void UnregisterTraceListener(se::TraceListener* listener) override {}

   private:
    string name_;
  };

  TF_EXPECT_OK(se::MultiPlatformManager::RegisterPlatform(
      absl::make_unique<FakePlatform>()));
  xla::Compiler::RegisterCompilerFactory(kFakePlatformId, []() {
    return std::unique_ptr<xla::Compiler>(nullptr);
  });

  EXPECT_THAT(xla::PlatformUtil::GetDefaultPlatform().status().error_message(),
              HasSubstr("FakePlatform"));

  GraphDef graph_def = SumGraph();
  tf2xla::Config config = SumConfig();
  TF_ASSERT_OK_AND_ASSIGN(
      std::unique_ptr<XlaJitCompiledCpuFunction> jit,
      XlaJitCompiledCpuFunction::Compile(graph_def, config,
                                         xla::ExecutableBuildOptions()));
}

}  // namespace
}  // namespace tensorflow
<commit_msg>[XLA:AOT] Add test using resource variables from XlaJitCompiledCpuFunction<commit_after>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/compiler/tf2xla/xla_jit_compiled_cpu_function.h"

#include <memory>
#include <string>

#include "absl/memory/memory.h"
#include "tensorflow/compiler/tf2xla/tf2xla.pb.h"
#include "tensorflow/compiler/xla/client/local_client.h"
#include "tensorflow/compiler/xla/service/compiler.h"
#include "tensorflow/compiler/xla/service/platform_util.h"
#include "tensorflow/compiler/xla/shape_util.h"
#include "tensorflow/compiler/xla/status_macros.h"
#include "tensorflow/compiler/xla/statusor.h"
#include "tensorflow/compiler/xla/test.h"
#include "tensorflow/compiler/xla/xla_data.pb.h"
#include "tensorflow/core/framework/attr_value.pb.h"
#include "tensorflow/core/framework/attr_value_util.h"
#include "tensorflow/core/framework/graph.pb.h"
#include "tensorflow/core/framework/node_def.pb.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/stream_executor/multi_platform_manager.h"
#include "tensorflow/stream_executor/platform.h"

namespace tensorflow {
namespace {

using ::testing::HasSubstr;

PLATFORM_DEFINE_ID(kFakePlatformId);

AttrValue TypeAttrValue(DataType type) {
  AttrValue attr_value;
  SetAttrValue(type, &attr_value);
  return attr_value;
}

GraphDef SumGraph() {
  GraphDef graph_def;
  NodeDef* x = graph_def.add_node();
  x->set_name("x");
  x->set_op("Placeholder");
  (*x->mutable_attr())["dtype"] = TypeAttrValue(DT_INT32);
  NodeDef* y = graph_def.add_node();
  y->set_name("y");
  y->set_op("Placeholder");
  (*y->mutable_attr())["dtype"] = TypeAttrValue(DT_INT32);
  NodeDef* sum = graph_def.add_node();
  sum->set_name("sum");
  sum->set_op("Add");
  sum->add_input("x");
  sum->add_input("y");
  (*sum->mutable_attr())["T"] = TypeAttrValue(DT_INT32);
  return graph_def;
}

tf2xla::Config SumConfig() {
  tf2xla::Config config;
  tf2xla::Feed* x = config.add_feed();
  x->mutable_id()->set_node_name("x");
  x->set_name("x_name");
  tf2xla::Feed* y = config.add_feed();
  y->mutable_id()->set_node_name("y");
  y->set_name("y_name");
  tf2xla::Fetch* sum = config.add_fetch();
  sum->mutable_id()->set_node_name("sum");
  sum->set_name("sum_name");
  return config;
}

GraphDef SumGraphVariable() {
  constexpr char text_proto[] = R"pb(
    node {
      name: "x"
      op: "VarHandleOp"
      attr {
        key: "dtype"
        value { type: DT_INT32 }
      }
      attr {
        key: "shared_name"
        value { s: "myvar" }
      }
      attr {
        key: "shape"
        value { shape { dim { size: 1 } } }
      }
    }
    node {
      name: "read"
      op: "ReadVariableOp"
      input: "x"
      attr {
        key: "dtype"
        value { type: DT_INT32 }
      }
    }
    node {
      name: "y"
      op: "Placeholder"
      attr {
        key: "dtype"
        value { type: DT_INT32 }
      }
    }
    node {
      name: "sum"
      op: "Add"
      input: "read"
      input: "y"
      attr {
        key: "T"
        value { type: DT_INT32 }
      }
    }
    node {
      name: "assign"
      op: "AssignVariableOp"
      input: "x"
      input: "sum"
      attr {
        key: "dtype"
        value { type: DT_INT32 }
      }
    }
    # We use this identity op to make sure assign doesn't get pruned away.
    node {
      name: "out"
      op: "Identity"
      input: "y"
      input: "^assign"
      attr {
        key: "T"
        value { type: DT_INT32 }
      }
    })pb";
  GraphDef graph;
  CHECK(protobuf::TextFormat::ParseFromString(text_proto, &graph));
  return graph;
}

tf2xla::Config SumConfigVariable() {
  constexpr char text_proto[] = R"pb(feed { id { node_name: "y" } }
                                     variable {
                                       node_name: "myvar"
                                       shape { dim { size: 1 } }
                                       type: DT_INT32
                                     }
                                     fetch { id { node_name: "out" } })pb";
  tf2xla::Config config;
  CHECK(protobuf::TextFormat::ParseFromString(text_proto, &config));
  return config;
}

TEST(XlaJitCompiledCpuFunction, Sum) {
  GraphDef graph_def = SumGraph();
  tf2xla::Config config = SumConfig();

  TF_ASSERT_OK_AND_ASSIGN(
      std::unique_ptr<XlaJitCompiledCpuFunction> jit,
      XlaJitCompiledCpuFunction::Compile(graph_def, config,
                                         xla::ExecutableBuildOptions()));
  XlaCompiledCpuFunction function(jit->StaticData());

  // Run the function and check results.
  *static_cast<int32*>(function.arg_data(0)) = 10;
  *static_cast<int32*>(function.arg_data(1)) = 32;
  EXPECT_TRUE(function.Run());
  EXPECT_EQ(function.error_msg(), "");
  EXPECT_EQ(*static_cast<int32*>(function.result_data(0)), 42);

  // Run the function again.
  *static_cast<int32*>(function.arg_data(0)) = 100;
  *static_cast<int32*>(function.arg_data(1)) = 320;
  EXPECT_TRUE(function.Run());
  EXPECT_EQ(function.error_msg(), "");
  EXPECT_EQ(*static_cast<int32*>(function.result_data(0)), 420);

  // Check name to index lookups.
  EXPECT_TRUE(function.HasNameIndices());

  EXPECT_EQ(function.LookupArgIndex("x_name"), 0);
  EXPECT_EQ(function.LookupArgIndex("y_name"), 1);
  EXPECT_EQ(function.LookupArgIndex(""), -1);
  EXPECT_EQ(function.LookupArgIndex("x"), -1);
  EXPECT_EQ(function.LookupArgIndex("y"), -1);
  EXPECT_EQ(function.LookupArgIndex("sum"), -1);
  EXPECT_EQ(function.LookupArgIndex("sum_name"), -1);

  EXPECT_EQ(function.LookupResultIndex("sum_name"), 0);
  EXPECT_EQ(function.LookupResultIndex(""), -1);
  EXPECT_EQ(function.LookupResultIndex("x"), -1);
  EXPECT_EQ(function.LookupResultIndex("y"), -1);
  EXPECT_EQ(function.LookupResultIndex("sum"), -1);
  EXPECT_EQ(function.LookupResultIndex("x_name"), -1);
  EXPECT_EQ(function.LookupResultIndex("y_name"), -1);

  // Check program shape.
  using xla::ShapeUtil;
  const xla::Shape s32 = ShapeUtil::MakeShape(xla::S32, {});
  ASSERT_TRUE(function.ProgramShape() != nullptr);
  const xla::ProgramShape program_shape(*function.ProgramShape());
  ASSERT_EQ(program_shape.parameters_size(), 2);
  EXPECT_TRUE(ShapeUtil::Compatible(program_shape.parameters(0), s32));
  EXPECT_TRUE(ShapeUtil::Compatible(program_shape.parameters(1), s32));

  const xla::Shape& result = program_shape.result();
  ASSERT_EQ(result.element_type(), xla::TUPLE);
  ASSERT_EQ(ShapeUtil::TupleElementCount(result), 1);
  const xla::Shape& result0 = ShapeUtil::GetTupleElementShape(result, 0);
  EXPECT_TRUE(ShapeUtil::Compatible(result0, s32));
}

TEST(XlaJitCompiledCpuFunction, SumVariable) {
  GraphDef graph_def = SumGraphVariable();
  tf2xla::Config config = SumConfigVariable();

  TF_ASSERT_OK_AND_ASSIGN(
      std::unique_ptr<XlaJitCompiledCpuFunction> jit,
      XlaJitCompiledCpuFunction::Compile(graph_def, config,
                                         xla::ExecutableBuildOptions()));
  XlaCompiledCpuFunction function(jit->StaticData());

  // Run the function and check results.
  *static_cast<int32*>(function.arg_data(0)) = 10;
  *static_cast<int32*>(function.arg_data(1)) = 32;
  EXPECT_TRUE(function.Run());
  EXPECT_EQ(function.error_msg(), "");
  EXPECT_EQ(*static_cast<int32*>(function.result_data(0)), 10);
  EXPECT_EQ(*static_cast<int32*>(function.result_data(1)), 42);

  // Run the function again.
  *static_cast<int32*>(function.arg_data(0)) = 100;
  *static_cast<int32*>(function.arg_data(1)) = 320;
  EXPECT_TRUE(function.Run());
  EXPECT_EQ(function.error_msg(), "");
  EXPECT_EQ(*static_cast<int32*>(function.result_data(0)), 100);
  EXPECT_EQ(*static_cast<int32*>(function.result_data(1)), 420);

  // Check program shape.
  using xla::ShapeUtil;
  const xla::Shape s32 = ShapeUtil::MakeShape(xla::S32, {});
  const xla::Shape s32_1 = ShapeUtil::MakeShape(xla::S32, {1});
  ASSERT_TRUE(function.ProgramShape() != nullptr);
  const xla::ProgramShape program_shape(*function.ProgramShape());
  ASSERT_EQ(program_shape.parameters_size(), 2);
  EXPECT_TRUE(ShapeUtil::Compatible(program_shape.parameters(0), s32));
  EXPECT_TRUE(ShapeUtil::Compatible(program_shape.parameters(1), s32_1));

  const xla::Shape& result = program_shape.result();
  ASSERT_EQ(result.element_type(), xla::TUPLE);
  ASSERT_EQ(ShapeUtil::TupleElementCount(result), 2);
  const xla::Shape& result0 = ShapeUtil::GetTupleElementShape(result, 0);
  EXPECT_TRUE(ShapeUtil::Compatible(result0, s32));
}

// Test when a graph compilation terminates early, resources are properly
// reclaimed.
TEST(XlaJitCompiledCpuFunction, SumWithJunkAttr) {
  GraphDef graph_def = SumGraph();

  (*graph_def.mutable_node(2)->mutable_attr())["junk"] =
      TypeAttrValue(DT_INT32);

  tf2xla::Config config = SumConfig();
  EXPECT_FALSE(XlaJitCompiledCpuFunction::Compile(graph_def, config,
                                                  xla::ExecutableBuildOptions())
                   .ok());
}

TEST(XlaJitCompiledCpuFunction, CanCompileWithAdditionalPlatform) {
  class FakePlatform : public se::Platform {
   public:
    FakePlatform() : name_("FakePlatform") {}
    ~FakePlatform() override {}

    se::Platform::Id id() const override { return kFakePlatformId; }

    int VisibleDeviceCount() const override { return 0; }

    const string& Name() const override { return name_; }

    se::port::StatusOr<std::unique_ptr<se::DeviceDescription>>
    DescriptionForDevice(int ordinal) const override {
      return std::unique_ptr<se::DeviceDescription>(nullptr);
    }

    se::port::StatusOr<se::StreamExecutor*> ExecutorForDevice(
        int ordinal) override {
      return nullptr;
    }

    se::port::StatusOr<se::StreamExecutor*> ExecutorForDeviceWithPluginConfig(
        int ordinal, const se::PluginConfig& config) override {
      return nullptr;
    }

    se::port::StatusOr<se::StreamExecutor*> GetExecutor(
        const se::StreamExecutorConfig& config) override {
      return nullptr;
    }

    se::port::StatusOr<std::unique_ptr<se::StreamExecutor>> GetUncachedExecutor(
        const se::StreamExecutorConfig& config) override {
      return std::unique_ptr<se::StreamExecutor>(nullptr);
    }

    void RegisterTraceListener(
        std::unique_ptr<se::TraceListener> listener) override {}

    void UnregisterTraceListener(se::TraceListener* listener) override {}

   private:
    string name_;
  };

  TF_EXPECT_OK(se::MultiPlatformManager::RegisterPlatform(
      absl::make_unique<FakePlatform>()));
  xla::Compiler::RegisterCompilerFactory(kFakePlatformId, []() {
    return std::unique_ptr<xla::Compiler>(nullptr);
  });

  EXPECT_THAT(xla::PlatformUtil::GetDefaultPlatform().status().error_message(),
              HasSubstr("FakePlatform"));

  GraphDef graph_def = SumGraph();
  tf2xla::Config config = SumConfig();
  TF_ASSERT_OK_AND_ASSIGN(
      std::unique_ptr<XlaJitCompiledCpuFunction> jit,
      XlaJitCompiledCpuFunction::Compile(graph_def, config,
                                         xla::ExecutableBuildOptions()));
}

}  // namespace
}  // namespace tensorflow
<|endoftext|>


<commit_before>/**
 * @file configuration.cpp
 *
 * @date Nov 26, 2012
 * @author partio
 */

#include "configuration.h"
#include "logger_factory.h"
#include "plugin_factory.h"

#define HIMAN_AUXILIARY_INCLUDE

#include "pcuda.h"

#undef HIMAN_AUXILIARY_INCLUDE

using namespace himan;

configuration::configuration() : itsSourceProducerIterator(new producer_iter())
{

	Init();
	itsLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog("configuration"));

}

configuration::configuration(const configuration& other)
{

	itsOutputFileType = other.itsOutputFileType;
	itsConfigurationFile = other.itsConfigurationFile;
	itsAuxiliaryFiles = other.itsAuxiliaryFiles;
	itsOriginTime = other.itsOriginTime;

	itsFileWriteOption = other.itsFileWriteOption;
	itsReadDataFromDatabase = other.itsReadDataFromDatabase;

	itsFileWaitTimeout = other.itsFileWaitTimeout;
	itsUseCuda = other.itsUseCuda;
	itsUseCudaForPacking = other.itsUseCudaForPacking;
	itsUseCache = other.itsUseCache;

	itsLeadingDimension = other.itsLeadingDimension;
	itsThreadCount = other.itsThreadCount;

	itsTargetGeomName = other.itsTargetGeomName;
	itsSourceGeomName = other.itsSourceGeomName;

	itsTargetProducer = other.itsTargetProducer;
	//itsSourceProducers = other.itsSourceProducers;

	itsStatisticsLabel = other.itsStatisticsLabel;

	itsSourceProducerIterator = std::unique_ptr<producer_iter> (new producer_iter(*other.itsSourceProducerIterator));
	itsSourceProducerIterator->Set(other.itsSourceProducerIterator->Index());

	itsLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog("configuration"));
}

std::ostream& configuration::Write(std::ostream& file) const
{

	file << "<" << ClassName() << " " << Version() << ">" << std::endl;

   // file << "__itsSourceProducer__ " << itsSourceProducer << std::endl;
	file << itsTargetProducer;

	file << "__itsOutputFileType__ " << itsOutputFileType << std::endl;
	file << "__itsFileWriteOption__ " << itsFileWriteOption << std::endl;
	file << "__itsUseCuda__ " << itsUseCuda << std::endl;
	file << "__itsFileWaitTimeout__ " << itsFileWaitTimeout << std::endl;
	file << "__itsReadDataFromDatabase__ " << itsReadDataFromDatabase << std::endl;
	file << "__itsLeadingDimension__ " << itsLeadingDimension << std::endl;

	file << "__itsThreadCount__ " << itsThreadCount << std::endl;

	file << "__itsTargetGeomName__ " << itsTargetGeomName << std::endl;
	file << "__itsSourceGeomName__ " << itsSourceGeomName << std::endl;

	file << "__itsStatisticsLabel__ " << itsStatisticsLabel << std::endl;

	file << "__itsConfigurationFile__ " << itsConfigurationFile << std::endl;

	file << "__itsUseCudaForPacking__ " << itsUseCudaForPacking << std::endl;

	file << "__itsUseCache__ " << itsUseCache << std::endl;

	for (size_t i = 0; i < itsAuxiliaryFiles.size(); i++)
	{
		file << "__itsAuxiliaryFiles__ " << i << " " << itsAuxiliaryFiles[i] << std::endl;
	}
	return file;
}

std::vector<std::string> configuration::AuxiliaryFiles() const
{
	return itsAuxiliaryFiles;
}

void configuration::AuxiliaryFiles(const std::vector<std::string>& theAuxiliaryFiles)
{
	itsAuxiliaryFiles = theAuxiliaryFiles;
}

void configuration::Init()
{
	itsOutputFileType = kQueryData;
	itsFileWriteOption = kSingleFile;
	itsReadDataFromDatabase = true;
	itsUseCuda = true;
	itsFileWaitTimeout = 0;
	itsLeadingDimension = kTimeDimension;
	itsThreadCount = -1;
	itsTargetGeomName = "";
	itsSourceGeomName = "";
	itsConfigurationFile = "";
	itsUseCudaForPacking = true;
	itsUseCache = true;
}

HPFileType configuration::OutputFileType() const
{
	return itsOutputFileType;
}

void configuration::OutputFileType(HPFileType theOutputFileType)
{
	itsOutputFileType = theOutputFileType;
}

HPFileWriteOption configuration::FileWriteOption() const
{
	return itsFileWriteOption;
}

void configuration::FileWriteOption(HPFileWriteOption theFileWriteOption)
{
	itsFileWriteOption = theFileWriteOption;
}

bool configuration::ReadDataFromDatabase() const
{
	return itsReadDataFromDatabase;
}

void configuration::ReadDataFromDatabase(bool theReadDataFromDatabase)
{
	itsReadDataFromDatabase = theReadDataFromDatabase;
}

unsigned short configuration::FileWaitTimeout() const
{
	return itsFileWaitTimeout;
}

void configuration::FileWaitTimeout(unsigned short theFileWaitTimeout)
{
	itsFileWaitTimeout = theFileWaitTimeout;
}

bool configuration::UseCuda() const
{
	return itsUseCuda && HaveCuda();
}

void configuration::UseCuda(bool theUseCuda)
{
	itsUseCuda = theUseCuda;
}

HPDimensionType configuration::LeadingDimension() const
{
	return itsLeadingDimension;
}

short configuration::ThreadCount() const
{
	return itsThreadCount;
}

void configuration::ThreadCount(short theThreadCount)
{
	itsThreadCount = theThreadCount;
}

std::string configuration::ConfigurationFile() const
{
	return itsConfigurationFile;
};

void configuration::ConfigurationFile(const std::string& theConfigurationFile)
{
	itsConfigurationFile = theConfigurationFile;
}

void configuration::SourceProducers(const std::vector<producer> theSourceProducers)
{
	itsSourceProducerIterator = std::unique_ptr<producer_iter> (new producer_iter(theSourceProducers));
}

bool configuration::SourceProducer(const producer& theSourceProducer)
{
	return itsSourceProducerIterator->Set(theSourceProducer);
}

bool configuration::NextSourceProducer() const
{
	return itsSourceProducerIterator->Next();
}

bool configuration::FirstSourceProducer() const
{
	return itsSourceProducerIterator->First();
}

producer configuration::SourceProducer() const
{
	return itsSourceProducerIterator->At();
}

producer configuration::TargetProducer() const
{
	return itsTargetProducer;
}

void configuration::StatisticsLabel(const std::string& theStatisticsLabel)
{
	itsStatisticsLabel = theStatisticsLabel;
}

std::string configuration::StatisticsLabel() const
{
	return itsStatisticsLabel;
}

bool configuration::UseCudaForPacking() const
{
	return itsUseCudaForPacking;
}

void configuration::UseCudaForPacking(bool theUseCudaForPacking)
{
	itsUseCudaForPacking = theUseCudaForPacking;
}

bool configuration::UseCache() const
{
	return itsUseCache;
}

void configuration::UseCache(bool theUseCache)
{
	itsUseCache = theUseCache;
}

std::string configuration::SourceGeomName() const
{
	return itsSourceGeomName;
}

void configuration::StoreCudaDeviceCount()
{
	std::shared_ptr<plugin::pcuda> p = std::dynamic_pointer_cast<plugin::pcuda> (plugin_factory::Instance()->Plugin("pcuda"));

	itsCudaDeviceCount = static_cast<short> (p->DeviceCount());
}

bool configuration::HaveCuda() const
{
	return (itsCudaDeviceCount > 0);
}

short configuration::CudaDeviceCount() const
{
	return itsCudaDeviceCount;
}
std::string configuration::TargetProjection() const
{
	if (itsTargetGeomName == "RCR068")
		return "11";
	if (itsTargetGeomName == "MTHIPS25")
		return "13";
	return "0";
}<commit_msg>cudaDeviceCount forgotten from copy constructor; re-add grib as default output parameter type<commit_after>/**
 * @file configuration.cpp
 *
 * @date Nov 26, 2012
 * @author partio
 */

#include "configuration.h"
#include "logger_factory.h"
#include "plugin_factory.h"

#define HIMAN_AUXILIARY_INCLUDE

#include "pcuda.h"

#undef HIMAN_AUXILIARY_INCLUDE

using namespace himan;

configuration::configuration() : itsSourceProducerIterator(new producer_iter())
{

	Init();
	itsLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog("configuration"));

}

configuration::configuration(const configuration& other)
{

	itsOutputFileType = other.itsOutputFileType;
	itsConfigurationFile = other.itsConfigurationFile;
	itsAuxiliaryFiles = other.itsAuxiliaryFiles;
	itsOriginTime = other.itsOriginTime;

	itsFileWriteOption = other.itsFileWriteOption;
	itsReadDataFromDatabase = other.itsReadDataFromDatabase;

	itsFileWaitTimeout = other.itsFileWaitTimeout;
	itsUseCuda = other.itsUseCuda;
	itsUseCudaForPacking = other.itsUseCudaForPacking;
	itsCudaDeviceCount = other.itsCudaDeviceCount;

	itsUseCache = other.itsUseCache;

	itsLeadingDimension = other.itsLeadingDimension;
	itsThreadCount = other.itsThreadCount;

	itsTargetGeomName = other.itsTargetGeomName;
	itsSourceGeomName = other.itsSourceGeomName;

	itsTargetProducer = other.itsTargetProducer;
	//itsSourceProducers = other.itsSourceProducers;

	itsStatisticsLabel = other.itsStatisticsLabel;

	itsSourceProducerIterator = std::unique_ptr<producer_iter> (new producer_iter(*other.itsSourceProducerIterator));
	itsSourceProducerIterator->Set(other.itsSourceProducerIterator->Index());

	itsLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog("configuration"));
}

std::ostream& configuration::Write(std::ostream& file) const
{

	file << "<" << ClassName() << " " << Version() << ">" << std::endl;

   // file << "__itsSourceProducer__ " << itsSourceProducer << std::endl;
	file << itsTargetProducer;

	file << "__itsOutputFileType__ " << itsOutputFileType << std::endl;
	file << "__itsFileWriteOption__ " << itsFileWriteOption << std::endl;
	file << "__itsUseCuda__ " << itsUseCuda << std::endl;
	file << "__itsFileWaitTimeout__ " << itsFileWaitTimeout << std::endl;
	file << "__itsReadDataFromDatabase__ " << itsReadDataFromDatabase << std::endl;
	file << "__itsLeadingDimension__ " << itsLeadingDimension << std::endl;

	file << "__itsThreadCount__ " << itsThreadCount << std::endl;

	file << "__itsTargetGeomName__ " << itsTargetGeomName << std::endl;
	file << "__itsSourceGeomName__ " << itsSourceGeomName << std::endl;

	file << "__itsStatisticsLabel__ " << itsStatisticsLabel << std::endl;

	file << "__itsConfigurationFile__ " << itsConfigurationFile << std::endl;

	file << "__itsUseCudaForPacking__ " << itsUseCudaForPacking << std::endl;

	file << "__itsUseCache__ " << itsUseCache << std::endl;

	for (size_t i = 0; i < itsAuxiliaryFiles.size(); i++)
	{
		file << "__itsAuxiliaryFiles__ " << i << " " << itsAuxiliaryFiles[i] << std::endl;
	}
	return file;
}

std::vector<std::string> configuration::AuxiliaryFiles() const
{
	return itsAuxiliaryFiles;
}

void configuration::AuxiliaryFiles(const std::vector<std::string>& theAuxiliaryFiles)
{
	itsAuxiliaryFiles = theAuxiliaryFiles;
}

void configuration::Init()
{
	itsOutputFileType = kGRIB;
	itsFileWriteOption = kSingleFile;
	itsReadDataFromDatabase = true;
	itsUseCuda = true;
	itsFileWaitTimeout = 0;
	itsLeadingDimension = kTimeDimension;
	itsThreadCount = -1;
	itsTargetGeomName = "";
	itsSourceGeomName = "";
	itsConfigurationFile = "";
	itsUseCudaForPacking = true;
	itsUseCache = true;
}

HPFileType configuration::OutputFileType() const
{
	return itsOutputFileType;
}

void configuration::OutputFileType(HPFileType theOutputFileType)
{
	itsOutputFileType = theOutputFileType;
}

HPFileWriteOption configuration::FileWriteOption() const
{
	return itsFileWriteOption;
}

void configuration::FileWriteOption(HPFileWriteOption theFileWriteOption)
{
	itsFileWriteOption = theFileWriteOption;
}

bool configuration::ReadDataFromDatabase() const
{
	return itsReadDataFromDatabase;
}

void configuration::ReadDataFromDatabase(bool theReadDataFromDatabase)
{
	itsReadDataFromDatabase = theReadDataFromDatabase;
}

unsigned short configuration::FileWaitTimeout() const
{
	return itsFileWaitTimeout;
}

void configuration::FileWaitTimeout(unsigned short theFileWaitTimeout)
{
	itsFileWaitTimeout = theFileWaitTimeout;
}

bool configuration::UseCuda() const
{
	return itsUseCuda && HaveCuda();
}

void configuration::UseCuda(bool theUseCuda)
{
	itsUseCuda = theUseCuda;
}

HPDimensionType configuration::LeadingDimension() const
{
	return itsLeadingDimension;
}

short configuration::ThreadCount() const
{
	return itsThreadCount;
}

void configuration::ThreadCount(short theThreadCount)
{
	itsThreadCount = theThreadCount;
}

std::string configuration::ConfigurationFile() const
{
	return itsConfigurationFile;
};

void configuration::ConfigurationFile(const std::string& theConfigurationFile)
{
	itsConfigurationFile = theConfigurationFile;
}

void configuration::SourceProducers(const std::vector<producer> theSourceProducers)
{
	itsSourceProducerIterator = std::unique_ptr<producer_iter> (new producer_iter(theSourceProducers));
}

bool configuration::SourceProducer(const producer& theSourceProducer)
{
	return itsSourceProducerIterator->Set(theSourceProducer);
}

bool configuration::NextSourceProducer() const
{
	return itsSourceProducerIterator->Next();
}

bool configuration::FirstSourceProducer() const
{
	return itsSourceProducerIterator->First();
}

producer configuration::SourceProducer() const
{
	return itsSourceProducerIterator->At();
}

producer configuration::TargetProducer() const
{
	return itsTargetProducer;
}

void configuration::StatisticsLabel(const std::string& theStatisticsLabel)
{
	itsStatisticsLabel = theStatisticsLabel;
}

std::string configuration::StatisticsLabel() const
{
	return itsStatisticsLabel;
}

bool configuration::UseCudaForPacking() const
{
	return itsUseCudaForPacking;
}

void configuration::UseCudaForPacking(bool theUseCudaForPacking)
{
	itsUseCudaForPacking = theUseCudaForPacking;
}

bool configuration::UseCache() const
{
	return itsUseCache;
}

void configuration::UseCache(bool theUseCache)
{
	itsUseCache = theUseCache;
}

std::string configuration::SourceGeomName() const
{
	return itsSourceGeomName;
}

void configuration::StoreCudaDeviceCount()
{
	std::shared_ptr<plugin::pcuda> p = std::dynamic_pointer_cast<plugin::pcuda> (plugin_factory::Instance()->Plugin("pcuda"));

	itsCudaDeviceCount = static_cast<short> (p->DeviceCount());
}

bool configuration::HaveCuda() const
{
	return (itsCudaDeviceCount > 0);
}

short configuration::CudaDeviceCount() const
{
	return itsCudaDeviceCount;
}
std::string configuration::TargetProjection() const
{
	if (itsTargetGeomName == "RCR068")
		return "11";
	if (itsTargetGeomName == "MTHIPS25")
		return "13";
	return "0";
}
<|endoftext|>


<commit_before>/* -*- coding: utf-8; mode: c++; tab-width: 3 -*-

Copyright 2013
Raffaello D. Di Napoli

This file is part of Application-Building Components (henceforth referred to as ABC).

ABC is free software: you can redistribute it and/or modify it under the terms of the GNU General
Public License as published by the Free Software Foundation, either version 3 of the License, or (at
your option) any later version.

ABC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
License for more details.

You should have received a copy of the GNU General Public License along with ABC. If not, see
<http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------------------------------*/

#ifndef ABC_TESTING_TEST_CASE_HXX
#define ABC_TESTING_TEST_CASE_HXX

#include <abc/testing/core.hxx>
#ifdef ABC_CXX_PRAGMA_ONCE
	#pragma once
#endif

#include <abc/testing/runner.hxx>

////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::testing::test_case

namespace abc {

namespace testing {

/** Base class for test cases.
*/
class ABCTESTINGAPI test_case {
public:

	/** Constructor.
	*/
	test_case();

	/** Destructor.
	*/
	virtual ~test_case();

	/** Initializes the object. Split into a method separated from the constructor so that derived
	classes don’t need to declare a constructor just to forward its arguments.

	prunner
		Pointer to the test runner.
	*/
	void init(runner * prunner);

	/** Executes the test case.
	*/
	virtual void run() = 0;

	/** Returns a short description for the test case.

	return
		Test case title.
	*/
	virtual istr title() = 0;

protected:

	/** Validates an assertion.

	bExpr
		Result of the assertion expression.
	pszExpr
		Assertion being tested.
	*/
	void assert(bool bExpr, istr const & sExpr);

protected:

	/** Runner executing this test. */
	runner * m_prunner;
};

} //namespace testing

} //namespace abc

/** Asserts that the specified expression does not throw.

expr
	Expression that should not throw.
*/
#define ABC_TESTING_ASSERT_DOES_NOT_THROW(expr) \
	do { \
		bool _bCaught(false); \
		try { \
			static_cast<void>(expr); \
		} catch (...) { \
			_bCaught = true; \
		} \
		this->assert(!_bCaught, SL(#expr)); \
	} while (false)

/** Asserts that the specified expressions evaluate to the same value.

expr1
	First expression.
expr2
	Second expression.
*/
#define ABC_TESTING_ASSERT_EQUAL(expr1, expr2) \
	this->assert(expr1 == expr2, SL(#expr1) SL(" == ") SL(#expr2))

/** Asserts that the specified expression evaluates to false.

expr
	Expression that should evaulate to false.
*/
#define ABC_TESTING_ASSERT_FALSE(expr) \
	/* Use static_cast() to make the compiler raise warnings in case expr is not of type bool. */ \
	this->assert(!static_cast<bool>(expr), SL(#expr) SL(" == false"))

/** Asserts that the first expression evaluates to at least the same value as the second expression.

expr1
	First expression.
expr2
	Second expression.
*/
#define ABC_TESTING_ASSERT_GREATER_EQUAL(expr1, expr2) \
	this->assert(expr1 >= expr2, SL(#expr1) SL(" >= ") SL(#expr2))

/** Asserts that the specified expressions don’t evaluate to the same value.

expr1
	First expression.
expr2
	Second expression.
*/
#define ABC_TESTING_ASSERT_NOT_EQUAL(expr1, expr2) \
	this->assert(expr1 != expr2, SL(#expr1) SL(" != ") SL(#expr2))

/** Asserts that the specified expression throws an exception of the specified type.

type
	Exception class that should be caught.
expr
	Expression that should throw.
*/
#define ABC_TESTING_ASSERT_THROWS(type, expr) \
	do { \
		bool _bCaught(false); \
		try { \
			static_cast<void>(expr); \
		} catch (type const &) { \
			_bCaught = true; \
		} \
		this->assert(_bCaught, SL(#expr)); \
	} while (false)

/** Asserts that the specified expression evaluates to true.

expr
	Expression that should evaulate to true.
*/
#define ABC_TESTING_ASSERT_TRUE(expr) \
	this->assert(expr, SL(#expr) SL(" == true"))

////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::testing::test_case_factory_impl

namespace abc {

namespace testing {

/** Maintains a list of abc::testing::test_case-derived classes that can be used by an
abc::testing::runner instance to instantiate and execute each test case.
*/
class ABCTESTINGAPI test_case_factory_impl {
public:

	/** Factory function, returning an abc::testing::test_case instance. */
	typedef std::unique_ptr<test_case> (* factory_fn)(runner * prunner);
	/** Linked list item. */
	struct factory_list_item {
		factory_list_item * pfliNext;
		factory_fn pfnFactory;
	};

public:

	/** Constructor.

	pfli
		Pointer to the derived class’s factory list item.
	*/
	test_case_factory_impl(factory_list_item * pfli);

	/** Returns a pointer to the head of the list of factory functions, which the caller can then use
	to walk the entire list (ending when an item’s next pointer is NULL).

	return
		Pointer to the head of the list.
	*/
	static factory_list_item * get_factory_list_head() {
		return sm_pfliHead;
	}

private:

	/** Pointer to the head of the list of factory functions. */
	static factory_list_item * sm_pfliHead;
	/** Pointer to the “next” pointer of the tail of the list of factory functions. */
	static factory_list_item ** sm_ppfliTailNext;
};

} //namespace testing

} //namespace abc

////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::testing::test_case_factory

namespace abc {

namespace testing {

/** Template version of abc::testing::test_case_factory_impl, able to instantiate classes derived
from abc::testing::test_case.
*/
template <class T>
class test_case_factory :
	public test_case_factory_impl {
public:

	/** Constructor.
	*/
	test_case_factory() :
		test_case_factory_impl(&sm_fli) {
	}

	/** Class factory for T.

	prunner
		Runner to provide to the test case.
	*/
	static std::unique_ptr<test_case> factory(runner * prunner) {
		std::unique_ptr<T> pt(new T());
		pt->init(prunner);
		return std::move(pt);
	}

private:

	/** Entry in the list of factory functions for this class. */
	static factory_list_item sm_fli;
};

} //namespace testing

} //namespace abc

/** Registers an abc::testing::test_case-derived class for execution by an abc::testing::runner
instance.

cls
	Test case class.
*/
#define ABC_TESTING_REGISTER_TEST_CASE(cls) \
	namespace abc { \
	namespace testing { \
	\
	static test_case_factory<cls> ABC_CPP_APPEND_UID(g__test_case_factory_); \
	template <> \
	/*static*/ test_case_factory_impl::factory_list_item test_case_factory<cls>::sm_fli = { \
		NULL, \
		test_case_factory<cls>::factory \
	}; \
	\
	} /*namespace testing*/ \
	} /*namespace abc*/

////////////////////////////////////////////////////////////////////////////////////////////////////

#endif //ifndef ABC_TESTING_TEST_CASE_HXX

<commit_msg>Add more ABC_TESTING_ASSERT_*() macros<commit_after>/* -*- coding: utf-8; mode: c++; tab-width: 3 -*-

Copyright 2013
Raffaello D. Di Napoli

This file is part of Application-Building Components (henceforth referred to as ABC).

ABC is free software: you can redistribute it and/or modify it under the terms of the GNU General
Public License as published by the Free Software Foundation, either version 3 of the License, or (at
your option) any later version.

ABC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
License for more details.

You should have received a copy of the GNU General Public License along with ABC. If not, see
<http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------------------------------*/

#ifndef ABC_TESTING_TEST_CASE_HXX
#define ABC_TESTING_TEST_CASE_HXX

#include <abc/testing/core.hxx>
#ifdef ABC_CXX_PRAGMA_ONCE
	#pragma once
#endif

#include <abc/testing/runner.hxx>

////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::testing::test_case

namespace abc {

namespace testing {

/** Base class for test cases.
*/
class ABCTESTINGAPI test_case {
public:

	/** Constructor.
	*/
	test_case();

	/** Destructor.
	*/
	virtual ~test_case();

	/** Initializes the object. Split into a method separated from the constructor so that derived
	classes don’t need to declare a constructor just to forward its arguments.

	prunner
		Pointer to the test runner.
	*/
	void init(runner * prunner);

	/** Executes the test case.
	*/
	virtual void run() = 0;

	/** Returns a short description for the test case.

	return
		Test case title.
	*/
	virtual istr title() = 0;

protected:

	/** Validates an assertion.

	bExpr
		Result of the assertion expression.
	pszExpr
		Assertion being tested.
	*/
	void assert(bool bExpr, istr const & sExpr);

protected:

	/** Runner executing this test. */
	runner * m_prunner;
};

} //namespace testing

} //namespace abc

/** Asserts that the specified expression does not throw.

expr
	Expression that should not throw.
*/
#define ABC_TESTING_ASSERT_DOES_NOT_THROW(expr) \
	do { \
		bool _bCaught(false); \
		try { \
			static_cast<void>(expr); \
		} catch (...) { \
			_bCaught = true; \
		} \
		this->assert(!_bCaught, SL(#expr)); \
	} while (false)

/** Asserts that the specified expressions evaluate to the same value.

expr1
	First expression.
expr2
	Second expression.
*/
#define ABC_TESTING_ASSERT_EQUAL(expr1, expr2) \
	this->assert(expr1 == expr2, SL(#expr1) SL(" == ") SL(#expr2))

/** Asserts that the specified expression evaluates to false.

expr
	Expression that should evaulate to false.
*/
#define ABC_TESTING_ASSERT_FALSE(expr) \
	/* Use static_cast() to make the compiler raise warnings in case expr is not of type bool. */ \
	this->assert(!static_cast<bool>(expr), SL(#expr) SL(" == false"))

/** Asserts that the first expression evaluates to more than the second expression.

expr1
	First expression.
expr2
	Second expression.
*/
#define ABC_TESTING_ASSERT_GREATER(expr1, expr2) \
	this->assert(expr1 > expr2, SL(#expr1) SL(" > ") SL(#expr2))

/** Asserts that the first expression evaluates to at least the same value as the second expression.

expr1
	First expression.
expr2
	Second expression.
*/
#define ABC_TESTING_ASSERT_GREATER_EQUAL(expr1, expr2) \
	this->assert(expr1 >= expr2, SL(#expr1) SL(" >= ") SL(#expr2))

/** Asserts that the first expression evaluates to less than the second expression.

expr1
	First expression.
expr2
	Second expression.
*/
#define ABC_TESTING_ASSERT_LESS(expr1, expr2) \
	this->assert(expr1 < expr2, SL(#expr1) SL(" < ") SL(#expr2))

/** Asserts that the first expression evaluates to at most the same value as the second expression.

expr1
	First expression.
expr2
	Second expression.
*/
#define ABC_TESTING_ASSERT_LESS_EQUAL(expr1, expr2) \
	this->assert(expr1 <= expr2, SL(#expr1) SL(" <= ") SL(#expr2))

/** Asserts that the specified expressions don’t evaluate to the same value.

expr1
	First expression.
expr2
	Second expression.
*/
#define ABC_TESTING_ASSERT_NOT_EQUAL(expr1, expr2) \
	this->assert(expr1 != expr2, SL(#expr1) SL(" != ") SL(#expr2))

/** Asserts that the specified expression throws an exception of the specified type.

type
	Exception class that should be caught.
expr
	Expression that should throw.
*/
#define ABC_TESTING_ASSERT_THROWS(type, expr) \
	do { \
		bool _bCaught(false); \
		try { \
			static_cast<void>(expr); \
		} catch (type const &) { \
			_bCaught = true; \
		} \
		this->assert(_bCaught, SL(#expr)); \
	} while (false)

/** Asserts that the specified expression evaluates to true.

expr
	Expression that should evaulate to true.
*/
#define ABC_TESTING_ASSERT_TRUE(expr) \
	this->assert(expr, SL(#expr) SL(" == true"))

////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::testing::test_case_factory_impl

namespace abc {

namespace testing {

/** Maintains a list of abc::testing::test_case-derived classes that can be used by an
abc::testing::runner instance to instantiate and execute each test case.
*/
class ABCTESTINGAPI test_case_factory_impl {
public:

	/** Factory function, returning an abc::testing::test_case instance. */
	typedef std::unique_ptr<test_case> (* factory_fn)(runner * prunner);
	/** Linked list item. */
	struct factory_list_item {
		factory_list_item * pfliNext;
		factory_fn pfnFactory;
	};

public:

	/** Constructor.

	pfli
		Pointer to the derived class’s factory list item.
	*/
	test_case_factory_impl(factory_list_item * pfli);

	/** Returns a pointer to the head of the list of factory functions, which the caller can then use
	to walk the entire list (ending when an item’s next pointer is NULL).

	return
		Pointer to the head of the list.
	*/
	static factory_list_item * get_factory_list_head() {
		return sm_pfliHead;
	}

private:

	/** Pointer to the head of the list of factory functions. */
	static factory_list_item * sm_pfliHead;
	/** Pointer to the “next” pointer of the tail of the list of factory functions. */
	static factory_list_item ** sm_ppfliTailNext;
};

} //namespace testing

} //namespace abc

////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::testing::test_case_factory

namespace abc {

namespace testing {

/** Template version of abc::testing::test_case_factory_impl, able to instantiate classes derived
from abc::testing::test_case.
*/
template <class T>
class test_case_factory :
	public test_case_factory_impl {
public:

	/** Constructor.
	*/
	test_case_factory() :
		test_case_factory_impl(&sm_fli) {
	}

	/** Class factory for T.

	prunner
		Runner to provide to the test case.
	*/
	static std::unique_ptr<test_case> factory(runner * prunner) {
		std::unique_ptr<T> pt(new T());
		pt->init(prunner);
		return std::move(pt);
	}

private:

	/** Entry in the list of factory functions for this class. */
	static factory_list_item sm_fli;
};

} //namespace testing

} //namespace abc

/** Registers an abc::testing::test_case-derived class for execution by an abc::testing::runner
instance.

cls
	Test case class.
*/
#define ABC_TESTING_REGISTER_TEST_CASE(cls) \
	namespace abc { \
	namespace testing { \
	\
	static test_case_factory<cls> ABC_CPP_APPEND_UID(g__test_case_factory_); \
	template <> \
	/*static*/ test_case_factory_impl::factory_list_item test_case_factory<cls>::sm_fli = { \
		NULL, \
		test_case_factory<cls>::factory \
	}; \
	\
	} /*namespace testing*/ \
	} /*namespace abc*/

////////////////////////////////////////////////////////////////////////////////////////////////////

#endif //ifndef ABC_TESTING_TEST_CASE_HXX

<|endoftext|>


<commit_before>// Copyright 2012-2013 Samplecount S.L.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "Methcla/Audio/Synth.hpp"
#include "Methcla/Audio/SynthDef.hpp"

#include <iostream>
#include <memory>
#include <utility>

using namespace boost;
using namespace Methcla::Audio;
using namespace std;

SynthDef::SynthDef(const Methcla_SynthDef* synthDef)
    : m_descriptor(synthDef)
{
    // Validate descriptor fields (some are optional)
    if (m_descriptor->uri == nullptr || m_descriptor->uri[0] == '\0')
        throw std::invalid_argument("SynthDef: Missing URI");
    if (m_descriptor->construct == nullptr)
        throw std::invalid_argument("SynthDef: Missing `construct' function");
    if (m_descriptor->port_descriptor == nullptr)
        throw std::invalid_argument("SynthDef: Missing `port_descriptor' function");
    if (m_descriptor->connect == nullptr)
        throw std::invalid_argument("SynthDef: Missing `connect' function");
    if (m_descriptor->process == nullptr)
        throw std::invalid_argument("SynthDef: Missing `process' function");

    m_options = m_descriptor->options_size > 0 ? new char[m_descriptor->options_size] : nullptr;

#if DEBUG
    std::cerr << "SynthDef " << uri() << " loaded (" << m_descriptor << "):" << std::endl
              << "    instance size: " << instanceSize() << std::endl;
#endif
}

SynthDef::~SynthDef()
{
    delete [] static_cast<char*>(m_options);
}

const Methcla_SynthOptions* SynthDef::configure(OSCPP::Server::ArgStream options) const
{
    if (m_descriptor->configure) {
        auto state = options.state();
        m_descriptor->configure(
            std::get<0>(state).pos(), std::get<0>(state).consumable(),
            std::get<1>(state).pos(), std::get<1>(state).consumable(),
            m_options
        );
        return m_options;
    }
    return nullptr;
}

bool SynthDef::portDescriptor(const Methcla_SynthOptions* options, size_t index, Methcla_PortDescriptor* port) const
{
    return m_descriptor->port_descriptor(options, index, port);
}

void SynthDef::construct(const Methcla_World* world, const Methcla_SynthOptions* options, Synth* owner, Methcla_Synth* synth) const
{
    m_descriptor->construct(world, m_descriptor, options, static_cast<Reference*>(owner), synth);
}

void SynthDef::destroy(const Methcla_World* world, Methcla_Synth* synth) const
{
    if (m_descriptor->destroy) m_descriptor->destroy(world, synth);
}

PluginLibrary::PluginLibrary(const Methcla_Library* lib, std::shared_ptr<Methcla::Plugin::Library> plugin)
    : m_lib(lib)
    , m_plugin(plugin)
{
}

PluginLibrary::~PluginLibrary()
{
    methcla_library_destroy(m_lib);
}

void PluginManager::loadPlugins(const Methcla_Host* host, const std::list<Methcla_LibraryFunction>& funcs)
{
    for (auto f : funcs) {
        const Methcla_Library* lib = f(host, ".");
        if (lib != nullptr) {
            m_libs.push_back(std::make_shared<PluginLibrary>(lib));
        }
    }
}

void PluginManager::loadPlugins(const Methcla_Host* host, const std::string& directory)
{
    std::cout << "PluginManager::loadPlugins not yet implemented" << std::endl;
}
<commit_msg>Comment out unused parameters<commit_after>// Copyright 2012-2013 Samplecount S.L.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "Methcla/Audio/Synth.hpp"
#include "Methcla/Audio/SynthDef.hpp"

#include <iostream>
#include <memory>
#include <utility>

using namespace boost;
using namespace Methcla::Audio;
using namespace std;

SynthDef::SynthDef(const Methcla_SynthDef* synthDef)
    : m_descriptor(synthDef)
{
    // Validate descriptor fields (some are optional)
    if (m_descriptor->uri == nullptr || m_descriptor->uri[0] == '\0')
        throw std::invalid_argument("SynthDef: Missing URI");
    if (m_descriptor->construct == nullptr)
        throw std::invalid_argument("SynthDef: Missing `construct' function");
    if (m_descriptor->port_descriptor == nullptr)
        throw std::invalid_argument("SynthDef: Missing `port_descriptor' function");
    if (m_descriptor->connect == nullptr)
        throw std::invalid_argument("SynthDef: Missing `connect' function");
    if (m_descriptor->process == nullptr)
        throw std::invalid_argument("SynthDef: Missing `process' function");

    m_options = m_descriptor->options_size > 0 ? new char[m_descriptor->options_size] : nullptr;

#if DEBUG
    std::cerr << "SynthDef " << uri() << " loaded (" << m_descriptor << "):" << std::endl
              << "    instance size: " << instanceSize() << std::endl;
#endif
}

SynthDef::~SynthDef()
{
    delete [] static_cast<char*>(m_options);
}

const Methcla_SynthOptions* SynthDef::configure(OSCPP::Server::ArgStream options) const
{
    if (m_descriptor->configure) {
        auto state = options.state();
        m_descriptor->configure(
            std::get<0>(state).pos(), std::get<0>(state).consumable(),
            std::get<1>(state).pos(), std::get<1>(state).consumable(),
            m_options
        );
        return m_options;
    }
    return nullptr;
}

bool SynthDef::portDescriptor(const Methcla_SynthOptions* options, size_t index, Methcla_PortDescriptor* port) const
{
    return m_descriptor->port_descriptor(options, index, port);
}

void SynthDef::construct(const Methcla_World* world, const Methcla_SynthOptions* options, Synth* owner, Methcla_Synth* synth) const
{
    m_descriptor->construct(world, m_descriptor, options, static_cast<Reference*>(owner), synth);
}

void SynthDef::destroy(const Methcla_World* world, Methcla_Synth* synth) const
{
    if (m_descriptor->destroy) m_descriptor->destroy(world, synth);
}

PluginLibrary::PluginLibrary(const Methcla_Library* lib, std::shared_ptr<Methcla::Plugin::Library> plugin)
    : m_lib(lib)
    , m_plugin(plugin)
{
}

PluginLibrary::~PluginLibrary()
{
    methcla_library_destroy(m_lib);
}

void PluginManager::loadPlugins(const Methcla_Host* host, const std::list<Methcla_LibraryFunction>& funcs)
{
    for (auto f : funcs) {
        const Methcla_Library* lib = f(host, ".");
        if (lib != nullptr) {
            m_libs.push_back(std::make_shared<PluginLibrary>(lib));
        }
    }
}

void PluginManager::loadPlugins(const Methcla_Host* /*host*/, const std::string& /*directory*/)
{
    std::cout << "PluginManager::loadPlugins not yet implemented" << std::endl;
}
<|endoftext|>


<commit_before><commit_msg>Disables browser test on chromeos as chromeos defaults to restoring last session, which means my test doesn't test what I want it to. I could make the test exercise the paths I want on chromeos by changing what to do on startup, but it didn't seem worth it given the default.<commit_after><|endoftext|>


<commit_before>// Copyright 2012-2013 Samplecount S.L.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#if defined(__clang__)
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Wunused-private-field"
#endif

#include <catch.hpp>

#if defined(__clang__)
# pragma clang diagnostic pop
#endif

#include <methcla/engine.hpp>

TEST_CASE("methcla/engine/creation", "Test engine creation and tear down.")
{
    Methcla_Engine* engine = nullptr;
    Methcla_Error result;
    result = methcla_engine_new(nullptr, nullptr, nullptr, &engine);
    REQUIRE(result == kMethcla_NoError);
    REQUIRE(engine);
    result = methcla_engine_start(engine);
    REQUIRE(result == kMethcla_NoError);
    result = methcla_engine_stop(engine);
    REQUIRE(result == kMethcla_NoError);
    methcla_engine_free(engine);
}
<commit_msg>Factor out engine creation<commit_after>// Copyright 2012-2013 Samplecount S.L.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#if defined(__clang__)
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Wunused-private-field"
#endif

#include <catch.hpp>

#if defined(__clang__)
# pragma clang diagnostic pop
#endif

#include <methcla/engine.hpp>

static Methcla_Engine* makeEngine()
{
    Methcla_Engine* engine = nullptr;
    Methcla_Error result;
    result = methcla_engine_new(nullptr, nullptr, nullptr, &engine);
    REQUIRE(result == kMethcla_NoError);
    REQUIRE(engine);
    return engine;
}

TEST_CASE("methcla/engine/creation", "Test engine creation and tear down.")
{
    Methcla_Engine* engine = makeEngine();
    Methcla_Error result = methcla_engine_start(engine);
    REQUIRE(result == kMethcla_NoError);
    result = methcla_engine_stop(engine);
    REQUIRE(result == kMethcla_NoError);
    methcla_engine_free(engine);
}
<|endoftext|>


<commit_before>#pragma once

#include <syslog.h>

#include <vector>

#include "blackhole/forward.hpp"
#include "blackhole/sink.hpp"

namespace blackhole {
inline namespace v1 {
namespace sink {

class syslog_t : public sink_t {
    class inner_t;
    std::unique_ptr<inner_t> inner;

public:
    syslog_t();
    syslog_t(const syslog_t& other) = delete;
    syslog_t(syslog_t&& other);

    ~syslog_t();

    auto option() const noexcept -> int;
    auto facility() const noexcept -> int;
    auto identity() const noexcept -> const std::string&;

    auto priorities(std::vector<int> priorities) -> void;

    virtual auto emit(const record_t& record, const string_view& formatted) -> void;
};

}  // namespace sink

template<>
struct factory<sink::syslog_t> {
    static auto type() -> const char*;
    static auto from(const config::node_t& config) -> sink::syslog_t;
};

}  // namespace v1
}  // namespace blackhole
<commit_msg>fix(syslog): add missing include<commit_after>#pragma once

#include <syslog.h>

#include <memory>
#include <vector>

#include "blackhole/forward.hpp"
#include "blackhole/sink.hpp"

namespace blackhole {
inline namespace v1 {
namespace sink {

class syslog_t : public sink_t {
    class inner_t;
    std::unique_ptr<inner_t> inner;

public:
    syslog_t();
    syslog_t(const syslog_t& other) = delete;
    syslog_t(syslog_t&& other);

    ~syslog_t();

    auto option() const noexcept -> int;
    auto facility() const noexcept -> int;
    auto identity() const noexcept -> const std::string&;

    auto priorities(std::vector<int> priorities) -> void;

    virtual auto emit(const record_t& record, const string_view& formatted) -> void;
};

}  // namespace sink

template<>
struct factory<sink::syslog_t> {
    static auto type() -> const char*;
    static auto from(const config::node_t& config) -> sink::syslog_t;
};

}  // namespace v1
}  // namespace blackhole
<|endoftext|>