summaryrefslogtreecommitdiffstats
path: root/lib/config/expression.cpp
blob: a8e99861a1f0a8fc4784a8fc6fcee7936df1b214 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
/* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */

#include "config/expression.hpp"
#include "config/configitem.hpp"
#include "config/configcompiler.hpp"
#include "config/vmops.hpp"
#include "base/array.hpp"
#include "base/json.hpp"
#include "base/object.hpp"
#include "base/logger.hpp"
#include "base/exception.hpp"
#include "base/scriptglobal.hpp"
#include "base/loader.hpp"
#include "base/reference.hpp"
#include "base/namespace.hpp"
#include "base/defer.hpp"
#include <boost/exception_ptr.hpp>
#include <boost/exception/errinfo_nested_exception.hpp>

using namespace icinga;

boost::signals2::signal<void (ScriptFrame&, ScriptError *ex, const DebugInfo&)> Expression::OnBreakpoint;
boost::thread_specific_ptr<bool> l_InBreakpointHandler;

Expression::~Expression()
{ }

void Expression::ScriptBreakpoint(ScriptFrame& frame, ScriptError *ex, const DebugInfo& di)
{
	bool *inHandler = l_InBreakpointHandler.get();
	if (!inHandler || !*inHandler) {
		inHandler = new bool(true);
		l_InBreakpointHandler.reset(inHandler);
		OnBreakpoint(frame, ex, di);
		*inHandler = false;
	}
}

ExpressionResult Expression::Evaluate(ScriptFrame& frame, DebugHint *dhint) const
{
	try {
#ifdef I2_DEBUG
/*		std::ostringstream msgbuf;
		ShowCodeLocation(msgbuf, GetDebugInfo(), false);
		Log(LogDebug, "Expression")
			<< "Executing:\n" << msgbuf.str();*/
#endif /* I2_DEBUG */

		frame.IncreaseStackDepth();

		Defer decreaseStackDepth([&frame]{
			frame.DecreaseStackDepth();
		});

		ExpressionResult result = DoEvaluate(frame, dhint);
		return result;
	} catch (ScriptError& ex) {
		ScriptBreakpoint(frame, &ex, GetDebugInfo());
		throw;
	} catch (const std::exception& ex) {
		BOOST_THROW_EXCEPTION(ScriptError("Error while evaluating expression: " + String(ex.what()), GetDebugInfo())
			<< boost::errinfo_nested_exception(boost::current_exception()));
	}
}

bool Expression::GetReference(ScriptFrame& frame, bool init_dict, Value *parent, String *index, DebugHint **dhint) const
{
	return false;
}

const DebugInfo& Expression::GetDebugInfo() const
{
	static DebugInfo debugInfo;
	return debugInfo;
}

std::unique_ptr<Expression> icinga::MakeIndexer(ScopeSpecifier scopeSpec, const String& index)
{
	std::unique_ptr<Expression> scope{new GetScopeExpression(scopeSpec)};
	return std::unique_ptr<Expression>(new IndexerExpression(std::move(scope), MakeLiteral(index)));
}

void DictExpression::MakeInline()
{
	m_Inline = true;
}

LiteralExpression::LiteralExpression(Value value)
	: m_Value(std::move(value))
{ }

ExpressionResult LiteralExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const
{
	return m_Value;
}

const DebugInfo& DebuggableExpression::GetDebugInfo() const
{
	return m_DebugInfo;
}

VariableExpression::VariableExpression(String variable, std::vector<Expression::Ptr> imports, const DebugInfo& debugInfo)
	: DebuggableExpression(debugInfo), m_Variable(std::move(variable)), m_Imports(std::move(imports))
{
	m_Imports.push_back(MakeIndexer(ScopeGlobal, "System").release());
	m_Imports.push_back(new IndexerExpression(MakeIndexer(ScopeGlobal, "System"), MakeLiteral("Configuration")));
	m_Imports.push_back(MakeIndexer(ScopeGlobal, "Types").release());
	m_Imports.push_back(MakeIndexer(ScopeGlobal, "Icinga").release());
}

ExpressionResult VariableExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const
{
	Value value;

	if (frame.Locals && frame.Locals->Get(m_Variable, &value))
		return value;
	else if (frame.Self.IsObject() && frame.Locals != frame.Self.Get<Object::Ptr>() && frame.Self.Get<Object::Ptr>()->GetOwnField(m_Variable, &value))
		return value;
	else if (VMOps::FindVarImport(frame, m_Imports, m_Variable, &value, m_DebugInfo))
		return value;
	else
		return ScriptGlobal::Get(m_Variable);
}

bool VariableExpression::GetReference(ScriptFrame& frame, bool init_dict, Value *parent, String *index, DebugHint **dhint) const
{
	*index = m_Variable;

	if (frame.Locals && frame.Locals->Contains(m_Variable)) {
		*parent = frame.Locals;

		if (dhint)
			*dhint = nullptr;
	} else if (frame.Self.IsObject() && frame.Locals != frame.Self.Get<Object::Ptr>() && frame.Self.Get<Object::Ptr>()->HasOwnField(m_Variable)) {
		*parent = frame.Self;

		if (dhint && *dhint)
			*dhint = new DebugHint((*dhint)->GetChild(m_Variable));
	} else if (VMOps::FindVarImportRef(frame, m_Imports, m_Variable, parent, m_DebugInfo)) {
		return true;
	} else if (ScriptGlobal::Exists(m_Variable)) {
		*parent = ScriptGlobal::GetGlobals();

		if (dhint)
			*dhint = nullptr;
	} else
		*parent = frame.Self;

	return true;
}

ExpressionResult RefExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const
{
	Value parent;
	String index;

	if (!m_Operand->GetReference(frame, false, &parent, &index, &dhint))
		BOOST_THROW_EXCEPTION(ScriptError("Cannot obtain reference for expression.", m_DebugInfo));

	if (!parent.IsObject())
		BOOST_THROW_EXCEPTION(ScriptError("Cannot obtain reference for expression because parent is not an object.", m_DebugInfo));

	return new Reference(parent, index);
}

ExpressionResult DerefExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const
{
	ExpressionResult operand = m_Operand->Evaluate(frame);
	CHECK_RESULT(operand);

	Object::Ptr obj = operand.GetValue();
	Reference::Ptr ref = dynamic_pointer_cast<Reference>(obj);

	if (!ref)
		BOOST_THROW_EXCEPTION(ScriptError("Invalid reference specified.", GetDebugInfo()));

	return ref->Get();
}

bool DerefExpression::GetReference(ScriptFrame& frame, bool init_dict, Value *parent, String *index, DebugHint **dhint) const
{
	ExpressionResult operand = m_Operand->Evaluate(frame);
	if (operand.GetCode() != ResultOK)
		return false;

	Reference::Ptr ref = operand.GetValue();

	*parent = ref->GetParent();
	*index = ref->GetIndex();
	return true;
}

ExpressionResult NegateExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const
{
	ExpressionResult operand = m_Operand->Evaluate(frame);
	CHECK_RESULT(operand);

	return ~(long)operand.GetValue();
}

ExpressionResult LogicalNegateExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const
{
	ExpressionResult operand = m_Operand->Evaluate(frame);
	CHECK_RESULT(operand);

	return !operand.GetValue().ToBool();
}

ExpressionResult AddExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const
{
	ExpressionResult operand1 = m_Operand1->Evaluate(frame);
	CHECK_RESULT(operand1);

	ExpressionResult operand2 = m_Operand2->Evaluate(frame);
	CHECK_RESULT(operand2);

	return operand1.GetValue() + operand2.GetValue();
}

ExpressionResult SubtractExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const
{
	ExpressionResult operand1 = m_Operand1->Evaluate(frame);
	CHECK_RESULT(operand1);

	ExpressionResult operand2 = m_Operand2->Evaluate(frame);
	CHECK_RESULT(operand2);

	return operand1.GetValue() - operand2.GetValue();
}

ExpressionResult MultiplyExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const
{
	ExpressionResult operand1 = m_Operand1->Evaluate(frame);
	CHECK_RESULT(operand1);

	ExpressionResult operand2 = m_Operand2->Evaluate(frame);
	CHECK_RESULT(operand2);

	return operand1.GetValue() * operand2.GetValue();
}

ExpressionResult DivideExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const
{
	ExpressionResult operand1 = m_Operand1->Evaluate(frame);
	CHECK_RESULT(operand1);

	ExpressionResult operand2 = m_Operand2->Evaluate(frame);
	CHECK_RESULT(operand2);

	return operand1.GetValue() / operand2.GetValue();
}

ExpressionResult ModuloExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const
{
	ExpressionResult operand1 = m_Operand1->Evaluate(frame);
	CHECK_RESULT(operand1);

	ExpressionResult operand2 = m_Operand2->Evaluate(frame);
	CHECK_RESULT(operand2);

	return operand1.GetValue() % operand2.GetValue();
}

ExpressionResult XorExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const
{
	ExpressionResult operand1 = m_Operand1->Evaluate(frame);
	CHECK_RESULT(operand1);

	ExpressionResult operand2 = m_Operand2->Evaluate(frame);
	CHECK_RESULT(operand2);

	return operand1.GetValue() ^ operand2.GetValue();
}

ExpressionResult BinaryAndExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const
{
	ExpressionResult operand1 = m_Operand1->Evaluate(frame);
	CHECK_RESULT(operand1);

	ExpressionResult operand2 = m_Operand2->Evaluate(frame);
	CHECK_RESULT(operand2);

	return operand1.GetValue() & operand2.GetValue();
}

ExpressionResult BinaryOrExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const
{
	ExpressionResult operand1 = m_Operand1->Evaluate(frame);
	CHECK_RESULT(operand1);

	ExpressionResult operand2 = m_Operand2->Evaluate(frame);
	CHECK_RESULT(operand2);

	return operand1.GetValue() | operand2.GetValue();
}

ExpressionResult ShiftLeftExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const
{
	ExpressionResult operand1 = m_Operand1->Evaluate(frame);
	CHECK_RESULT(operand1);

	ExpressionResult operand2 = m_Operand2->Evaluate(frame);
	CHECK_RESULT(operand2);

	return operand1.GetValue() << operand2.GetValue();
}

ExpressionResult ShiftRightExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const
{
	ExpressionResult operand1 = m_Operand1->Evaluate(frame);
	CHECK_RESULT(operand1);

	ExpressionResult operand2 = m_Operand2->Evaluate(frame);
	CHECK_RESULT(operand2);

	return operand1.GetValue() >> operand2.GetValue();
}

ExpressionResult EqualExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const
{
	ExpressionResult operand1 = m_Operand1->Evaluate(frame);
	CHECK_RESULT(operand1);

	ExpressionResult operand2 = m_Operand2->Evaluate(frame);
	CHECK_RESULT(operand2);

	return operand1.GetValue() == operand2.GetValue();
}

ExpressionResult NotEqualExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const
{
	ExpressionResult operand1 = m_Operand1->Evaluate(frame);
	CHECK_RESULT(operand1);

	ExpressionResult operand2 = m_Operand2->Evaluate(frame);
	CHECK_RESULT(operand2);

	return operand1.GetValue() != operand2.GetValue();
}

ExpressionResult LessThanExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const
{
	ExpressionResult operand1 = m_Operand1->Evaluate(frame);
	CHECK_RESULT(operand1);

	ExpressionResult operand2 = m_Operand2->Evaluate(frame);
	CHECK_RESULT(operand2);

	return operand1.GetValue() < operand2.GetValue();
}

ExpressionResult GreaterThanExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const
{
	ExpressionResult operand1 = m_Operand1->Evaluate(frame);
	CHECK_RESULT(operand1);

	ExpressionResult operand2 = m_Operand2->Evaluate(frame);
	CHECK_RESULT(operand2);

	return operand1.GetValue() > operand2.GetValue();
}

ExpressionResult LessThanOrEqualExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const
{
	ExpressionResult operand1 = m_Operand1->Evaluate(frame);
	CHECK_RESULT(operand1);

	ExpressionResult operand2 = m_Operand2->Evaluate(frame);
	CHECK_RESULT(operand2);

	return operand1.GetValue() <= operand2.GetValue();
}

ExpressionResult GreaterThanOrEqualExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const
{
	ExpressionResult operand1 = m_Operand1->Evaluate(frame);
	CHECK_RESULT(operand1);

	ExpressionResult operand2 = m_Operand2->Evaluate(frame);
	CHECK_RESULT(operand2);

	return operand1.GetValue() >= operand2.GetValue();
}

ExpressionResult InExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const
{
	ExpressionResult operand2 = m_Operand2->Evaluate(frame);
	CHECK_RESULT(operand2);

	if (operand2.GetValue().IsEmpty())
		return false;
	else if (!operand2.GetValue().IsObjectType<Array>())
		BOOST_THROW_EXCEPTION(ScriptError("Invalid right side argument for 'in' operator: " + JsonEncode(operand2.GetValue()), m_DebugInfo));

	ExpressionResult operand1 = m_Operand1->Evaluate(frame);
	CHECK_RESULT(operand1)

	Array::Ptr arr = operand2.GetValue();
	return arr->Contains(operand1.GetValue());
}

ExpressionResult NotInExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const
{
	ExpressionResult operand2 = m_Operand2->Evaluate(frame);
	CHECK_RESULT(operand2);

	if (operand2.GetValue().IsEmpty())
		return true;
	else if (!operand2.GetValue().IsObjectType<Array>())
		BOOST_THROW_EXCEPTION(ScriptError("Invalid right side argument for 'in' operator: " + JsonEncode(operand2.GetValue()), m_DebugInfo));

	ExpressionResult operand1 = m_Operand1->Evaluate(frame);
	CHECK_RESULT(operand1);

	Array::Ptr arr = operand2.GetValue();
	return !arr->Contains(operand1.GetValue());
}

ExpressionResult LogicalAndExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const
{
	ExpressionResult operand1 = m_Operand1->Evaluate(frame);
	CHECK_RESULT(operand1);

	if (!operand1.GetValue().ToBool())
		return operand1;
	else {
		ExpressionResult operand2 = m_Operand2->Evaluate(frame);
		CHECK_RESULT(operand2);

		return operand2.GetValue();
	}
}

ExpressionResult LogicalOrExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const
{
	ExpressionResult operand1 = m_Operand1->Evaluate(frame);
	CHECK_RESULT(operand1);

	if (operand1.GetValue().ToBool())
		return operand1;
	else {
		ExpressionResult operand2 = m_Operand2->Evaluate(frame);
		CHECK_RESULT(operand2);

		return operand2.GetValue();
	}
}

ExpressionResult FunctionCallExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const
{
	Value self, vfunc;
	String index;

	if (m_FName->GetReference(frame, false, &self, &index))
		vfunc = VMOps::GetField(self, index, frame.Sandboxed, m_DebugInfo);
	else {
		ExpressionResult vfuncres = m_FName->Evaluate(frame);
		CHECK_RESULT(vfuncres);

		vfunc = vfuncres.GetValue();
	}

	if (vfunc.IsObjectType<Type>()) {
		std::vector<Value> arguments;
		arguments.reserve(m_Args.size());
		for (const auto& arg : m_Args) {
			ExpressionResult argres = arg->Evaluate(frame);
			CHECK_RESULT(argres);

			arguments.push_back(argres.GetValue());
		}

		return VMOps::ConstructorCall(vfunc, arguments, m_DebugInfo);
	}

	if (!vfunc.IsObjectType<Function>())
		BOOST_THROW_EXCEPTION(ScriptError("Argument is not a callable object.", m_DebugInfo));

	Function::Ptr func = vfunc;

	if (!func->IsSideEffectFree() && frame.Sandboxed)
		BOOST_THROW_EXCEPTION(ScriptError("Function is not marked as safe for sandbox mode.", m_DebugInfo));

	std::vector<Value> arguments;
	arguments.reserve(m_Args.size());
	for (const auto& arg : m_Args) {
		ExpressionResult argres = arg->Evaluate(frame);
		CHECK_RESULT(argres);

		arguments.push_back(argres.GetValue());
	}

	return VMOps::FunctionCall(frame, self, func, arguments);
}

ExpressionResult ArrayExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const
{
	ArrayData result;
	result.reserve(m_Expressions.size());

	for (const auto& aexpr : m_Expressions) {
		ExpressionResult element = aexpr->Evaluate(frame);
		CHECK_RESULT(element);

		result.push_back(element.GetValue());
	}

	return new Array(std::move(result));
}

ExpressionResult DictExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const
{
	Value self;

	if (!m_Inline) {
		self = frame.Self;
		frame.Self = new Dictionary();
	}

	Value result;

	try {
		for (const auto& aexpr : m_Expressions) {
			ExpressionResult element = aexpr->Evaluate(frame, m_Inline ? dhint : nullptr);
			CHECK_RESULT(element);
			result = element.GetValue();
		}
	} catch (...) {
		if (!m_Inline)
			std::swap(self, frame.Self);
		throw;
	}

	if (m_Inline)
		return result;
	else {
		std::swap(self, frame.Self);
		return self;
	}
}

ExpressionResult GetScopeExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const
{
	if (m_ScopeSpec == ScopeLocal)
		return frame.Locals;
	else if (m_ScopeSpec == ScopeThis)
		return frame.Self;
	else if (m_ScopeSpec == ScopeGlobal)
		return ScriptGlobal::GetGlobals();
	else
		VERIFY(!"Invalid scope.");
}

static inline
void WarnOnImplicitlySetGlobalVar(const std::unique_ptr<Expression>& setLhs, const Value& setLhsParent, CombinedSetOp setOp, const DebugInfo& debug)
{
	auto var (dynamic_cast<VariableExpression*>(setLhs.get()));

	if (var && setLhsParent.IsObject()) {
		auto ns (dynamic_pointer_cast<Namespace>(setLhsParent.Get<Object::Ptr>()));

		if (ns && ns == ScriptGlobal::GetGlobals() && debug.Path.GetLength()) {
			const char *opStr = nullptr;

			switch (setOp) {
				case OpSetLiteral:
					opStr = "=";
					break;
				case OpSetAdd:
					opStr = "+=";
					break;
				case OpSetSubtract:
					opStr = "-=";
					break;
				case OpSetMultiply:
					opStr = "*=";
					break;
				case OpSetDivide:
					opStr = "/=";
					break;
				case OpSetModulo:
					opStr = "%=";
					break;
				case OpSetXor:
					opStr = "^=";
					break;
				case OpSetBinaryAnd:
					opStr = "&=";
					break;
				case OpSetBinaryOr:
					opStr = "|=";
					break;
				default:
					VERIFY(!"Invalid opcode.");
			}

			auto varName (var->GetVariable());

			Log(LogWarning, "config")
				<< "Global variable '" << varName << "' has been set implicitly via '" << varName << ' ' << opStr << " ...' " << debug << "."
				" Please set it explicitly via 'globals." << varName << ' ' << opStr << " ...' instead.";
		}
	}
}

ExpressionResult SetExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const
{
	if (frame.Sandboxed)
		BOOST_THROW_EXCEPTION(ScriptError("Assignments are not allowed in sandbox mode.", m_DebugInfo));

	DebugHint *psdhint = dhint;

	Value parent;
	String index;

	if (!m_Operand1->GetReference(frame, true, &parent, &index, &psdhint))
		BOOST_THROW_EXCEPTION(ScriptError("Expression cannot be assigned to.", m_DebugInfo));

	ExpressionResult operand2 = m_Operand2->Evaluate(frame, dhint);
	CHECK_RESULT(operand2);

	if (m_Op != OpSetLiteral) {
		Value object = VMOps::GetField(parent, index, frame.Sandboxed, m_DebugInfo);

		switch (m_Op) {
			case OpSetAdd:
				operand2 = object + operand2;
				break;
			case OpSetSubtract:
				operand2 = object - operand2;
				break;
			case OpSetMultiply:
				operand2 = object * operand2;
				break;
			case OpSetDivide:
				operand2 = object / operand2;
				break;
			case OpSetModulo:
				operand2 = object % operand2;
				break;
			case OpSetXor:
				operand2 = object ^ operand2;
				break;
			case OpSetBinaryAnd:
				operand2 = object & operand2;
				break;
			case OpSetBinaryOr:
				operand2 = object | operand2;
				break;
			default:
				VERIFY(!"Invalid opcode.");
		}
	}

	VMOps::SetField(parent, index, operand2.GetValue(), m_OverrideFrozen, m_DebugInfo);

	if (psdhint) {
		psdhint->AddMessage("=", m_DebugInfo);

		if (psdhint != dhint)
			delete psdhint;
	}

	WarnOnImplicitlySetGlobalVar(m_Operand1, parent, m_Op, m_DebugInfo);

	return Empty;
}

void SetExpression::SetOverrideFrozen()
{
	m_OverrideFrozen = true;
}

ExpressionResult SetConstExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const
{
	auto globals = ScriptGlobal::GetGlobals();

	ExpressionResult operandres = m_Operand->Evaluate(frame);
	CHECK_RESULT(operandres);
	Value operand = operandres.GetValue();

	globals->Set(m_Name, operand, true);

	return Empty;
}

ExpressionResult ConditionalExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const
{
	ExpressionResult condition = m_Condition->Evaluate(frame, dhint);
	CHECK_RESULT(condition);

	if (condition.GetValue().ToBool())
		return m_TrueBranch->Evaluate(frame, dhint);
	else if (m_FalseBranch)
		return m_FalseBranch->Evaluate(frame, dhint);

	return Empty;
}

ExpressionResult WhileExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const
{
	if (frame.Sandboxed)
		BOOST_THROW_EXCEPTION(ScriptError("While loops are not allowed in sandbox mode.", m_DebugInfo));

	for (;;) {
		ExpressionResult condition = m_Condition->Evaluate(frame, dhint);
		CHECK_RESULT(condition);

		if (!condition.GetValue().ToBool())
			break;

		ExpressionResult loop_body = m_LoopBody->Evaluate(frame, dhint);
		CHECK_RESULT_LOOP(loop_body);
	}

	return Empty;
}

ExpressionResult ReturnExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const
{
	ExpressionResult operand = m_Operand->Evaluate(frame);
	CHECK_RESULT(operand);

	return ExpressionResult(operand.GetValue(), ResultReturn);
}

ExpressionResult BreakExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const
{
	return ExpressionResult(Empty, ResultBreak);
}

ExpressionResult ContinueExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const
{
	return ExpressionResult(Empty, ResultContinue);
}

ExpressionResult IndexerExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const
{
	ExpressionResult operand1 = m_Operand1->Evaluate(frame, dhint);
	CHECK_RESULT(operand1);

	ExpressionResult operand2 = m_Operand2->Evaluate(frame, dhint);
	CHECK_RESULT(operand2);

	return VMOps::GetField(operand1.GetValue(), operand2.GetValue(), frame.Sandboxed, m_DebugInfo);
}

bool IndexerExpression::GetReference(ScriptFrame& frame, bool init_dict, Value *parent, String *index, DebugHint **dhint) const
{
	Value vparent;
	String vindex;
	DebugHint *psdhint = nullptr;
	bool free_psd = false;

	if (dhint)
		psdhint = *dhint;

	if (frame.Sandboxed)
		init_dict = false;

	if (m_Operand1->GetReference(frame, init_dict, &vparent, &vindex, &psdhint)) {
		if (init_dict) {
			Value old_value;
			bool has_field = true;

			if (vparent.IsObject()) {
				Object::Ptr oparent = vparent;
				has_field = oparent->HasOwnField(vindex);
			}

			if (has_field)
				old_value = VMOps::GetField(vparent, vindex, frame.Sandboxed, m_Operand1->GetDebugInfo());

			if (old_value.IsEmpty() && !old_value.IsString())
				VMOps::SetField(vparent, vindex, new Dictionary(), m_OverrideFrozen, m_Operand1->GetDebugInfo());
		}

		*parent = VMOps::GetField(vparent, vindex, frame.Sandboxed, m_DebugInfo);
		free_psd = true;
	} else {
		ExpressionResult operand1 = m_Operand1->Evaluate(frame);
		*parent = operand1.GetValue();
	}

	ExpressionResult operand2 = m_Operand2->Evaluate(frame);
	*index = operand2.GetValue();

	if (dhint) {
		if (psdhint)
			*dhint = new DebugHint(psdhint->GetChild(*index));
		else
			*dhint = nullptr;
	}

	if (free_psd)
		delete psdhint;

	return true;
}

void IndexerExpression::SetOverrideFrozen()
{
	m_OverrideFrozen = true;
}

void icinga::BindToScope(std::unique_ptr<Expression>& expr, ScopeSpecifier scopeSpec)
{
	auto *dexpr = dynamic_cast<DictExpression *>(expr.get());

	if (dexpr) {
		for (auto& expr : dexpr->m_Expressions)
			BindToScope(expr, scopeSpec);

		return;
	}

	auto *aexpr = dynamic_cast<SetExpression *>(expr.get());

	if (aexpr) {
		BindToScope(aexpr->m_Operand1, scopeSpec);

		return;
	}

	auto *iexpr = dynamic_cast<IndexerExpression *>(expr.get());

	if (iexpr) {
		BindToScope(iexpr->m_Operand1, scopeSpec);
		return;
	}

	auto *lexpr = dynamic_cast<LiteralExpression *>(expr.get());

	if (lexpr && lexpr->GetValue().IsString()) {
		std::unique_ptr<Expression> scope{new GetScopeExpression(scopeSpec)};
		expr.reset(new IndexerExpression(std::move(scope), std::move(expr), lexpr->GetDebugInfo()));
	}

	auto *vexpr = dynamic_cast<VariableExpression *>(expr.get());

	if (vexpr) {
		std::unique_ptr<Expression> scope{new GetScopeExpression(scopeSpec)};
		expr.reset(new IndexerExpression(std::move(scope), MakeLiteral(vexpr->GetVariable()), vexpr->GetDebugInfo()));
	}
}

ExpressionResult ThrowExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const
{
	ExpressionResult messageres = m_Message->Evaluate(frame);
	CHECK_RESULT(messageres);
	Value message = messageres.GetValue();
	BOOST_THROW_EXCEPTION(ScriptError(message, m_DebugInfo, m_IncompleteExpr));
}

ExpressionResult ImportExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const
{
	if (frame.Sandboxed)
		BOOST_THROW_EXCEPTION(ScriptError("Imports are not allowed in sandbox mode.", m_DebugInfo));

	String type = VMOps::GetField(frame.Self, "type", frame.Sandboxed, m_DebugInfo);
	ExpressionResult nameres = m_Name->Evaluate(frame);
	CHECK_RESULT(nameres);
	Value name = nameres.GetValue();

	if (!name.IsString())
		BOOST_THROW_EXCEPTION(ScriptError("Template/object name must be a string", m_DebugInfo));

	ConfigItem::Ptr item = ConfigItem::GetByTypeAndName(Type::GetByName(type), name);

	if (!item)
		BOOST_THROW_EXCEPTION(ScriptError("Import references unknown template: '" + name + "'", m_DebugInfo));

	Dictionary::Ptr scope = item->GetScope();

	if (scope)
		scope->CopyTo(frame.Locals);

	ExpressionResult result = item->GetExpression()->Evaluate(frame, dhint);
	CHECK_RESULT(result);

	return Empty;
}

ExpressionResult ImportDefaultTemplatesExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const
{
	if (frame.Sandboxed)
		BOOST_THROW_EXCEPTION(ScriptError("Imports are not allowed in sandbox mode.", m_DebugInfo));

	String type = VMOps::GetField(frame.Self, "type", frame.Sandboxed, m_DebugInfo);
	Type::Ptr ptype = Type::GetByName(type);

	for (const ConfigItem::Ptr& item : ConfigItem::GetDefaultTemplates(ptype)) {
		Dictionary::Ptr scope = item->GetScope();

		if (scope)
			scope->CopyTo(frame.Locals);

		ExpressionResult result = item->GetExpression()->Evaluate(frame, dhint);
		CHECK_RESULT(result);
	}

	return Empty;
}

ExpressionResult FunctionExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const
{
	return VMOps::NewFunction(frame, m_Name, m_Args, m_ClosedVars, m_Expression);
}

ExpressionResult ApplyExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const
{
	if (frame.Sandboxed)
		BOOST_THROW_EXCEPTION(ScriptError("Apply rules are not allowed in sandbox mode.", m_DebugInfo));

	ExpressionResult nameres = m_Name->Evaluate(frame);
	CHECK_RESULT(nameres);

	return VMOps::NewApply(frame, m_Type, m_Target, nameres.GetValue(), m_Filter,
		m_Package, m_FKVar, m_FVVar, m_FTerm, m_ClosedVars, m_IgnoreOnError, m_Expression, m_DebugInfo);
}

ExpressionResult NamespaceExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const
{
	Namespace::Ptr ns = new Namespace(true);

	ScriptFrame innerFrame(true, ns);
	ExpressionResult result = m_Expression->Evaluate(innerFrame);
	CHECK_RESULT(result);

	return ns;
}

ExpressionResult ObjectExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const
{
	if (frame.Sandboxed)
		BOOST_THROW_EXCEPTION(ScriptError("Object definitions are not allowed in sandbox mode.", m_DebugInfo));

	ExpressionResult typeres = m_Type->Evaluate(frame, dhint);
	CHECK_RESULT(typeres);
	Type::Ptr type = typeres.GetValue();

	String name;

	if (m_Name) {
		ExpressionResult nameres = m_Name->Evaluate(frame, dhint);
		CHECK_RESULT(nameres);

		name = nameres.GetValue();
	}

	return VMOps::NewObject(frame, m_Abstract, type, name, m_Filter, m_Zone,
		m_Package, m_DefaultTmpl, m_IgnoreOnError, m_ClosedVars, m_Expression, m_DebugInfo);
}

ExpressionResult ForExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const
{
	if (frame.Sandboxed)
		BOOST_THROW_EXCEPTION(ScriptError("For loops are not allowed in sandbox mode.", m_DebugInfo));

	ExpressionResult valueres = m_Value->Evaluate(frame, dhint);
	CHECK_RESULT(valueres);

	return VMOps::For(frame, m_FKVar, m_FVVar, valueres.GetValue(), m_Expression, m_DebugInfo);
}

ExpressionResult LibraryExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const
{
	if (frame.Sandboxed)
		BOOST_THROW_EXCEPTION(ScriptError("Loading libraries is not allowed in sandbox mode.", m_DebugInfo));

	ExpressionResult libres = m_Operand->Evaluate(frame, dhint);
	CHECK_RESULT(libres);

	Log(LogNotice, "config")
		<< "Ignoring explicit load request for library \"" << libres << "\".";

	return Empty;
}

ExpressionResult IncludeExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const
{
	if (frame.Sandboxed)
		BOOST_THROW_EXCEPTION(ScriptError("Includes are not allowed in sandbox mode.", m_DebugInfo));

	std::unique_ptr<Expression> expr;
	String name, path, pattern;

	switch (m_Type) {
		case IncludeRegular:
			{
				ExpressionResult pathres = m_Path->Evaluate(frame, dhint);
				CHECK_RESULT(pathres);
				path = pathres.GetValue();
			}

			expr = ConfigCompiler::HandleInclude(m_RelativeBase, path, m_SearchIncludes, m_Zone, m_Package, m_DebugInfo);
			break;

		case IncludeRecursive:
			{
				ExpressionResult pathres = m_Path->Evaluate(frame, dhint);
				CHECK_RESULT(pathres);
				path = pathres.GetValue();
			}

			{
				ExpressionResult patternres = m_Pattern->Evaluate(frame, dhint);
				CHECK_RESULT(patternres);
				pattern = patternres.GetValue();
			}

			expr = ConfigCompiler::HandleIncludeRecursive(m_RelativeBase, path, pattern, m_Zone, m_Package, m_DebugInfo);
			break;

		case IncludeZones:
			{
				ExpressionResult nameres = m_Name->Evaluate(frame, dhint);
				CHECK_RESULT(nameres);
				name = nameres.GetValue();
			}

			{
				ExpressionResult pathres = m_Path->Evaluate(frame, dhint);
				CHECK_RESULT(pathres);
				path = pathres.GetValue();
			}

			{
				ExpressionResult patternres = m_Pattern->Evaluate(frame, dhint);
				CHECK_RESULT(patternres);
				pattern = patternres.GetValue();
			}

			expr = ConfigCompiler::HandleIncludeZones(m_RelativeBase, name, path, pattern, m_Package, m_DebugInfo);
			break;
	}

	ExpressionResult res(Empty);

	try {
		res = expr->Evaluate(frame, dhint);
	} catch (const std::exception&) {
		throw;
	}

	return res;
}

ExpressionResult BreakpointExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const
{
	ScriptBreakpoint(frame, nullptr, GetDebugInfo());

	return Empty;
}

ExpressionResult TryExceptExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const
{
	try {
		ExpressionResult tryResult = m_TryBody->Evaluate(frame, dhint);
		CHECK_RESULT(tryResult);
	} catch (const std::exception&) {
		ExpressionResult exceptResult = m_ExceptBody->Evaluate(frame, dhint);
		CHECK_RESULT(exceptResult);
	}

	return Empty;
}