]> granicus.if.org Git - icinga2/blob - lib/config/vmops.hpp
Merge pull request #6999 from Icinga/bugfix/compiler-warnings
[icinga2] / lib / config / vmops.hpp
1 /* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */
2
3 #ifndef VMOPS_H
4 #define VMOPS_H
5
6 #include "config/i2-config.hpp"
7 #include "config/expression.hpp"
8 #include "config/configitembuilder.hpp"
9 #include "config/applyrule.hpp"
10 #include "config/objectrule.hpp"
11 #include "base/debuginfo.hpp"
12 #include "base/array.hpp"
13 #include "base/dictionary.hpp"
14 #include "base/namespace.hpp"
15 #include "base/function.hpp"
16 #include "base/scriptglobal.hpp"
17 #include "base/exception.hpp"
18 #include "base/convert.hpp"
19 #include "base/objectlock.hpp"
20 #include <map>
21 #include <vector>
22
23 namespace icinga
24 {
25
26 class VMOps
27 {
28 public:
29         static inline bool FindVarImportRef(ScriptFrame& frame, const std::vector<std::shared_ptr<Expression> >& imports, const String& name, Value *result, const DebugInfo& debugInfo = DebugInfo())
30         {
31                 for (const auto& import : imports) {
32                         ExpressionResult res = import->Evaluate(frame);
33                         Object::Ptr obj = res.GetValue();
34                         if (obj->HasOwnField(name)) {
35                                 *result = obj;
36                                 return true;
37                         }
38                 }
39
40                 return false;
41         }
42
43         static inline bool FindVarImport(ScriptFrame& frame, const std::vector<std::shared_ptr<Expression> >& imports, const String& name, Value *result, const DebugInfo& debugInfo = DebugInfo())
44         {
45                 Value parent;
46
47                 if (FindVarImportRef(frame, imports, name, &parent, debugInfo)) {
48                         *result = GetField(parent, name, frame.Sandboxed, debugInfo);
49                         return true;
50                 }
51
52                 return false;
53         }
54
55         static inline Value ConstructorCall(const Type::Ptr& type, const std::vector<Value>& args, const DebugInfo& debugInfo = DebugInfo())
56         {
57                 if (type->GetName() == "String") {
58                         if (args.empty())
59                                 return "";
60                         else if (args.size() == 1)
61                                 return Convert::ToString(args[0]);
62                         else
63                                 BOOST_THROW_EXCEPTION(ScriptError("Too many arguments for constructor."));
64                 } else if (type->GetName() == "Number") {
65                         if (args.empty())
66                                 return 0;
67                         else if (args.size() == 1)
68                                 return Convert::ToDouble(args[0]);
69                         else
70                                 BOOST_THROW_EXCEPTION(ScriptError("Too many arguments for constructor."));
71                 } else if (type->GetName() == "Boolean") {
72                         if (args.empty())
73                                 return 0;
74                         else if (args.size() == 1)
75                                 return Convert::ToBool(args[0]);
76                         else
77                                 BOOST_THROW_EXCEPTION(ScriptError("Too many arguments for constructor."));
78                 } else if (args.size() == 1 && type->IsAssignableFrom(args[0].GetReflectionType()))
79                         return args[0];
80                 else
81                         return type->Instantiate(args);
82         }
83
84         static inline Value FunctionCall(ScriptFrame& frame, const Value& self, const Function::Ptr& func, const std::vector<Value>& arguments)
85         {
86                 if (!self.IsEmpty() || self.IsString())
87                         return func->InvokeThis(self, arguments);
88                 else
89                         return func->Invoke(arguments);
90
91         }
92
93         static inline Value NewFunction(ScriptFrame& frame, const String& name, const std::vector<String>& argNames,
94                 const std::map<String, std::unique_ptr<Expression> >& closedVars, const std::shared_ptr<Expression>& expression)
95         {
96                 auto evaluatedClosedVars = EvaluateClosedVars(frame, closedVars);
97
98                 auto wrapper = [argNames, evaluatedClosedVars, expression](const std::vector<Value>& arguments) -> Value {
99                         if (arguments.size() < argNames.size())
100                                 BOOST_THROW_EXCEPTION(std::invalid_argument("Too few arguments for function"));
101
102                         ScriptFrame *frame = ScriptFrame::GetCurrentFrame();
103
104                         frame->Locals = new Dictionary();
105
106                         if (evaluatedClosedVars)
107                                 evaluatedClosedVars->CopyTo(frame->Locals);
108
109                         for (std::vector<Value>::size_type i = 0; i < std::min(arguments.size(), argNames.size()); i++)
110                                 frame->Locals->Set(argNames[i], arguments[i]);
111
112                         return expression->Evaluate(*frame);
113                 };
114
115                 return new Function(name, wrapper, argNames);
116         }
117
118         static inline Value NewApply(ScriptFrame& frame, const String& type, const String& target, const String& name, const std::shared_ptr<Expression>& filter,
119                 const String& package, const String& fkvar, const String& fvvar, const std::shared_ptr<Expression>& fterm, const std::map<String, std::unique_ptr<Expression> >& closedVars,
120                 bool ignoreOnError, const std::shared_ptr<Expression>& expression, const DebugInfo& debugInfo = DebugInfo())
121         {
122                 ApplyRule::AddRule(type, target, name, expression, filter, package, fkvar,
123                         fvvar, fterm, ignoreOnError, debugInfo, EvaluateClosedVars(frame, closedVars));
124
125                 return Empty;
126         }
127
128         static inline Value NewObject(ScriptFrame& frame, bool abstract, const Type::Ptr& type, const String& name, const std::shared_ptr<Expression>& filter,
129                 const String& zone, const String& package, bool defaultTmpl, bool ignoreOnError, const std::map<String, std::unique_ptr<Expression> >& closedVars, const std::shared_ptr<Expression>& expression, const DebugInfo& debugInfo = DebugInfo())
130         {
131                 ConfigItemBuilder item{debugInfo};
132
133                 String checkName = name;
134
135                 if (!abstract) {
136                         auto *nc = dynamic_cast<NameComposer *>(type.get());
137
138                         if (nc)
139                                 checkName = nc->MakeName(name, nullptr);
140                 }
141
142                 if (!checkName.IsEmpty()) {
143                         ConfigItem::Ptr oldItem = ConfigItem::GetByTypeAndName(type, checkName);
144
145                         if (oldItem) {
146                                 std::ostringstream msgbuf;
147                                 msgbuf << "Object '" << name << "' of type '" << type->GetName() << "' re-defined: " << debugInfo << "; previous definition: " << oldItem->GetDebugInfo();
148                                 BOOST_THROW_EXCEPTION(ScriptError(msgbuf.str(), debugInfo));
149                         }
150                 }
151
152                 if (filter && !ObjectRule::IsValidSourceType(type->GetName())) {
153                         std::ostringstream msgbuf;
154                         msgbuf << "Object '" << name << "' of type '" << type->GetName() << "' must not have 'assign where' and 'ignore where' rules: " << debugInfo;
155                         BOOST_THROW_EXCEPTION(ScriptError(msgbuf.str(), debugInfo));
156                 }
157
158                 item.SetType(type);
159                 item.SetName(name);
160
161                 if (!abstract)
162                         item.AddExpression(new ImportDefaultTemplatesExpression());
163
164                 item.AddExpression(new OwnedExpression(expression));
165                 item.SetAbstract(abstract);
166                 item.SetScope(EvaluateClosedVars(frame, closedVars));
167                 item.SetZone(zone);
168                 item.SetPackage(package);
169                 item.SetFilter(filter);
170                 item.SetDefaultTemplate(defaultTmpl);
171                 item.SetIgnoreOnError(ignoreOnError);
172                 item.Compile()->Register();
173
174                 return Empty;
175         }
176
177         static inline ExpressionResult For(ScriptFrame& frame, const String& fkvar, const String& fvvar, const Value& value, const std::unique_ptr<Expression>& expression, const DebugInfo& debugInfo = DebugInfo())
178         {
179                 if (value.IsObjectType<Array>()) {
180                         if (!fvvar.IsEmpty())
181                                 BOOST_THROW_EXCEPTION(ScriptError("Cannot use dictionary iterator for array.", debugInfo));
182
183                         Array::Ptr arr = value;
184
185                         for (Array::SizeType i = 0; i < arr->GetLength(); i++) {
186                                 frame.Locals->Set(fkvar, arr->Get(i));
187                                 ExpressionResult res = expression->Evaluate(frame);
188                                 CHECK_RESULT_LOOP(res);
189                         }
190                 } else if (value.IsObjectType<Dictionary>()) {
191                         if (fvvar.IsEmpty())
192                                 BOOST_THROW_EXCEPTION(ScriptError("Cannot use array iterator for dictionary.", debugInfo));
193
194                         Dictionary::Ptr dict = value;
195                         std::vector<String> keys;
196
197                         {
198                                 ObjectLock olock(dict);
199                                 for (const Dictionary::Pair& kv : dict) {
200                                         keys.push_back(kv.first);
201                                 }
202                         }
203
204                         for (const String& key : keys) {
205                                 frame.Locals->Set(fkvar, key);
206                                 frame.Locals->Set(fvvar, dict->Get(key));
207                                 ExpressionResult res = expression->Evaluate(frame);
208                                 CHECK_RESULT_LOOP(res);
209                         }
210                 } else if (value.IsObjectType<Namespace>()) {
211                         if (fvvar.IsEmpty())
212                                 BOOST_THROW_EXCEPTION(ScriptError("Cannot use array iterator for namespace.", debugInfo));
213
214                         Namespace::Ptr ns = value;
215                         std::vector<String> keys;
216
217                         {
218                                 ObjectLock olock(ns);
219                                 for (const Namespace::Pair& kv : ns) {
220                                         keys.push_back(kv.first);
221                                 }
222                         }
223
224                         for (const String& key : keys) {
225                                 frame.Locals->Set(fkvar, key);
226                                 frame.Locals->Set(fvvar, ns->Get(key));
227                                 ExpressionResult res = expression->Evaluate(frame);
228                                 CHECK_RESULT_LOOP(res);
229                         }
230                 } else
231                         BOOST_THROW_EXCEPTION(ScriptError("Invalid type in for expression: " + value.GetTypeName(), debugInfo));
232
233                 return Empty;
234         }
235
236         static inline Value GetField(const Value& context, const String& field, bool sandboxed = false, const DebugInfo& debugInfo = DebugInfo())
237         {
238                 if (unlikely(context.IsEmpty() && !context.IsString()))
239                         return Empty;
240
241                 if (unlikely(!context.IsObject()))
242                         return GetPrototypeField(context, field, true, debugInfo);
243
244                 Object::Ptr object = context;
245
246                 return object->GetFieldByName(field, sandboxed, debugInfo);
247         }
248
249         static inline void SetField(const Object::Ptr& context, const String& field, const Value& value, bool overrideFrozen, const DebugInfo& debugInfo = DebugInfo())
250         {
251                 if (!context)
252                         BOOST_THROW_EXCEPTION(ScriptError("Cannot set field '" + field + "' on a value that is not an object.", debugInfo));
253
254                 return context->SetFieldByName(field, value, overrideFrozen, debugInfo);
255         }
256
257 private:
258         static inline Dictionary::Ptr EvaluateClosedVars(ScriptFrame& frame, const std::map<String, std::unique_ptr<Expression> >& closedVars)
259         {
260                 if (closedVars.empty())
261                         return nullptr;
262
263                 DictionaryData locals;
264
265                 for (const auto& cvar : closedVars)
266                         locals.emplace_back(cvar.first, cvar.second->Evaluate(frame));
267
268                 return new Dictionary(std::move(locals));
269         }
270 };
271
272 }
273
274 #endif /* VMOPS_H */