Version: 1.0
base_ruleset.h
Go to the documentation of this file.
1 // Copyright (c) 2020, the GRAPHGEN contributors, as
2 // shown by the AUTHORS file. All rights reserved.
3 //
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file.
6 
7 #ifndef GRAPHGEN_BASE_RULESET_H_
8 #define GRAPHGEN_BASE_RULESET_H_
9 
10 #include <fstream>
11 #include <filesystem>
12 #include <string>
13 #include <utility>
14 
15 #include "yaml-cpp/yaml.h"
16 
17 #include "rule_set.h"
18 
19 
26 class BaseRuleSet {
27  std::filesystem::path p_;
28  bool force_generation_;
29  bool disable_generation_;
30  rule_set rs_;
31 
35  bool LoadRuleSet() {
36 
37  YAML::Node rs_node;
38  try {
39  rs_node = YAML::LoadFile(p_.string());
40  }
41  catch (...){
42  return false;
43  }
44 
45  rs_ = rule_set(rs_node);
46  return true;
47  }
48 
52  void SaveRuleSet() {
53  std::ofstream os(p_.string());
54  if (os) {
55  YAML::Node n = rs_.Serialize();
56  YAML::Emitter emitter(os);
57  emitter.SetSeqFormat(YAML::EMITTER_MANIP::Flow);
58  emitter << n;
59  }
60  }
61 
62 public:
63 
64  BaseRuleSet(bool force_generation = false) : force_generation_{ force_generation }, disable_generation_{ false }
65  {
66  p_ = conf.rstable_path_;
67  }
68 
69  BaseRuleSet(std::filesystem::path custom_path) : force_generation_{ false }, disable_generation_{ true }, p_{ custom_path }
70  {
71  }
72 
74  if (force_generation_ || !LoadRuleSet()) {
75  if (disable_generation_) {
76  auto msg = "Could not load rule set " + p_.string() + " from file (generation disabled).\n";
77  std::cerr << msg;
78  throw std::runtime_error((msg).c_str());
79  }
80 
81  rs_ = GenerateRuleSet();
82  SaveRuleSet();
83  }
84  return rs_;
85  }
86 
87  virtual rule_set GenerateRuleSet() = 0;
88 
89 };
90 
91 #endif //GRAPHGEN_BASE_RULESET_H_
Is the base class for the RuleSet from which every user-defined RuleSet should inherit.
Definition: base_ruleset.h:26
rule_set GetRuleSet()
Definition: base_ruleset.h:73
BaseRuleSet(std::filesystem::path custom_path)
Definition: base_ruleset.h:69
BaseRuleSet(bool force_generation=false)
Definition: base_ruleset.h:64
virtual rule_set GenerateRuleSet()=0
std::filesystem::path rstable_path_
Definition: config_data.h:64
YAML::Node Serialize() const
Definition: rule_set.h:169
ConfigData conf
Definition: utilities.cpp:9