-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Value.cc
1337 lines (1186 loc) · 44.2 KB
/
Value.cc
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
/*
* OpenSCAD (www.openscad.org)
* Copyright (C) 2009-2011 Clifford Wolf <clifford@clifford.at> and
* Marius Kintel <marius@kintel.net>
*
* This program 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 2 of the License, or
* (at your option) any later version.
*
* As a special exception, you have permission to link this program
* with the CGAL library and distribute executables, as long as you
* follow the requirements of the GNU GPL in regard to all of the
* software in the executable aside from CGAL.
*
* This program 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 this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include <cassert>
#include <cmath>
#include <numeric>
#include <sstream>
#include <boost/format.hpp>
#include <boost/variant/apply_visitor.hpp>
#include <boost/variant/static_visitor.hpp>
/*Unicode support for string lengths and array accesses*/
#include <glib.h>
#include "Value.h"
#include "Expression.h"
#include "EvaluationSession.h"
#include "printutils.h"
#include "boost-utils.h"
#include "double-conversion/double-conversion.h"
#include "double-conversion/utils.h"
#include "double-conversion/ieee.h"
#include "boost-utils.h"
namespace fs = boost::filesystem;
const Value Value::undefined;
const VectorType VectorType::EMPTY(nullptr);
const RangeType RangeType::EMPTY{0, 0, 0};
/* Define values for double-conversion library. */
#define DC_BUFFER_SIZE 128
#define DC_FLAGS (double_conversion::DoubleToStringConverter::UNIQUE_ZERO | double_conversion::DoubleToStringConverter::EMIT_POSITIVE_EXPONENT_SIGN)
#define DC_INF "inf"
#define DC_NAN "nan"
#define DC_EXP 'e'
#define DC_DECIMAL_LOW_EXP -6
#define DC_DECIMAL_HIGH_EXP 21
#define DC_MAX_LEADING_ZEROES 5
#define DC_MAX_TRAILING_ZEROES 0
/* WARNING: using values > 8 will significantly slow double to string
* conversion, defeating the purpose of using double-conversion library */
#define DC_PRECISION_REQUESTED 6
//private definitions used by trimTrailingZeroesHelper
#define TRIM_TRAILINGZEROES_DONE 0
#define TRIM_TRAILINGZEROES_CONTINUE 1
//process parameter buffer from the end to start to find out where the zeroes are located (if any).
//parameter pos shall be the pos in buffer where '\0' is located.
//parameter currentpos shall be set to end of buffer (where '\0' is located).
//set parameters exppos and decimalpos when needed.
//leave parameter zeropos as is.
inline int trimTrailingZeroesHelper(char *buffer, const int pos, char *currentpos = nullptr, char *exppos = nullptr, char *decimalpos = nullptr, char *zeropos = nullptr) {
int cont = TRIM_TRAILINGZEROES_CONTINUE;
//we have exhausted all positions from end to start
if (currentpos <= buffer) return TRIM_TRAILINGZEROES_DONE;
//we do no need to process the terminator of string
if (*currentpos == '\0') {
currentpos--;
cont = trimTrailingZeroesHelper(buffer, pos, currentpos, exppos, decimalpos, zeropos);
}
//we have an exponent and jumps to the position before the exponent - no need to process the characters belonging to the exponent
if (cont && exppos && currentpos >= exppos) {
currentpos = exppos;
currentpos--;
cont = trimTrailingZeroesHelper(buffer, pos, currentpos, exppos, decimalpos, zeropos);
}
//we are still on the right side of the decimal and still counting zeroes (keep track of) from the back to start
if (cont && currentpos && decimalpos < currentpos && *currentpos == '0') {
zeropos = currentpos;
currentpos--;
cont = trimTrailingZeroesHelper(buffer, pos, currentpos, exppos, decimalpos, zeropos);
}
//we have found the first occurrence of not a zero and have zeroes and exponent to take care of (move exponent to either the position of the zero or the decimal)
if (cont && zeropos && exppos) {
int count = &buffer[pos] - exppos + 1;
memmove(zeropos - 1 == decimalpos ? decimalpos : zeropos, exppos, count);
return TRIM_TRAILINGZEROES_DONE;
}
//we have found a zero and need to take care of (truncate the string to the position of either the zero or the decimal)
if (cont && zeropos) {
zeropos - 1 == decimalpos ? *decimalpos = '\0' : *zeropos = '\0';
return TRIM_TRAILINGZEROES_DONE;
}
//we have just another character (other than a zero) and are done
if (cont && !zeropos) return TRIM_TRAILINGZEROES_DONE;
return TRIM_TRAILINGZEROES_DONE;
}
inline void trimTrailingZeroes(char *buffer, const int pos) {
char *decimal = strchr(buffer, '.');
if (decimal) {
char *exppos = strchr(buffer, DC_EXP);
trimTrailingZeroesHelper(buffer, pos, &buffer[pos], exppos, decimal, nullptr);
}
}
inline bool HandleSpecialValues(const double& value, double_conversion::StringBuilder& builder) {
double_conversion::Double double_inspect(value);
if (double_inspect.IsInfinite()) {
if (value < 0) {
builder.AddCharacter('-');
}
builder.AddString(DC_INF);
return true;
}
if (double_inspect.IsNan()) {
builder.AddString(DC_NAN);
return true;
}
return false;
}
inline std::string DoubleConvert(const double& value, char *buffer,
double_conversion::StringBuilder& builder, const double_conversion::DoubleToStringConverter& dc) {
builder.Reset();
if (double_conversion::Double(value).IsSpecial()) {
HandleSpecialValues(value, builder);
builder.Finalize();
return buffer;
}
dc.ToPrecision(value, DC_PRECISION_REQUESTED, &builder);
int pos = builder.position(); // get position before Finalize destroys it
builder.Finalize();
trimTrailingZeroes(buffer, pos);
return buffer;
}
static uint32_t convert_to_uint32(const double d)
{
auto ret = std::numeric_limits<uint32_t>::max();
if (std::isfinite(d)) {
try {
ret = boost::numeric_cast<uint32_t>(d);
} catch (boost::bad_numeric_cast&) {
// ignore, leaving the default max() value
}
}
return ret;
}
std::ostream& operator<<(std::ostream& stream, const Filename& filename)
{
fs::path fnpath{static_cast<std::string>(filename)}; // gcc-4.6
auto fpath = boostfs_uncomplete(fnpath, fs::current_path());
stream << QuotedString(fpath.generic_string());
return stream;
}
// FIXME: This could probably be done more elegantly using boost::regex
std::ostream& operator<<(std::ostream& stream, const QuotedString& s)
{
stream << '"';
for (char c : s) {
switch (c) {
case '\t': stream << "\\t"; break;
case '\n': stream << "\\n"; break;
case '\r': stream << "\\r"; break;
case '"': stream << "\\\""; break;
case '\\': stream << "\\\\"; break;
default: stream << c;
}
}
return stream << '"';
}
Value Value::clone() const {
switch (this->type()) {
case Type::UNDEFINED: return Value();
case Type::BOOL: return boost::get<bool>(this->value);
case Type::NUMBER: return boost::get<double>(this->value);
case Type::STRING: return boost::get<str_utf8_wrapper>(this->value).clone();
case Type::RANGE: return boost::get<RangePtr>(this->value).clone();
case Type::VECTOR: return boost::get<VectorType>(this->value).clone();
case Type::OBJECT: return boost::get<ObjectType>(this->value).clone();
case Type::FUNCTION: return boost::get<FunctionPtr>(this->value).clone();
default: assert(false && "unknown Value variant type"); return Value();
}
}
Value Value::undef(const std::string& why)
{
return Value{UndefType{why}};
}
std::string Value::typeName(Type type)
{
switch (type) {
case Type::UNDEFINED: return "undefined";
case Type::BOOL: return "bool";
case Type::NUMBER: return "number";
case Type::STRING: return "string";
case Type::VECTOR: return "vector";
case Type::RANGE: return "range";
case Type::OBJECT: return "object";
case Type::FUNCTION: return "function";
default: assert(false && "unknown Value variant type"); return "<unknown>";
}
}
const std::string Value::typeName() const
{
return typeName(this->type());
}
// free functions for use by static_visitor templated functions in creating undef messages.
std::string getTypeName(const UndefType&) { return "undefined"; }
std::string getTypeName(bool) { return "bool"; }
std::string getTypeName(double) { return "number"; }
std::string getTypeName(const str_utf8_wrapper&) { return "string"; }
std::string getTypeName(const VectorType&) { return "vector"; }
std::string getTypeName(const ObjectType&) { return "object"; }
std::string getTypeName(const RangePtr&) { return "range"; }
std::string getTypeName(const FunctionPtr&) { return "function"; }
bool Value::toBool() const
{
switch (this->type()) {
case Type::UNDEFINED: return false;
case Type::BOOL: return boost::get<bool>(this->value);
case Type::NUMBER: return boost::get<double>(this->value) != 0;
case Type::STRING: return !boost::get<str_utf8_wrapper>(this->value).empty();
case Type::VECTOR: return !boost::get<VectorType>(this->value).empty();
case Type::RANGE: return true;
case Type::OBJECT: return true;
case Type::FUNCTION: return true;
default: assert(false && "unknown Value variant type"); return false;
}
}
double Value::toDouble() const
{
const double *d = boost::get<double>(&this->value);
return d ? *d : 0.0;
}
bool Value::getDouble(double& v) const
{
const double *d = boost::get<double>(&this->value);
if (d) {
v = *d;
return true;
}
return false;
}
bool Value::getFiniteDouble(double& v) const
{
double result;
if (getDouble(result) && std::isfinite(result)) {
v = result;
return true;
}
return false;
}
const str_utf8_wrapper& Value::toStrUtf8Wrapper() const {
return boost::get<str_utf8_wrapper>(this->value);
}
// Optimization to avoid multiple stream instantiations and copies to str for long vectors.
// Functions identically to "class tostring_visitor", except outputting to stream and not returning strings
class tostream_visitor : public boost::static_visitor<>
{
public:
std::ostringstream& stream;
mutable char buffer[DC_BUFFER_SIZE];
mutable double_conversion::StringBuilder builder;
double_conversion::DoubleToStringConverter dc;
tostream_visitor(std::ostringstream& stream)
: stream(stream), builder(buffer, DC_BUFFER_SIZE),
dc(DC_FLAGS, DC_INF, DC_NAN, DC_EXP, DC_DECIMAL_LOW_EXP, DC_DECIMAL_HIGH_EXP, DC_MAX_LEADING_ZEROES, DC_MAX_TRAILING_ZEROES)
{}
template <typename T> void operator()(const T& op1) const {
//std::cout << "[generic tostream_visitor]\n";
stream << boost::lexical_cast<std::string>(op1);
}
void operator()(const double& op1) const {
stream << DoubleConvert(op1, buffer, builder, dc);
}
void operator()(const UndefType&) const {
stream << "undef";
}
void operator()(const bool& v) const {
stream << (v ? "true" : "false");
}
void operator()(const EmbeddedVectorType&) const {
assert(false && "Error: unexpected visit to EmbeddedVectorType!");
}
void operator()(const VectorType& v) const {
stream << '[';
if (!v.empty()) {
auto it = v.begin();
boost::apply_visitor(*this, it->getVariant());
for (++it; it != v.end(); ++it) {
stream << ", ";
boost::apply_visitor(*this, it->getVariant());
}
}
stream << ']';
}
void operator()(const str_utf8_wrapper& v) const {
stream << '"' << v.toString() << '"';
}
void operator()(const RangePtr& v) const {
stream << *v;
}
void operator()(const FunctionPtr& v) const {
stream << *v;
}
};
class tostring_visitor : public boost::static_visitor<std::string>
{
public:
template <typename T> std::string operator()(const T& op1) const {
assert(false && "unhandled tostring_visitor type");
return boost::lexical_cast<std::string>(op1);
}
std::string operator()(const str_utf8_wrapper& op1) const {
return op1.toString();
}
std::string operator()(const double& op1) const {
char buffer[DC_BUFFER_SIZE];
double_conversion::StringBuilder builder(buffer, DC_BUFFER_SIZE);
double_conversion::DoubleToStringConverter dc(DC_FLAGS, DC_INF, DC_NAN, DC_EXP,
DC_DECIMAL_LOW_EXP, DC_DECIMAL_HIGH_EXP, DC_MAX_LEADING_ZEROES, DC_MAX_TRAILING_ZEROES);
return DoubleConvert(op1, buffer, builder, dc);
}
std::string operator()(const UndefType&) const {
return "undef";
}
std::string operator()(const bool& v) const {
return v ? "true" : "false";
}
std::string operator()(const EmbeddedVectorType&) const {
assert(false && "Error: unexpected visit to EmbeddedVectorType!");
return "";
}
std::string operator()(const VectorType& v) const {
// Create a single stream and pass reference to it for list elements for optimization.
std::ostringstream stream;
(tostream_visitor(stream))(v);
return stream.str();
}
std::string operator()(const ObjectType& v) const {
return STR(v);
}
std::string operator()(const RangePtr& v) const {
return STR(*v);
}
std::string operator()(const FunctionPtr& v) const {
return STR(*v);
}
};
std::string Value::toString() const
{
return boost::apply_visitor(tostring_visitor(), this->value);
}
std::string Value::toEchoString() const
{
if (type() == Value::Type::STRING) {
return std::string("\"") + toString() + '"';
} else {
return toString();
}
}
std::string UndefType::toString() const {
std::ostringstream stream;
if (!reasons->empty()) {
auto it = reasons->begin();
stream << *it;
for (++it; it != reasons->end(); ++it) {
stream << "\n\t" << *it;
}
}
// clear reasons so multiple same warnings are not given on the same value
reasons->clear();
return stream.str();
}
const UndefType& Value::toUndef()
{
return boost::get<UndefType>(this->value);
}
std::string Value::toUndefString() const
{
return boost::get<UndefType>(this->value).toString();
}
std::ostream& operator<<(std::ostream& stream, const UndefType& u)
{
stream << "undef";
return stream;
}
class chr_visitor : public boost::static_visitor<std::string>
{
public:
template <typename S> std::string operator()(const S&) const
{
return "";
}
std::string operator()(const double& v) const
{
char buf[8];
memset(buf, 0, 8);
if (v > 0) {
const gunichar c = v;
if (g_unichar_validate(c) && (c != 0)) {
g_unichar_to_utf8(c, buf);
}
}
return std::string(buf);
}
std::string operator()(const VectorType& v) const
{
std::ostringstream stream;
for (auto& val : v) {
stream << val.chrString();
}
return stream.str();
}
std::string operator()(const RangePtr& v) const
{
const uint32_t steps = v->numValues();
if (steps >= RangeType::MAX_RANGE_STEPS) {
LOG(message_group::Warning, Location::NONE, "", "Bad range parameter in for statement: too many elements (%1$lu).", steps);
return "";
}
std::ostringstream stream;
for (double d : *v) stream << Value(d).chrString();
return stream.str();
}
};
std::string Value::chrString() const
{
return boost::apply_visitor(chr_visitor(), this->value);
}
VectorType::VectorType(EvaluationSession *session) :
ptr(shared_ptr<VectorObject>(new VectorObject(), VectorObjectDeleter() ))
{
ptr->evaluation_session = session;
}
VectorType::VectorType(class EvaluationSession *session, double x, double y, double z) :
ptr(shared_ptr<VectorObject>(new VectorObject(), VectorObjectDeleter() ))
{
ptr->evaluation_session = session;
emplace_back(x);
emplace_back(y);
emplace_back(z);
}
void VectorType::emplace_back(Value&& val)
{
if (val.type() == Value::Type::EMBEDDED_VECTOR) {
emplace_back(std::move(val.toEmbeddedVectorNonConst()));
} else {
ptr->vec.push_back(std::move(val));
if (ptr->evaluation_session) {
ptr->evaluation_session->accounting().addVectorElement(1);
}
}
}
// Specialized handler for EmbeddedVectorTypes
void VectorType::emplace_back(EmbeddedVectorType&& mbed)
{
if (mbed.size() > 1) {
// embed_excess represents how many to add to vec.size() to get the total elements after flattening,
// the embedded vector itself already counts towards an element in the parent's size, so subtract 1 from its size.
ptr->embed_excess += mbed.size() - 1;
ptr->vec.emplace_back(std::move(mbed));
if (ptr->evaluation_session) {
ptr->evaluation_session->accounting().addVectorElement(1);
}
} else if (mbed.size() == 1) {
// If embedded vector contains only one value, then insert a copy of that element
// Due to the above mentioned "-1" count, putting it in directaly as an EmbeddedVector
// would not change embed_excess, which is needed to check if flatten is required.
emplace_back(mbed.ptr->vec[0].clone());
}
// else mbed.size() == 0, do nothing
}
void VectorType::flatten() const
{
vec_t ret;
ret.reserve(this->size());
// VectorType::iterator already handles the tricky recursive navigation of embedded vectors,
// so just build up our new vector from that.
for (const auto& el : *this) ret.emplace_back(el.clone());
assert(ret.size() == this->size());
ptr->embed_excess = 0;
if (ptr->evaluation_session) {
ptr->evaluation_session->accounting().addVectorElement(ret.size());
ptr->evaluation_session->accounting().removeVectorElement(ptr->vec.size());
}
ptr->vec = std::move(ret);
}
void VectorType::VectorObjectDeleter::operator()(VectorObject *v)
{
if (v->evaluation_session) {
v->evaluation_session->accounting().removeVectorElement(v->vec.size());
}
VectorObject *orig = v;
shared_ptr<VectorObject> curr;
std::vector<shared_ptr<VectorObject>> purge;
while (true) {
if (v && v->embed_excess) {
for (Value& val : v->vec) {
auto type = val.type();
if (type == Value::Type::EMBEDDED_VECTOR) {
shared_ptr<VectorObject>& temp = boost::get<EmbeddedVectorType>(val.value).ptr;
if (temp.use_count() <= 1) purge.emplace_back(std::move(temp));
} else if (type == Value::Type::VECTOR) {
shared_ptr<VectorObject>& temp = boost::get<VectorType>(val.value).ptr;
if (temp.use_count() <= 1) purge.emplace_back(std::move(temp));
}
}
}
if (purge.empty()) break;
curr = std::move(purge.back()); // this should cause destruction of the *previous value* for curr
v = curr.get();
purge.pop_back();
}
delete orig;
}
const VectorType& Value::toVector() const
{
static const VectorType empty(nullptr);
const VectorType *v = boost::get<VectorType>(&this->value);
return v ? *v : empty;
}
VectorType& Value::toVectorNonConst()
{
return boost::get<VectorType>(this->value);
}
const ObjectType& Value::toObject() const
{
static const ObjectType empty(nullptr);
const ObjectType *v = boost::get<ObjectType>(&this->value);
return v ? *v : empty;
}
EmbeddedVectorType& Value::toEmbeddedVectorNonConst()
{
return boost::get<EmbeddedVectorType>(this->value);
}
const EmbeddedVectorType& Value::toEmbeddedVector() const
{
return boost::get<EmbeddedVectorType>(this->value);
}
bool Value::getVec2(double& x, double& y, bool ignoreInfinite) const
{
if (this->type() != Type::VECTOR) return false;
const auto& v = this->toVector();
if (v.size() != 2) return false;
double rx, ry;
bool valid = ignoreInfinite
? v[0].getFiniteDouble(rx) && v[1].getFiniteDouble(ry)
: v[0].getDouble(rx) && v[1].getDouble(ry);
if (valid) {
x = rx;
y = ry;
}
return valid;
}
bool Value::getVec3(double& x, double& y, double& z) const
{
if (this->type() != Type::VECTOR) return false;
const VectorType& v = this->toVector();
if (v.size() != 3) return false;
return (v[0].getDouble(x) && v[1].getDouble(y) && v[2].getDouble(z));
}
bool Value::getVec3(double& x, double& y, double& z, double defaultval) const
{
if (this->type() != Type::VECTOR) return false;
const VectorType& v = toVector();
if (v.size() == 2) {
getVec2(x, y);
z = defaultval;
return true;
} else {
if (v.size() != 3) return false;
}
return (v[0].getDouble(x) && v[1].getDouble(y) && v[2].getDouble(z));
}
const RangeType& Value::toRange() const
{
const RangePtr *val = boost::get<RangePtr>(&this->value);
if (val) {
return **val;
} else return RangeType::EMPTY;
}
const FunctionType& Value::toFunction() const
{
return *boost::get<FunctionPtr>(this->value);
}
bool Value::isUncheckedUndef() const
{
return this->type() == Type::UNDEFINED && !boost::get<UndefType>(this->value).empty();
}
Value FunctionType::operator==(const FunctionType& other) const {
return this == &other;
}
Value FunctionType::operator!=(const FunctionType& other) const {
return this != &other;
}
Value FunctionType::operator<(const FunctionType& other) const {
return Value::undef("operation undefined (function < function)");
}
Value FunctionType::operator>(const FunctionType& other) const {
return Value::undef("operation undefined (function > function)");
}
Value FunctionType::operator<=(const FunctionType& other) const {
return Value::undef("operation undefined (function <= function)");
}
Value FunctionType::operator>=(const FunctionType& other) const {
return Value::undef("operation undefined (function >= function)");
}
Value UndefType::operator<(const UndefType& other) const {
return Value::undef("operation undefined (undefined < undefined)");
}
Value UndefType::operator>(const UndefType& other) const {
return Value::undef("operation undefined (undefined > undefined)");
}
Value UndefType::operator<=(const UndefType& other) const {
return Value::undef("operation undefined (undefined <= undefined)");
}
Value UndefType::operator>=(const UndefType& other) const {
return Value::undef("operation undefined (undefined >= undefined)");
}
Value ObjectType::operator==(const ObjectType& other) const {
return Value::undef("operation undefined (object == object)");
}
Value ObjectType::operator!=(const ObjectType& other) const {
return Value::undef("operation undefined (object != object)");
}
Value ObjectType::operator<(const ObjectType& other) const {
return Value::undef("operation undefined (object < object)");
}
Value ObjectType::operator>(const ObjectType& other) const {
return Value::undef("operation undefined (object > object)");
}
Value ObjectType::operator<=(const ObjectType& other) const {
return Value::undef("operation undefined (object <= object)");
}
Value ObjectType::operator>=(const ObjectType& other) const {
return Value::undef("operation undefined (object >= object)");
}
Value VectorType::operator==(const VectorType& v) const {
size_t i = 0;
auto first1 = this->begin(), last1 = this->end(), first2 = v.begin(), last2 = v.end();
for ( ; (first1 != last1) && (first2 != last2); ++first1, ++first2, ++i) {
Value temp = *first1 == *first2;
if (temp.isUndefined()) {
temp.toUndef().append(STR("in vector comparison at index " << i));
return temp;
}
if (!temp.toBool()) return false;
}
return (first1 == last1) && (first2 == last2);
}
Value VectorType::operator!=(const VectorType& v) const {
Value temp = this->VectorType::operator==(v);
if (temp.isUndefined()) return temp;
return !temp.toBool();
}
// lexicographical compare with possible undef result
Value VectorType::operator<(const VectorType& v) const {
auto first1 = this->begin(), last1 = this->end(), first2 = v.begin(), last2 = v.end();
size_t i = 0;
for ( ; (first1 != last1) && (first2 != last2); ++first1, ++first2, ++i) {
Value temp = *first1 < *first2;
if (temp.isUndefined()) {
temp.toUndef().append(STR("in vector comparison at index " << i));
return temp;
}
if (temp.toBool()) return true;
if ((*first2 < *first1).toBool()) return false;
}
return (first1 == last1) && (first2 != last2);
}
Value VectorType::operator>(const VectorType& v) const {
return v.VectorType::operator<(*this);
}
Value VectorType::operator<=(const VectorType& v) const {
Value temp = this->VectorType::operator>(v);
if (temp.isUndefined()) return temp;
return !temp.toBool();
}
Value VectorType::operator>=(const VectorType& v) const {
Value temp = this->VectorType::operator<(v);
if (temp.isUndefined()) return temp;
return !temp.toBool();
}
class notequal_visitor : public boost::static_visitor<Value>
{
public:
template <typename T, typename U> Value operator()(const T& op1, const U& op2) const { return true; }
template <typename T> Value operator()(const T& op1, const T& op2) const { return op1 != op2; }
Value operator()(const UndefType&, const UndefType&) const { return false; }
template <typename T> Value operator()(const ValuePtr<T>& op1, const ValuePtr<T>& op2) const { return *op1 != *op2; }
};
class equals_visitor : public boost::static_visitor<Value>
{
public:
template <typename T, typename U> Value operator()(const T& op1, const U& op2) const { return false; }
template <typename T> Value operator()(const T& op1, const T& op2) const { return op1 == op2; }
Value operator()(const UndefType&, const UndefType&) const { return true; }
template <typename T> Value operator()(const ValuePtr<T>& op1, const ValuePtr<T>& op2) const { return *op1 == *op2; }
};
class less_visitor : public boost::static_visitor<Value>
{
public:
template <typename T, typename U> Value operator()(const T& op1, const U& op2) const {
return Value::undef(STR("undefined operation (" << getTypeName(op1) << " < " << getTypeName(op2) << ")"));
}
template <typename T> Value operator()(const T& op1, const T& op2) const { return op1 < op2; }
template <typename T> Value operator()(const ValuePtr<T>& op1, const ValuePtr<T>& op2) const { return *op1 < *op2; }
};
class greater_visitor : public boost::static_visitor<Value>
{
public:
template <typename T, typename U> Value operator()(const T& op1, const U& op2) const {
return Value::undef(STR("undefined operation (" << getTypeName(op1) << " > " << getTypeName(op2) << ")"));
}
template <typename T> Value operator()(const T& op1, const T& op2) const { return op1 > op2; }
template <typename T> Value operator()(const ValuePtr<T>& op1, const ValuePtr<T>& op2) const { return *op1 > *op2; }
};
class lessequal_visitor : public boost::static_visitor<Value>
{
public:
template <typename T, typename U> Value operator()(const T& op1, const U& op2) const {
return Value::undef(STR("undefined operation (" << getTypeName(op1) << " <= " << getTypeName(op2) << ")"));
}
template <typename T> Value operator()(const T& op1, const T& op2) const { return op1 <= op2; }
template <typename T> Value operator()(const ValuePtr<T>& op1, const ValuePtr<T>& op2) const { return *op1 <= *op2; }
};
class greaterequal_visitor : public boost::static_visitor<Value>
{
public:
template <typename T, typename U> Value operator()(const T& op1, const U& op2) const {
return Value::undef(STR("undefined operation (" << getTypeName(op1) << " >= " << getTypeName(op2) << ")"));
}
template <typename T> Value operator()(const T& op1, const T& op2) const { return op1 >= op2; }
template <typename T> Value operator()(const ValuePtr<T>& op1, const ValuePtr<T>& op2) const { return *op1 >= *op2; }
};
Value Value::operator==(const Value& v) const
{
return boost::apply_visitor(equals_visitor(), this->value, v.value);
}
Value Value::operator!=(const Value& v) const
{
return boost::apply_visitor(notequal_visitor(), this->value, v.value);
}
Value Value::operator<(const Value& v) const
{
return boost::apply_visitor(less_visitor(), this->value, v.value);
}
Value Value::operator>=(const Value& v) const
{
return boost::apply_visitor(greaterequal_visitor(), this->value, v.value);
}
Value Value::operator>(const Value& v) const
{
return boost::apply_visitor(greater_visitor(), this->value, v.value);
}
Value Value::operator<=(const Value& v) const
{
return boost::apply_visitor(lessequal_visitor(), this->value, v.value);
}
bool Value::cmp_less(const Value& v1, const Value& v2) {
return v1.operator<(v2).toBool();
}
class plus_visitor : public boost::static_visitor<Value>
{
public:
template <typename T, typename U> Value operator()(const T& op1, const U& op2) const {
return Value::undef(STR("undefined operation (" << getTypeName(op1) << " + " << getTypeName(op2) << ")"));
}
Value operator()(const double& op1, const double& op2) const {
return op1 + op2;
}
Value operator()(const VectorType& op1, const VectorType& op2) const {
VectorType sum(op1.evaluation_session());
// FIXME: should we really truncate to shortest vector here?
// Maybe better to either "add zeroes" and return longest
// and/or issue an warning/error about length mismatch.
for (auto it1 = op1.begin(), end1 = op1.end(), it2 = op2.begin(), end2 = op2.end();
it1 != end1 && it2 != end2;
++it1, ++it2) {
sum.emplace_back(*it1 + *it2);
}
return std::move(sum);
}
};
Value Value::operator+(const Value& v) const
{
return boost::apply_visitor(plus_visitor(), this->value, v.value);
}
class minus_visitor : public boost::static_visitor<Value>
{
public:
template <typename T, typename U> Value operator()(const T& op1, const U& op2) const {
return Value::undef(STR("undefined operation (" << getTypeName(op1) << " - " << getTypeName(op2) << ")"));
}
Value operator()(const double& op1, const double& op2) const {
return op1 - op2;
}
Value operator()(const VectorType& op1, const VectorType& op2) const {
VectorType sum(op1.evaluation_session());
for (size_t i = 0; i < op1.size() && i < op2.size(); ++i) {
sum.emplace_back(op1[i] - op2[i]);
}
return std::move(sum);
}
};
Value Value::operator-(const Value& v) const
{
return boost::apply_visitor(minus_visitor(), this->value, v.value);
}
Value multvecnum(const VectorType& vecval, const Value& numval)
{
// Vector * Number
VectorType dstv(vecval.evaluation_session());
for (const auto& val : vecval) {
dstv.emplace_back(val * numval);
}
return std::move(dstv);
}
Value multmatvec(const VectorType& matrixvec, const VectorType& vectorvec)
{
// Matrix * Vector
VectorType dstv(matrixvec.evaluation_session());
for (size_t i = 0; i < matrixvec.size(); ++i) {
if (matrixvec[i].type() != Value::Type::VECTOR ||
matrixvec[i].toVector().size() != vectorvec.size()) {
return Value::undef(STR("Matrix must be rectangular. Problem at row " << i));
}
double r_e = 0.0;
for (size_t j = 0; j < matrixvec[i].toVector().size(); ++j) {
if (matrixvec[i].toVector()[j].type() != Value::Type::NUMBER) {
return Value::undef(STR("Matrix must contain only numbers. Problem at row " << i << ", col " << j));
}
if (vectorvec[j].type() != Value::Type::NUMBER) {
return Value::undef(STR("Vector must contain only numbers. Problem at index " << j));
}
r_e += matrixvec[i].toVector()[j].toDouble() * vectorvec[j].toDouble();
}
dstv.emplace_back(Value(r_e));
}
return std::move(dstv);
}
Value multvecmat(const VectorType& vectorvec, const VectorType& matrixvec)
{
assert(vectorvec.size() == matrixvec.size());
// Vector * Matrix
VectorType dstv(matrixvec[0].toVector().evaluation_session());
size_t firstRowSize = matrixvec[0].toVector().size();
for (size_t i = 0; i < firstRowSize; ++i) {
double r_e = 0.0;
for (size_t j = 0; j < vectorvec.size(); ++j) {
if (matrixvec[j].type() != Value::Type::VECTOR ||
matrixvec[j].toVector().size() != firstRowSize) {
LOG(message_group::Warning, Location::NONE, "", "Matrix must be rectangular. Problem at row %1$lu", j);
return Value::undef(STR("Matrix must be rectangular. Problem at row " << j));
}
if (vectorvec[j].type() != Value::Type::NUMBER) {
LOG(message_group::Warning, Location::NONE, "", "Vector must contain only numbers. Problem at index %1$lu", j);
return Value::undef(STR("Vector must contain only numbers. Problem at index " << j));
}
if (matrixvec[j].toVector()[i].type() != Value::Type::NUMBER) {
LOG(message_group::Warning, Location::NONE, "", "Matrix must contain only numbers. Problem at row %1$lu, col %2$lu", j, i);
return Value::undef(STR("Matrix must contain only numbers. Problem at row " << j << ", col " << i));
}
r_e += vectorvec[j].toDouble() * matrixvec[j].toVector()[i].toDouble();
}
dstv.emplace_back(r_e);
}
return Value(std::move(dstv));
}
Value multvecvec(const VectorType& vec1, const VectorType& vec2) {
// Vector dot product.
auto r = 0.0;
for (size_t i = 0; i < vec1.size(); i++) {
if (vec1[i].type() != Value::Type::NUMBER || vec2[i].type() != Value::Type::NUMBER) {
return Value::undef(STR("undefined operation (" << vec1[i].typeName() << " * " << vec2[i].typeName() << ")"));
}
r += vec1[i].toDouble() * vec2[i].toDouble();