/
Expression.cpp
3343 lines (2909 loc) · 92.3 KB
/
Expression.cpp
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
/***************************************************************************
* Copyright (c) 2015 Eivind Kvedalen <eivind@kvedalen.name> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifdef __GNUC__
# include <unistd.h>
#endif
#if defined(__clang__)
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Wdelete-non-virtual-dtor"
#endif
#include <boost/algorithm/string/predicate.hpp>
#include <boost/io/ios_state.hpp>
#include <Base/Console.h>
#include "Base/Exception.h"
#include <Base/Interpreter.h>
#include <App/Application.h>
#include <App/Document.h>
#include <App/DocumentPy.h>
#include <App/DocumentObject.h>
#include <App/PropertyUnits.h>
#include <Base/QuantityPy.h>
#include <Base/MatrixPy.h>
#include <Base/PlacementPy.h>
#include <Base/RotationPy.h>
#include <Base/VectorPy.h>
#include <QStringList>
#include <string>
#include <sstream>
#include <math.h>
#include <stdio.h>
#include <stack>
#include <deque>
#include <algorithm>
#include "ExpressionParser.h"
#include <Base/Unit.h>
#include <App/PropertyUnits.h>
#include <App/ObjectIdentifier.h>
#include <boost/math/special_functions/round.hpp>
#include <boost/math/special_functions/trunc.hpp>
/** \defgroup Expression Expressions framework
\ingroup APP
\brief The expression system allows users to write expressions and formulas that produce values
*/
using namespace Base;
using namespace App;
FC_LOG_LEVEL_INIT("Expression",true,true)
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
#ifndef M_E
#define M_E 2.71828182845904523536
#endif
#ifndef DOUBLE_MAX
# define DOUBLE_MAX 1.7976931348623157E+308 /* max decimal value of a "double"*/
#endif
#ifndef DOUBLE_MIN
# define DOUBLE_MIN 2.2250738585072014E-308 /* min decimal value of a "double"*/
#endif
#if defined(_MSC_VER)
#define strtoll _strtoi64
#pragma warning(disable : 4003)
#pragma warning(disable : 4065)
#endif
#define __EXPR_THROW(_e,_msg,_expr) do {\
std::ostringstream ss;\
ss << _msg << (_expr);\
throw _e(ss.str().c_str());\
}while(0)
#define _EXPR_THROW(_msg,_expr) __EXPR_THROW(ExpressionError,_msg,_expr)
#define __EXPR_SET_MSG(_e,_msg,_expr) do {\
std::ostringstream ss;\
ss << _msg << _e.what() << (_expr);\
_e.setMessage(ss.str());\
}while(0)
#define _EXPR_RETHROW(_e,_msg,_expr) do {\
__EXPR_SET_MSG(_e,_msg,_expr);\
throw;\
}while(0)
#define _EXPR_PY_THROW(_msg,_expr) do {\
Base::PyException _e;\
__EXPR_SET_MSG(_e,_msg,_expr);\
_e.raiseException();\
}while(0)
#define EXPR_PY_THROW(_expr) _EXPR_PY_THROW("",_expr)
#define EXPR_THROW(_msg) _EXPR_THROW(_msg,this)
#define RUNTIME_THROW(_msg) __EXPR_THROW(Base::RuntimeError,_msg, (Expression*)0)
#define TYPE_THROW(_msg) __EXPR_THROW(Base::TypeError,_msg, (Expression*)0)
#define PARSER_THROW(_msg) __EXPR_THROW(Base::ParserError,_msg, (Expression*)0)
#define PY_THROW(_msg) __EXPR_THROW(Py::RuntimeError,_msg, (Expression*)0)
static inline std::ostream &operator<<(std::ostream &os, const App::Expression *expr) {
if(expr) {
os << std::endl;
expr->toString(os);
}
return os;
}
template<typename T>
void copy_vector(T &dst, const T& src) {
dst.clear();
dst.reserve(src.size());
for(auto &s : src) {
if(s)
dst.push_back(s->copy());
else
dst.emplace_back();
}
}
////////////////////////////////////////////////////////////////////////////////
// WARNING! The following define enables slightly faster any type comparison which
// is not standard conforming, and may break in some rare cases (although not likely)
//
// #define USE_FAST_ANY
static inline bool is_type(const App::any &value, const std::type_info& t) {
#ifdef USE_FAST_ANY
return &value.type() == &t;
#else
return value.type() == t;
#endif
}
template<class T>
static inline const T &cast(const App::any &value) {
#ifdef USE_FAST_ANY
return *value.cast<T>();
#else
return App::any_cast<const T&>(value);
#endif
}
template<class T>
static inline T &cast(App::any &value) {
#ifdef USE_FAST_ANY
return *value.cast<T>();
#else
return App::any_cast<T&>(value);
#endif
}
template<class T>
static inline T &&cast(App::any &&value) {
#ifdef USE_FAST_ANY
return std::move(*value.cast<T>());
#else
return App::any_cast<T&&>(std::move(value));
#endif
}
std::string unquote(const std::string & input)
{
assert(input.size() >= 4);
std::string output;
std::string::const_iterator cur = input.begin() + 2;
std::string::const_iterator end = input.end() - 2;
output.reserve(input.size());
bool escaped = false;
while (cur != end) {
if (escaped) {
switch (*cur) {
case 't':
output += '\t';
break;
case 'n':
output += '\n';
break;
case 'r':
output += '\r';
break;
case '\\':
output += '\\';
break;
case '\'':
output += '\'';
break;
case '"':
output += '"';
break;
}
escaped = false;
}
else {
if (*cur == '\\')
escaped = true;
else
output += *cur;
}
++cur;
}
return output;
}
////////////////////////////////////////////////////////////////////////////////////
//
// ExpressionVistor
//
void ExpressionVisitor::getDeps(Expression &e, ExpressionDeps &deps) {
e._getDeps(deps);
}
void ExpressionVisitor::getDepObjects(Expression &e,
std::set<App::DocumentObject*> &deps, std::vector<std::string> *labels)
{
e._getDepObjects(deps,labels);
}
void ExpressionVisitor::getIdentifiers(Expression &e, std::set<App::ObjectIdentifier> &ids) {
e._getIdentifiers(ids);
}
bool ExpressionVisitor::adjustLinks(Expression &e, const std::set<App::DocumentObject*> &inList) {
return e._adjustLinks(inList,*this);
}
void ExpressionVisitor::importSubNames(Expression &e, const ObjectIdentifier::SubNameMap &subNameMap) {
e._importSubNames(subNameMap);
}
void ExpressionVisitor::updateLabelReference(Expression &e,
DocumentObject *obj, const std::string &ref, const char *newLabel)
{
e._updateLabelReference(obj,ref,newLabel);
}
bool ExpressionVisitor::updateElementReference(Expression &e, App::DocumentObject *feature, bool reverse) {
return e._updateElementReference(feature,reverse,*this);
}
bool ExpressionVisitor::relabeledDocument(
Expression &e, const std::string &oldName, const std::string &newName)
{
return e._relabeledDocument(oldName,newName,*this);
}
bool ExpressionVisitor::renameObjectIdentifier(Expression &e,
const std::map<ObjectIdentifier,ObjectIdentifier> &paths, const ObjectIdentifier &path)
{
return e._renameObjectIdentifier(paths,path,*this);
}
void ExpressionVisitor::collectReplacement(Expression &e,
std::map<ObjectIdentifier,ObjectIdentifier> &paths,
const App::DocumentObject *parent, App::DocumentObject *oldObj, App::DocumentObject *newObj) const
{
return e._collectReplacement(paths,parent,oldObj,newObj);
}
void ExpressionVisitor::moveCells(Expression &e, const CellAddress &address, int rowCount, int colCount) {
e._moveCells(address,rowCount,colCount,*this);
}
void ExpressionVisitor::offsetCells(Expression &e, int rowOffset, int colOffset) {
e._offsetCells(rowOffset,colOffset,*this);
}
/////////////////////////////////////////////////////////////////////////////////////
// Helper functions
/* The following definitions are from The art of computer programming by Knuth
* (copied from http://stackoverflow.com/questions/17333/most-effective-way-for-float-and-double-comparison)
*/
/*
static bool approximatelyEqual(double a, double b, double epsilon)
{
return fabs(a - b) <= ( (fabs(a) < fabs(b) ? fabs(b) : fabs(a)) * epsilon);
}
*/
template<class T>
static inline bool essentiallyEqual(T a, T b)
{
static const T _epsilon = std::numeric_limits<T>::epsilon();
return std::fabs(a - b) <= ( (std::fabs(a) > std::fabs(b) ? std::fabs(b) : std::fabs(a)) * _epsilon);
}
template<class T>
inline bool essentiallyZero(T a) {
return !a;
}
template<>
inline bool essentiallyZero(double a) {
return essentiallyEqual(a, 0.0);
}
template<>
inline bool essentiallyZero(float a) {
return essentiallyEqual(a, 0.0f);
}
template<class T>
static inline bool definitelyGreaterThan(T a, T b)
{
static const T _epsilon = std::numeric_limits<T>::epsilon();
return (a - b) > ( (std::fabs(a) < std::fabs(b) ? std::fabs(b) : std::fabs(a)) * _epsilon);
}
template<class T>
static inline bool definitelyLessThan(T a, T b)
{
static const T _epsilon = std::numeric_limits<T>::epsilon();
return (b - a) > ( (std::fabs(a) < std::fabs(b) ? std::fabs(b) : std::fabs(a)) * _epsilon);
}
static inline int essentiallyInteger(double a, long &l, int &i) {
double intpart;
if (std::modf(a,&intpart) == 0.0) {
if (intpart<0.0) {
if (intpart >= INT_MIN) {
i = static_cast<int>(intpart);
l = i;
return 1;
}
if (intpart >= LONG_MIN) {
l = static_cast<long>(intpart);
return 2;
}
}
else if (intpart <= INT_MAX) {
i = static_cast<int>(intpart);
l = i;
return 1;
}
else if (intpart <= static_cast<double>(LONG_MAX)) {
l = static_cast<int>(intpart);
return 2;
}
}
return 0;
}
static inline bool essentiallyInteger(double a, long &l) {
double intpart;
if (std::modf(a,&intpart) == 0.0) {
if (intpart<0.0) {
if (intpart >= LONG_MIN) {
l = static_cast<long>(intpart);
return true;
}
}
else if (intpart <= static_cast<double>(LONG_MAX)) {
l = static_cast<long>(intpart);
return true;
}
}
return false;
}
// This class is intended to be contained inside App::any (via a shared_ptr)
// without holding Python global lock
struct PyObjectWrapper {
public:
typedef std::shared_ptr<PyObjectWrapper> Pointer;
PyObjectWrapper(PyObject *obj):pyobj(obj) {
Py::_XINCREF(pyobj);
}
~PyObjectWrapper() {
if(pyobj) {
Base::PyGILStateLocker lock;
Py::_XDECREF(pyobj);
}
}
PyObjectWrapper(const PyObjectWrapper &) = delete;
PyObjectWrapper &operator=(const PyObjectWrapper &) = delete;
Py::Object get() const {
if(!pyobj)
return Py::Object();
return Py::Object(const_cast<PyObject*>(pyobj));
}
private:
PyObject *pyobj;
};
static inline PyObjectWrapper::Pointer pyObjectWrap(PyObject *obj) {
return std::make_shared<PyObjectWrapper>(obj);
}
static inline bool isAnyPyObject(const App::any &value) {
return is_type(value,typeid(PyObjectWrapper::Pointer));
}
static inline Py::Object __pyObjectFromAny(const App::any &value) {
return cast<PyObjectWrapper::Pointer>(value)->get();
}
static Py::Object _pyObjectFromAny(const App::any &value, const Expression *e) {
if(value.empty())
return Py::Object();
else if (isAnyPyObject(value))
return __pyObjectFromAny(value);
if (is_type(value,typeid(Quantity)))
return Py::asObject(new QuantityPy(new Quantity(cast<Quantity>(value))));
else if (is_type(value,typeid(double)))
return Py::Float(cast<double>(value));
else if (is_type(value,typeid(float)))
return Py::Float(cast<float>(value));
else if (is_type(value,typeid(int)))
return Py::Long(cast<int>(value));
else if (is_type(value,typeid(long))) {
return Py::Long(cast<long>(value));
} else if (is_type(value,typeid(bool)))
return Py::Boolean(cast<bool>(value));
else if (is_type(value,typeid(std::string)))
return Py::String(cast<string>(value));
else if (is_type(value,typeid(const char*)))
return Py::String(cast<const char*>(value));
_EXPR_THROW("Unknown type", e);
}
namespace App {
Py::Object pyObjectFromAny(const App::any &value) {
return _pyObjectFromAny(value,0);
}
App::any pyObjectToAny(Py::Object value, bool check) {
if(value.isNone())
return App::any();
PyObject *pyvalue = value.ptr();
if(!check)
return App::any(pyObjectWrap(pyvalue));
if (PyObject_TypeCheck(pyvalue, &Base::QuantityPy::Type)) {
Base::QuantityPy * qp = static_cast<Base::QuantityPy*>(pyvalue);
Base::Quantity * q = qp->getQuantityPtr();
return App::any(*q);
}
if (PyFloat_Check(pyvalue))
return App::any(PyFloat_AsDouble(pyvalue));
if (PyLong_Check(pyvalue))
return App::any(PyLong_AsLong(pyvalue));
else if (PyUnicode_Check(pyvalue)) {
const char* value = PyUnicode_AsUTF8(pyvalue);
if (!value) {
FC_THROWM(Base::ValueError, "Invalid unicode string");
}
return App::any(std::string(value));
}
else {
return App::any(pyObjectWrap(pyvalue));
}
}
bool pyToQuantity(Quantity &q, const Py::Object &pyobj) {
if (PyObject_TypeCheck(*pyobj, &Base::QuantityPy::Type))
q = *static_cast<Base::QuantityPy*>(*pyobj)->getQuantityPtr();
else if (PyFloat_Check(*pyobj))
q = Quantity(PyFloat_AsDouble(*pyobj));
else if (PyLong_Check(*pyobj))
q = Quantity(PyLong_AsLong(*pyobj));
else
return false;
return true;
}
static inline Quantity pyToQuantity(const Py::Object &pyobj,
const Expression *e, const char *msg=0)
{
Quantity q;
if(!pyToQuantity(q,pyobj)) {
if(!msg)
msg = "Failed to convert to Quantity.";
__EXPR_THROW(TypeError,msg,e);
}
return q;
}
Py::Object pyFromQuantity(const Quantity &quantity) {
if(!quantity.getUnit().isEmpty())
return Py::asObject(new QuantityPy(new Quantity(quantity)));
double v = quantity.getValue();
long l;
int i;
switch(essentiallyInteger(v,l,i)) {
case 1:
#if PY_MAJOR_VERSION < 3
return Py::Int(i);
#endif
case 2:
return Py::Long(l);
default:
return Py::Float(v);
}
}
Quantity anyToQuantity(const App::any &value, const char *msg) {
if (is_type(value,typeid(Quantity))) {
return cast<Quantity>(value);
} else if (is_type(value,typeid(bool))) {
return Quantity(cast<bool>(value)?1.0:0.0);
} else if (is_type(value,typeid(int))) {
return Quantity(cast<int>(value));
} else if (is_type(value,typeid(long))) {
return Quantity(cast<long>(value));
} else if (is_type(value,typeid(float))) {
return Quantity(cast<float>(value));
} else if (is_type(value,typeid(double))) {
return Quantity(cast<double>(value));
}
if(!msg)
msg = "Failed to convert to Quantity";
TYPE_THROW(msg);
}
static inline bool anyToLong(long &res, const App::any &value) {
if (is_type(value,typeid(int))) {
res = cast<int>(value);
} else if (is_type(value,typeid(long))) {
res = cast<long>(value);
} else if (is_type(value,typeid(bool)))
res = cast<bool>(value)?1:0;
else
return false;
return true;
}
static inline bool anyToDouble(double &res, const App::any &value) {
if (is_type(value,typeid(double)))
res = cast<double>(value);
else if (is_type(value,typeid(float)))
res = cast<float>(value);
else if (is_type(value,typeid(long)))
res = cast<long>(value);
else if (is_type(value,typeid(int)))
res = cast<int>(value);
else if (is_type(value,typeid(bool)))
res = cast<bool>(value)?1:0;
else
return false;
return true;
}
bool isAnyEqual(const App::any &v1, const App::any &v2) {
if(v1.empty())
return v2.empty();
else if(v2.empty())
return false;
if(!is_type(v1,v2.type())) {
if(is_type(v1,typeid(Quantity)))
return cast<Quantity>(v1) == anyToQuantity(v2);
else if(is_type(v2,typeid(Quantity)))
return anyToQuantity(v1) == cast<Quantity>(v2);
long l1,l2;
double d1,d2;
if(anyToLong(l1,v1)) {
if(anyToLong(l2,v2))
return l1==l2;
else if(anyToDouble(d2,v2))
return essentiallyEqual((double)l1,d2);
else
return false;
}else if(anyToDouble(d1,v1))
return anyToDouble(d2,v2) && essentiallyEqual(d1,d2);
if(is_type(v1,typeid(std::string))) {
if(is_type(v2,typeid(const char*))) {
auto c = cast<const char*>(v2);
return c && cast<std::string>(v1)==c;
}
return false;
}else if(is_type(v1,typeid(const char*))) {
if(is_type(v2,typeid(std::string))) {
auto c = cast<const char*>(v1);
return c && cast<std::string>(v2)==c;
}
return false;
}
}
if (is_type(v1,typeid(int)))
return cast<int>(v1) == cast<int>(v2);
if (is_type(v1,typeid(long)))
return cast<long>(v1) == cast<long>(v2);
if (is_type(v1,typeid(std::string)))
return cast<std::string>(v1) == cast<std::string>(v2);
if (is_type(v1,typeid(const char*))) {
auto c1 = cast<const char*>(v1);
auto c2 = cast<const char*>(v2);
return c1==c2 || (c1 && c2 && strcmp(c1,c2)==0);
}
if (is_type(v1,typeid(bool)))
return cast<bool>(v1) == cast<bool>(v2);
if (is_type(v1,typeid(double)))
return essentiallyEqual(cast<double>(v1), cast<double>(v2));
if (is_type(v1,typeid(float)))
return essentiallyEqual(cast<float>(v1), cast<float>(v2));
if (is_type(v1,typeid(Quantity)))
return cast<Quantity>(v1) == cast<Quantity>(v2);
if (!isAnyPyObject(v1))
throw Base::TypeError("Unknown type");
Base::PyGILStateLocker lock;
Py::Object o1 = __pyObjectFromAny(v1);
Py::Object o2 = __pyObjectFromAny(v2);
if(!o1.isType(o2.type()))
return false;
int res = PyObject_RichCompareBool(o1.ptr(),o2.ptr(),Py_EQ);
if(res<0)
PyException::ThrowException();
return !!res;
}
Expression* expressionFromPy(const DocumentObject *owner, const Py::Object &value) {
if (value.isNone())
return new PyObjectExpression(owner);
if(value.isString()) {
return new StringExpression(owner,value.as_string());
} else if (PyObject_TypeCheck(value.ptr(),&QuantityPy::Type)) {
return new NumberExpression(owner,
*static_cast<QuantityPy*>(value.ptr())->getQuantityPtr());
} else if (value.isBoolean()) {
if(value.isTrue())
return new ConstantExpression(owner,"True",Quantity(1.0));
else
return new ConstantExpression(owner,"False",Quantity(0.0));
} else {
Quantity q;
if(pyToQuantity(q,value))
return new NumberExpression(owner,q);
}
return new PyObjectExpression(owner,value.ptr());
}
} // namespace App
//
// Expression component
//
Expression::Component::Component(const std::string &n)
:comp(ObjectIdentifier::SimpleComponent(n))
,e1(0) ,e2(0) ,e3(0)
{}
Expression::Component::Component(Expression *_e1, Expression *_e2, Expression *_e3, bool isRange)
:e1(_e1) ,e2(_e2) ,e3(_e3)
{
if(isRange || e2 || e3)
comp = ObjectIdentifier::RangeComponent(0);
}
Expression::Component::Component(const ObjectIdentifier::Component &comp)
:comp(comp)
,e1(0) ,e2(0) ,e3(0)
{}
Expression::Component::Component(const Component &other)
:comp(other.comp)
,e1(other.e1?other.e1->copy():0)
,e2(other.e2?other.e2->copy():0)
,e3(other.e3?other.e3->copy():0)
{}
Expression::Component::~Component()
{
delete e1;
delete e2;
delete e3;
}
Expression::Component* Expression::Component::copy() const {
return new Component(*this);
}
Expression::Component* Expression::Component::eval() const {
auto res = new Component(comp);
if(e1) res->e1 = e1->eval();
if(e2) res->e2 = e2->eval();
if(e3) res->e3 = e3->eval();
return res;
}
Py::Object Expression::Component::get(const Expression *owner, const Py::Object &pyobj) const {
try {
if(!e1 && !e2 && !e3)
return comp.get(pyobj);
if(!comp.isRange() && !e2 && !e3) {
auto index = e1->getPyValue();
Py::Object res;
if(pyobj.isMapping())
res = Py::Mapping(pyobj).getItem(index);
else {
Py_ssize_t i = PyNumber_AsSsize_t(index.ptr(), PyExc_IndexError);
if(PyErr_Occurred())
throw Py::Exception();
res = Py::Sequence(pyobj).getItem(i);
}
if(!res.ptr())
throw Py::Exception();
return res;
}else{
Py::Object v1,v2,v3;
if(e1) v1 = e1->getPyValue();
if(e2) v2 = e2->getPyValue();
if(e3) v3 = e3->getPyValue();
PyObject *s = PySlice_New(e1?v1.ptr():nullptr,
e2?v2.ptr():nullptr,
e3?v3.ptr():nullptr);
if(!s)
throw Py::Exception();
Py::Object slice(s,true);
PyObject *res = PyObject_GetItem(pyobj.ptr(),slice.ptr());
if(!res)
throw Py::Exception();
return Py::asObject(res);
}
}catch(Py::Exception &) {
EXPR_PY_THROW(owner);
}
return Py::Object();
}
void Expression::Component::set(const Expression *owner, Py::Object &pyobj, const Py::Object &value) const
{
if(!e1 && !e2 && !e3)
return comp.set(pyobj,value);
try {
if(!comp.isRange() && !e2 && !e3) {
auto index = e1->getPyValue();
if(pyobj.isMapping())
Py::Mapping(pyobj).setItem(index,value);
else {
Py_ssize_t i = PyNumber_AsSsize_t(pyobj.ptr(), PyExc_IndexError);
if(PyErr_Occurred() || PySequence_SetItem(pyobj.ptr(),i,value.ptr())==-1)
throw Py::Exception();
}
}else{
Py::Object v1,v2,v3;
if(e1) v1 = e1->getPyValue();
if(e2) v2 = e2->getPyValue();
if(e3) v3 = e3->getPyValue();
PyObject *s = PySlice_New(e1?v1.ptr():nullptr,
e2?v2.ptr():nullptr,
e3?v3.ptr():nullptr);
if(!s)
throw Py::Exception();
Py::Object slice(s,true);
if(PyObject_SetItem(pyobj.ptr(),slice.ptr(),value.ptr())<0)
throw Py::Exception();
}
}catch(Py::Exception &) {
EXPR_PY_THROW(owner);
}
}
void Expression::Component::del(const Expression *owner, Py::Object &pyobj) const {
try {
if (!e1 && !e2 && !e3) {
comp.del(pyobj);
}
else if (!comp.isRange() && !e2 && !e3) {
auto index = e1->getPyValue();
if (pyobj.isMapping()) {
Py::Mapping(pyobj).delItem(index);
}
else {
Py_ssize_t i = PyNumber_AsSsize_t(pyobj.ptr(), PyExc_IndexError);
if (PyErr_Occurred() || PySequence_DelItem(pyobj.ptr(),i)==-1)
throw Py::Exception();
}
}
else {
Py::Object v1,v2,v3;
if(e1) v1 = e1->getPyValue();
if(e2) v2 = e2->getPyValue();
if(e3) v3 = e3->getPyValue();
PyObject *s = PySlice_New(e1?v1.ptr():nullptr,
e2?v2.ptr():nullptr,
e3?v3.ptr():nullptr);
if (!s)
throw Py::Exception();
Py::Object slice(s,true);
if (PyObject_DelItem(pyobj.ptr(),slice.ptr())<0)
throw Py::Exception();
}
}
catch(Py::Exception &) {
EXPR_PY_THROW(owner);
}
}
void Expression::Component::visit(ExpressionVisitor &v) {
if(e1) e1->visit(v);
if(e2) e2->visit(v);
if(e3) e3->visit(v);
}
bool Expression::Component::isTouched() const {
return (e1&&e1->isTouched()) ||
(e2&&e2->isTouched()) ||
(e3&&e3->isTouched());
}
void Expression::Component::toString(std::ostream &ss, bool persistent) const {
if(!e1 && !e2 && !e3) {
if(comp.isSimple())
ss << '.';
comp.toString(ss,!persistent);
return;
}
ss << '[';
if(e1)
e1->toString(ss,persistent);
if(e2 || comp.isRange())
ss << ':';
if(e2)
e2->toString(ss,persistent);
if(e3) {
ss << ':';
e3->toString(ss,persistent);
}
ss << ']';
}
//
// Expression base-class
//
TYPESYSTEM_SOURCE_ABSTRACT(App::Expression, Base::BaseClass)
Expression::Expression(const DocumentObject *_owner)
: owner(const_cast<App::DocumentObject*>(_owner))
{
}
Expression::~Expression()
{
for(auto c : components)
delete c;
}
Expression::Component* Expression::createComponent(const std::string &n) {
return new Component(n);
}
Expression::Component* Expression::createComponent(
Expression* e1, Expression* e2, Expression* e3, bool isRange)
{
return new Component(e1,e2,e3,isRange);
}
int Expression::priority() const {
return 20;
}
Expression * Expression::parse(const DocumentObject *owner, const std::string &buffer)
{
return ExpressionParser::parse(owner, buffer.c_str());
}
class GetDepsExpressionVisitor : public ExpressionVisitor {
public:
GetDepsExpressionVisitor(ExpressionDeps &deps)
:deps(deps)
{}
virtual void visit(Expression &e) {
this->getDeps(e,deps);
}
ExpressionDeps &deps;
};
void Expression::getDeps(ExpressionDeps &deps) const {
GetDepsExpressionVisitor v(deps);
const_cast<Expression*>(this)->visit(v);
}
ExpressionDeps Expression::getDeps() const {
ExpressionDeps deps;
getDeps(deps);
return deps;
}
class GetDepObjsExpressionVisitor : public ExpressionVisitor {
public:
GetDepObjsExpressionVisitor(std::set<App::DocumentObject*> &deps, std::vector<std::string> *labels)
:deps(deps),labels(labels)
{}
virtual void visit(Expression &e) {
this->getDepObjects(e,deps,labels);
}
std::set<App::DocumentObject*> &deps;
std::vector<std::string> *labels;
};
void Expression::getDepObjects(std::set<App::DocumentObject*> &deps, std::vector<std::string> *labels) const {
GetDepObjsExpressionVisitor v(deps,labels);
const_cast<Expression *>(this)->visit(v);
}
std::set<App::DocumentObject*> Expression::getDepObjects(std::vector<std::string> *labels) const {
std::set<App::DocumentObject*> deps;
getDepObjects(deps,labels);
return deps;
}
class GetIdentifiersExpressionVisitor : public ExpressionVisitor {
public:
GetIdentifiersExpressionVisitor(std::set<App::ObjectIdentifier> &deps)
:deps(deps)
{}
virtual void visit(Expression &e) {
this->getIdentifiers(e,deps);
}
std::set<App::ObjectIdentifier> &deps;
};
void Expression::getIdentifiers(std::set<App::ObjectIdentifier> &deps) const {
GetIdentifiersExpressionVisitor v(deps);
const_cast<Expression*>(this)->visit(v);
}
std::set<App::ObjectIdentifier> Expression::getIdentifiers() const {
std::set<App::ObjectIdentifier> deps;
getIdentifiers(deps);
return deps;
}
class AdjustLinksExpressionVisitor : public ExpressionVisitor {
public:
AdjustLinksExpressionVisitor(const std::set<App::DocumentObject*> &inList)
:inList(inList),res(false)
{}
virtual void visit(Expression &e) {
if(this->adjustLinks(e,inList))
res = true;
}
const std::set<App::DocumentObject*> &inList;
bool res;
};
bool Expression::adjustLinks(const std::set<App::DocumentObject*> &inList) {
AdjustLinksExpressionVisitor v(inList);