1// SPDX-License-Identifier: GPL-3.0-or-later
2
3#include "units/template.hpp"
4
5#include "global.hpp"
6#include "logging.hpp"
7#include "units/unit.hpp"
8
9static inline constexpr auto VectorAppender(std::vector<std::string> &target)
10{
11 return [&](const toml::array &array)
12 {
13 for (const auto &dep : array)
14 target.push_back(x: **dep.as_string());
15 };
16};
17
18static bool VerifyArguments(const std::vector<std::string> &params, const ArgumentMap &args)
19{
20 const auto &rhs = args;
21 const auto b1 = std::all_of(first: params.begin(), last: params.end(), pred: [&rhs](const auto &p) { return rhs.contains(p); });
22 const auto b2 = std::all_of(first: rhs.begin(), last: rhs.end(), pred: [&params](const auto &p) { return std::find(params.begin(), params.end(), p.first) != params.end(); });
23
24 if (!b1)
25 std::cerr << RED("Missing required arguments for unit instantiation.") << std::endl;
26
27 if (!b2)
28 Debug << RED("Extraneous arguments for unit instantiation.") << std::endl;
29
30 return b1 && b2;
31}
32
33Template::Template(const std::string &id, const toml::table &table, const ArgumentMap &predefined_args) : id(id), table(table), predefined_args(predefined_args)
34{
35 if (const auto template_params = table["template_params"]; template_params)
36 template_params.visit(visitor: VectorAppender(target&: parameters));
37 else
38 std::cerr << "template " << id << " missing template_params" << std::endl;
39}
40
41std::optional<std::pair<std::string, std::shared_ptr<IUnit>>> Template::Instantiate(const ArgumentMap &args) const
42{
43 ArgumentMap args_copy = predefined_args;
44 for (const auto &[key, value] : args)
45 args_copy[key] = value;
46
47 if (!VerifyArguments(params: parameters, args: args_copy))
48 return std::nullopt;
49
50 std::vector<std::string> templateArgs;
51 table["template_params"].as_array()->visit(visitor: VectorAppender(target&: templateArgs));
52
53 if (templateArgs.empty() || args_copy.empty() || !VerifyArguments(params: templateArgs, args: args_copy))
54 {
55 std::cerr << "template " << id << " has incorrect arguments" << std::endl;
56 return std::nullopt;
57 }
58
59 const auto new_unit_id = GetID(id, args); // don't involve predefined_args
60 return std::make_pair(x: new_unit_id, y: Unit::Instantiate(id: new_unit_id, template_: shared_from_this(), args: args_copy));
61}
62
63std::string Template::GetID(const std::string &id, const ArgumentMap &args)
64{
65 std::ostringstream ss;
66 ss << id.substr(pos: 0, n: id.find(svt: TEMPLATE_SUFFIX)) << ARGUMENTS_SEPARATOR;
67
68 for (auto it = args.begin(); it != args.end(); it++)
69 {
70 ss << it->first << "=" << it->second;
71 if (std::next(x: it) != args.end())
72 ss << ',';
73 }
74
75 return ss.str();
76}
77