| 1 |
/*************************************************************************** |
| 2 |
* Copyright (c) 2015 Eivind Kvedalen <[email protected]> * |
| 3 |
* * |
| 4 |
* This file is part of the FreeCAD CAx development system. * |
| 5 |
* * |
| 6 |
* This library is free software; you can redistribute it and/or * |
| 7 |
* modify it under the terms of the GNU Library General Public * |
| 8 |
* License as published by the Free Software Foundation; either * |
| 9 |
* version 2 of the License, or (at your option) any later version. * |
| 10 |
* * |
| 11 |
* This library is distributed in the hope that it will be useful, * |
| 12 |
* but WITHOUT ANY WARRANTY; without even the implied warranty of * |
| 13 |
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * |
| 14 |
* GNU Library General Public License for more details. * |
| 15 |
* * |
| 16 |
* You should have received a copy of the GNU Library General Public * |
| 17 |
* License along with this library; see the file COPYING.LIB. If not, * |
| 18 |
* write to the Free Software Foundation, Inc., 59 Temple Place, * |
| 19 |
* Suite 330, Boston, MA 02111-1307, USA * |
| 20 |
* * |
| 21 |
***************************************************************************/ |
| 22 |
|
| 23 |
#ifdef __GNUC__ |
| 24 |
# include <unistd.h> |
| 25 |
#endif |
| 26 |
|
| 27 |
#if defined(__clang__) |
| 28 |
# pragma clang diagnostic push |
| 29 |
# pragma clang diagnostic ignored "-Wdelete-non-virtual-dtor" |
| 30 |
#endif |
| 31 |
|
| 32 |
#include <boost/algorithm/string/predicate.hpp> |
| 33 |
#include <boost/io/ios_state.hpp> |
| 34 |
#include <boost/math/special_functions/round.hpp> |
| 35 |
#include <boost/math/special_functions/trunc.hpp> |
| 36 |
|
| 37 |
#include <numbers> |
| 38 |
#include <limits> |
| 39 |
#include <sstream> |
| 40 |
#include <stack> |
| 41 |
#include <string> |
| 42 |
#include <fmt/format.h> |
| 43 |
|
| 44 |
#include <App/Application.h> |
| 45 |
#include <App/DocumentObject.h> |
| 46 |
#include <App/ObjectIdentifier.h> |
| 47 |
#include <App/PropertyUnits.h> |
| 48 |
#include <Base/Interpreter.h> |
| 49 |
#include <Base/MatrixPy.h> |
| 50 |
#include <Base/PlacementPy.h> |
| 51 |
#include <Base/QuantityPy.h> |
| 52 |
#include <Base/RotationPy.h> |
| 53 |
#include <Base/Tools.h> |
| 54 |
#include <Base/VectorPy.h> |
| 55 |
#include <Base/Precision.h> |
| 56 |
|
| 57 |
#include "ExpressionParser.h" |
| 58 |
|
| 59 |
|
| 60 |
using namespace Base; |
| 61 |
using namespace App; |
| 62 |
|
| 63 |
FC_LOG_LEVEL_INIT("Expression", true, true) |
| 64 |
|
| 65 |
#if defined(_MSC_VER) |
| 66 |
#define strtoll _strtoi64 |
| 67 |
#pragma warning(disable : 4003) |
| 68 |
#pragma warning(disable : 4065) |
| 69 |
#endif |
| 70 |
|
| 71 |
#define __EXPR_THROW(_e,_msg,_expr) do {\ |
| 72 |
std::ostringstream ss;\ |
| 73 |
ss << _msg << (_expr);\ |
| 74 |
throw _e(ss.str().c_str());\ |
| 75 |
}while(0) |
| 76 |
|
| 77 |
#define _EXPR_THROW(_msg,_expr) __EXPR_THROW(ExpressionError,_msg,_expr) |
| 78 |
|
| 79 |
#define __EXPR_SET_MSG(_e,_msg,_expr) do {\ |
| 80 |
std::ostringstream ss;\ |
| 81 |
ss << _msg << _e.what() << (_expr);\ |
| 82 |
_e.setMessage(ss.str());\ |
| 83 |
}while(0) |
| 84 |
|
| 85 |
#define _EXPR_RETHROW(_e,_msg,_expr) do {\ |
| 86 |
__EXPR_SET_MSG(_e,_msg,_expr);\ |
| 87 |
throw;\ |
| 88 |
}while(0) |
| 89 |
|
| 90 |
#define _EXPR_PY_THROW(_msg,_expr) do {\ |
| 91 |
Base::PyException _e;\ |
| 92 |
__EXPR_SET_MSG(_e,_msg,_expr);\ |
| 93 |
_e.raiseException();\ |
| 94 |
}while(0) |
| 95 |
|
| 96 |
#define EXPR_PY_THROW(_expr) _EXPR_PY_THROW("", _expr) |
| 97 |
|
| 98 |
#define EXPR_THROW(_msg) _EXPR_THROW(_msg, this) |
| 99 |
|
| 100 |
#define ARGUMENT_THROW(_msg) EXPR_THROW("Invalid number of arguments: " _msg) |
| 101 |
|
| 102 |
#define RUNTIME_THROW(_msg) __EXPR_THROW(Base::RuntimeError, _msg, static_cast<Expression*>(nullptr)) |
| 103 |
|
| 104 |
#define TYPE_THROW(_msg) __EXPR_THROW(Base::TypeError, _msg, static_cast<Expression*>(nullptr)) |
| 105 |
|
| 106 |
#define PARSER_THROW(_msg) __EXPR_THROW(Base::ParserError, _msg, static_cast<Expression*>(nullptr)) |
| 107 |
|
| 108 |
#define PY_THROW(_msg) __EXPR_THROW(Py::RuntimeError, _msg, static_cast<Expression*>(nullptr)) |
| 109 |
|
| 110 |
static inline std::ostream &operator<<(std::ostream &os, const App::Expression *expr) { |
| 111 |
if(expr) { |
| 112 |
os << "\nin expression: "; |
| 113 |
expr->toString(os); |
| 114 |
} |
| 115 |
return os; |
| 116 |
} |
| 117 |
|
| 118 |
template<typename T> |
| 119 |
void copy_vector(T &dst, const T& src) { |
| 120 |
dst.clear(); |
| 121 |
dst.reserve(src.size()); |
| 122 |
for(auto &s : src) { |
| 123 |
if(s) |
| 124 |
dst.push_back(s->copy()); |
| 125 |
else |
| 126 |
dst.emplace_back(); |
| 127 |
} |
| 128 |
} |
| 129 |
|
| 130 |
//////////////////////////////////////////////////////////////////////////////// |
| 131 |
|
| 132 |
// WARNING! The following define enables slightly faster any type comparison which |
| 133 |
// is not standard conforming, and may break in some rare cases (although not likely) |
| 134 |
// |
| 135 |
// #define USE_FAST_ANY |
| 136 |
|
| 137 |
static inline bool is_type(const App::any &value, const std::type_info& t) { |
| 138 |
#ifdef USE_FAST_ANY |
| 139 |
return &value.type() == &t; |
| 140 |
#else |
| 141 |
return value.type() == t; |
| 142 |
#endif |
| 143 |
} |
| 144 |
|
| 145 |
template<class T> |
| 146 |
static inline const T &cast(const App::any &value) { |
| 147 |
#ifdef USE_FAST_ANY |
| 148 |
return *value.cast<T>(); |
| 149 |
#else |
| 150 |
return App::any_cast<const T&>(value); |
| 151 |
#endif |
| 152 |
} |
| 153 |
|
| 154 |
template<class T> |
| 155 |
static inline T &cast(App::any &value) { |
| 156 |
#ifdef USE_FAST_ANY |
| 157 |
return *value.cast<T>(); |
| 158 |
#else |
| 159 |
return App::any_cast<T&>(value); |
| 160 |
#endif |
| 161 |
} |
| 162 |
|
| 163 |
template<class T> |
| 164 |
static inline T &&cast(App::any &&value) { |
| 165 |
#ifdef USE_FAST_ANY |
| 166 |
return std::move(*value.cast<T>()); |
| 167 |
#else |
| 168 |
return App::any_cast<T&&>(std::move(value)); |
| 169 |
#endif |
| 170 |
} |
| 171 |
|
| 172 |
namespace |
| 173 |
{ |
| 174 |
|
| 175 |
inline bool asBool(double value) { |
| 176 |
return std::fabs(value) >= Base::Precision::Confusion(); |
| 177 |
} |
| 178 |
|
| 179 |
} |
| 180 |
|
| 181 |
std::string unquote(const std::string & input) |
| 182 |
{ |
| 183 |
assert(input.size() >= 4); |
| 184 |
|
| 185 |
std::string output; |
| 186 |
std::string::const_iterator cur = input.begin() + 2; |
| 187 |
std::string::const_iterator end = input.end() - 2; |
| 188 |
|
| 189 |
output.reserve(input.size()); |
| 190 |
|
| 191 |
bool escaped = false; |
| 192 |
while (cur != end) { |
| 193 |
if (escaped) { |
| 194 |
switch (*cur) { |
| 195 |
case 't': |
| 196 |
output += '\t'; |
| 197 |
break; |
| 198 |
case 'n': |
| 199 |
output += '\n'; |
| 200 |
break; |
| 201 |
case 'r': |
| 202 |
output += '\r'; |
| 203 |
break; |
| 204 |
case '\\': |
| 205 |
output += '\\'; |
| 206 |
break; |
| 207 |
case '\'': |
| 208 |
output += '\''; |
| 209 |
break; |
| 210 |
case '"': |
| 211 |
output += '"'; |
| 212 |
break; |
| 213 |
} |
| 214 |
escaped = false; |
| 215 |
} |
| 216 |
else { |
| 217 |
if (*cur == '\\') |
| 218 |
escaped = true; |
| 219 |
else |
| 220 |
output += *cur; |
| 221 |
} |
| 222 |
++cur; |
| 223 |
} |
| 224 |
|
| 225 |
return output; |
| 226 |
} |
| 227 |
|
| 228 |
//////////////////////////////////////////////////////////////////////////////////// |
| 229 |
// |
| 230 |
// ExpressionVistor |
| 231 |
// |
| 232 |
void ExpressionVisitor::getIdentifiers(Expression &e, std::map<App::ObjectIdentifier,bool> &ids) { |
| 233 |
e._getIdentifiers(ids); |
| 234 |
} |
| 235 |
|
| 236 |
bool ExpressionVisitor::adjustLinks(Expression &e, const std::set<App::DocumentObject*> &inList) { |
| 237 |
return e._adjustLinks(inList,*this); |
| 238 |
} |
| 239 |
|
| 240 |
void ExpressionVisitor::importSubNames(Expression &e, const ObjectIdentifier::SubNameMap &subNameMap) { |
| 241 |
e._importSubNames(subNameMap); |
| 242 |
} |
| 243 |
|
| 244 |
void ExpressionVisitor::updateLabelReference(Expression &e, |
| 245 |
DocumentObject *obj, const std::string &ref, const char *newLabel) |
| 246 |
{ |
| 247 |
e._updateLabelReference(obj,ref,newLabel); |
| 248 |
} |
| 249 |
|
| 250 |
bool ExpressionVisitor::updateElementReference(Expression &e, App::DocumentObject *feature, bool reverse) { |
| 251 |
return e._updateElementReference(feature,reverse,*this); |
| 252 |
} |
| 253 |
|
| 254 |
bool ExpressionVisitor::relabeledDocument( |
| 255 |
Expression &e, const std::string &oldName, const std::string &newName) |
| 256 |
{ |
| 257 |
return e._relabeledDocument(oldName,newName,*this); |
| 258 |
} |
| 259 |
|
| 260 |
bool ExpressionVisitor::renameObjectIdentifier(Expression &e, |
| 261 |
const std::map<ObjectIdentifier,ObjectIdentifier> &paths, const ObjectIdentifier &path) |
| 262 |
{ |
| 263 |
return e._renameObjectIdentifier(paths,path,*this); |
| 264 |
} |
| 265 |
|
| 266 |
void ExpressionVisitor::collectReplacement(Expression &e, |
| 267 |
std::map<ObjectIdentifier,ObjectIdentifier> &paths, |
| 268 |
const App::DocumentObject *parent, App::DocumentObject *oldObj, App::DocumentObject *newObj) const |
| 269 |
{ |
| 270 |
return e._collectReplacement(paths,parent,oldObj,newObj); |
| 271 |
} |
| 272 |
|
| 273 |
void ExpressionVisitor::moveCells(Expression &e, const CellAddress &address, int rowCount, int colCount) { |
| 274 |
e._moveCells(address,rowCount,colCount,*this); |
| 275 |
} |
| 276 |
|
| 277 |
void ExpressionVisitor::offsetCells(Expression &e, int rowOffset, int colOffset) { |
| 278 |
e._offsetCells(rowOffset,colOffset,*this); |
| 279 |
} |
| 280 |
|
| 281 |
///////////////////////////////////////////////////////////////////////////////////// |
| 282 |
// Helper functions |
| 283 |
|
| 284 |
/* The following definitions are from The art of computer programming by Knuth |
| 285 |
* (copied from http://stackoverflow.com/questions/17333/most-effective-way-for-float-and-double-comparison) |
| 286 |
*/ |
| 287 |
|
| 288 |
/* |
| 289 |
static bool approximatelyEqual(double a, double b, double epsilon) |
| 290 |
{ |
| 291 |
return fabs(a - b) <= ( (fabs(a) < fabs(b) ? fabs(b) : fabs(a)) * epsilon); |
| 292 |
} |
| 293 |
*/ |
| 294 |
|
| 295 |
template<class T> |
| 296 |
static inline bool essentiallyEqual(T a, T b) |
| 297 |
{ |
| 298 |
static const T _epsilon = std::numeric_limits<T>::epsilon(); |
| 299 |
return std::fabs(a - b) <= ( (std::fabs(a) > std::fabs(b) ? std::fabs(b) : std::fabs(a)) * _epsilon); |
| 300 |
} |
| 301 |
|
| 302 |
template<class T> |
| 303 |
inline bool essentiallyZero(T a) { |
| 304 |
return !a; |
| 305 |
} |
| 306 |
|
| 307 |
template<> |
| 308 |
inline bool essentiallyZero(double a) { |
| 309 |
return essentiallyEqual(a, 0.0); |
| 310 |
} |
| 311 |
|
| 312 |
template<> |
| 313 |
inline bool essentiallyZero(float a) { |
| 314 |
return essentiallyEqual(a, 0.0f); |
| 315 |
} |
| 316 |
|
| 317 |
template<class T> |
| 318 |
static inline bool definitelyGreaterThan(T a, T b) |
| 319 |
{ |
| 320 |
static const T _epsilon = std::numeric_limits<T>::epsilon(); |
| 321 |
return (a - b) > ( (std::fabs(a) < std::fabs(b) ? std::fabs(b) : std::fabs(a)) * _epsilon); |
| 322 |
} |
| 323 |
|
| 324 |
template<class T> |
| 325 |
static inline bool definitelyLessThan(T a, T b) |
| 326 |
{ |
| 327 |
static const T _epsilon = std::numeric_limits<T>::epsilon(); |
| 328 |
return (b - a) > ( (std::fabs(a) < std::fabs(b) ? std::fabs(b) : std::fabs(a)) * _epsilon); |
| 329 |
} |
| 330 |
|
| 331 |
static inline int essentiallyInteger(double a, long &l, int &i) { |
| 332 |
double intpart; |
| 333 |
if (std::modf(a,&intpart) == 0.0) { |
| 334 |
if (intpart<0.0) { |
| 335 |
if (intpart >= std::numeric_limits<int>::min()) { |
| 336 |
i = static_cast<int>(intpart); |
| 337 |
l = i; |
| 338 |
return 1; |
| 339 |
} |
| 340 |
if (intpart >= std::numeric_limits<long>::min()) { |
| 341 |
l = static_cast<long>(intpart); |
| 342 |
return 2; |
| 343 |
} |
| 344 |
} |
| 345 |
else if (intpart <= std::numeric_limits<int>::max()) { |
| 346 |
i = static_cast<int>(intpart); |
| 347 |
l = i; |
| 348 |
return 1; |
| 349 |
} |
| 350 |
else if (intpart <= static_cast<double>(std::numeric_limits<long>::max())) { |
| 351 |
l = static_cast<int>(intpart); |
| 352 |
return 2; |
| 353 |
} |
| 354 |
} |
| 355 |
return 0; |
| 356 |
} |
| 357 |
|
| 358 |
static inline bool essentiallyInteger(double a, long &l) { |
| 359 |
double intpart; |
| 360 |
if (std::modf(a,&intpart) == 0.0) { |
| 361 |
if (intpart<0.0) { |
| 362 |
if (intpart >= std::numeric_limits<long>::min()) { |
| 363 |
l = static_cast<long>(intpart); |
| 364 |
return true; |
| 365 |
} |
| 366 |
} |
| 367 |
else if (intpart <= static_cast<double>(std::numeric_limits<long>::max())) { |
| 368 |
l = static_cast<long>(intpart); |
| 369 |
return true; |
| 370 |
} |
| 371 |
} |
| 372 |
return false; |
| 373 |
} |
| 374 |
|
| 375 |
// This class is intended to be contained inside App::any (via a shared_ptr) |
| 376 |
// without holding Python global lock |
| 377 |
struct PyObjectWrapper { |
| 378 |
public: |
| 379 |
using Pointer = std::shared_ptr<PyObjectWrapper>; |
| 380 |
|
| 381 |
explicit PyObjectWrapper(PyObject *obj):pyobj(obj) { |
| 382 |
Py::_XINCREF(pyobj); |
| 383 |
} |
| 384 |
~PyObjectWrapper() { |
| 385 |
if(pyobj) { |
| 386 |
Base::PyGILStateLocker lock; |
| 387 |
Py::_XDECREF(pyobj); |
| 388 |
} |
| 389 |
} |
| 390 |
PyObjectWrapper(const PyObjectWrapper &) = delete; |
| 391 |
PyObjectWrapper &operator=(const PyObjectWrapper &) = delete; |
| 392 |
|
| 393 |
Py::Object get() const { |
| 394 |
if(!pyobj) |
| 395 |
return Py::Object(); |
| 396 |
return Py::Object(const_cast<PyObject*>(pyobj)); |
| 397 |
} |
| 398 |
|
| 399 |
private: |
| 400 |
PyObject *pyobj; |
| 401 |
}; |
| 402 |
|
| 403 |
static inline PyObjectWrapper::Pointer pyObjectWrap(PyObject *obj) { |
| 404 |
return std::make_shared<PyObjectWrapper>(obj); |
| 405 |
} |
| 406 |
|
| 407 |
static inline bool isAnyPyObject(const App::any &value) { |
| 408 |
return is_type(value,typeid(PyObjectWrapper::Pointer)); |
| 409 |
} |
| 410 |
|
| 411 |
static inline Py::Object __pyObjectFromAny(const App::any &value) { |
| 412 |
return cast<PyObjectWrapper::Pointer>(value)->get(); |
| 413 |
} |
| 414 |
|
| 415 |
static Py::Object _pyObjectFromAny(const App::any &value, const Expression *e) { |
| 416 |
if(value.empty()) |
| 417 |
return Py::Object(); |
| 418 |
else if (isAnyPyObject(value)) |
| 419 |
return __pyObjectFromAny(value); |
| 420 |
if (is_type(value,typeid(Quantity))) |
| 421 |
return Py::asObject(new QuantityPy(new Quantity(cast<Quantity>(value)))); |
| 422 |
else if (is_type(value,typeid(double))) |
| 423 |
return Py::Float(cast<double>(value)); |
| 424 |
else if (is_type(value,typeid(float))) |
| 425 |
return Py::Float(cast<float>(value)); |
| 426 |
else if (is_type(value,typeid(int))) |
| 427 |
return Py::Long(cast<int>(value)); |
| 428 |
else if (is_type(value,typeid(long))) { |
| 429 |
return Py::Long(cast<long>(value)); |
| 430 |
} else if (is_type(value,typeid(bool))) |
| 431 |
return Py::Boolean(cast<bool>(value)); |
| 432 |
else if (is_type(value,typeid(std::string))) |
| 433 |
return Py::String(cast<std::string>(value)); |
| 434 |
else if (is_type(value,typeid(const char*))) |
| 435 |
return Py::String(cast<const char*>(value)); |
| 436 |
|
| 437 |
_EXPR_THROW("Unknown type", e); |
| 438 |
} |
| 439 |
|
| 440 |
namespace App { |
| 441 |
Py::Object pyObjectFromAny(const App::any &value) { |
| 442 |
return _pyObjectFromAny(value,nullptr); |
| 443 |
} |
| 444 |
|
| 445 |
App::any pyObjectToAny(Py::Object value, bool check) { |
| 446 |
|
| 447 |
if(value.isNone()) |
| 448 |
return {}; |
| 449 |
|
| 450 |
PyObject *pyvalue = value.ptr(); |
| 451 |
|
| 452 |
if(!check) |
| 453 |
return {pyObjectWrap(pyvalue)}; |
| 454 |
|
| 455 |
if (PyObject_TypeCheck(pyvalue, &Base::QuantityPy::Type)) { |
| 456 |
Base::QuantityPy * qp = static_cast<Base::QuantityPy*>(pyvalue); |
| 457 |
Base::Quantity * q = qp->getQuantityPtr(); |
| 458 |
|
| 459 |
return App::any(*q); |
| 460 |
} |
| 461 |
if (PyFloat_Check(pyvalue)) |
| 462 |
return App::any(PyFloat_AsDouble(pyvalue)); |
| 463 |
if (PyLong_Check(pyvalue)) |
| 464 |
return App::any(PyLong_AsLong(pyvalue)); |
| 465 |
else if (PyUnicode_Check(pyvalue)) { |
| 466 |
const char* utf8value = PyUnicode_AsUTF8(pyvalue); |
| 467 |
if (!utf8value) { |
| 468 |
FC_THROWM(Base::ValueError, "Invalid unicode string"); |
| 469 |
} |
| 470 |
return App::any(std::string(utf8value)); |
| 471 |
} |
| 472 |
else { |
| 473 |
return App::any(pyObjectWrap(pyvalue)); |
| 474 |
} |
| 475 |
} |
| 476 |
|
| 477 |
bool pyToQuantity(Quantity &q, const Py::Object &pyobj) { |
| 478 |
if (PyObject_TypeCheck(*pyobj, &Base::QuantityPy::Type)) |
| 479 |
q = *static_cast<Base::QuantityPy*>(*pyobj)->getQuantityPtr(); |
| 480 |
else if (PyFloat_Check(*pyobj)) |
| 481 |
q = Quantity(PyFloat_AsDouble(*pyobj)); |
| 482 |
else if (PyLong_Check(*pyobj)) |
| 483 |
q = Quantity(PyLong_AsLong(*pyobj)); |
| 484 |
else |
| 485 |
return false; |
| 486 |
return true; |
| 487 |
} |
| 488 |
|
| 489 |
static inline Quantity pyToQuantity(const Py::Object &pyobj, |
| 490 |
const Expression *e, const char *msg=nullptr) |
| 491 |
{ |
| 492 |
Quantity q; |
| 493 |
if(!pyToQuantity(q,pyobj)) { |
| 494 |
if(!msg) |
| 495 |
msg = "Failed to convert to Quantity."; |
| 496 |
__EXPR_THROW(TypeError,msg,e); |
| 497 |
} |
| 498 |
return q; |
| 499 |
} |
| 500 |
|
| 501 |
Py::Object pyFromQuantity(const Quantity &quantity) { |
| 502 |
if (!quantity.isDimensionless()) |
| 503 |
return Py::asObject(new QuantityPy(new Quantity(quantity))); |
| 504 |
double v = quantity.getValue(); |
| 505 |
long l; |
| 506 |
int i; |
| 507 |
switch(essentiallyInteger(v,l,i)) { |
| 508 |
case 1: |
| 509 |
case 2: |
| 510 |
return Py::Long(l); |
| 511 |
default: |
| 512 |
return Py::Float(v); |
| 513 |
} |
| 514 |
} |
| 515 |
|
| 516 |
Quantity anyToQuantity(const App::any &value, const char *msg) { |
| 517 |
if (is_type(value,typeid(Quantity))) { |
| 518 |
return cast<Quantity>(value); |
| 519 |
} else if (is_type(value,typeid(bool))) { |
| 520 |
return Quantity(cast<bool>(value)?1.0:0.0); |
| 521 |
} else if (is_type(value,typeid(int))) { |
| 522 |
return Quantity(cast<int>(value)); |
| 523 |
} else if (is_type(value,typeid(long))) { |
| 524 |
return Quantity(cast<long>(value)); |
| 525 |
} else if (is_type(value,typeid(float))) { |
| 526 |
return Quantity(cast<float>(value)); |
| 527 |
} else if (is_type(value,typeid(double))) { |
| 528 |
return Quantity(cast<double>(value)); |
| 529 |
} |
| 530 |
if(!msg) |
| 531 |
msg = "Failed to convert to Quantity"; |
| 532 |
TYPE_THROW(msg); |
| 533 |
} |
| 534 |
|
| 535 |
static inline bool anyToLong(long &res, const App::any &value) { |
| 536 |
if (is_type(value,typeid(int))) { |
| 537 |
res = cast<int>(value); |
| 538 |
} else if (is_type(value,typeid(long))) { |
| 539 |
res = cast<long>(value); |
| 540 |
} else if (is_type(value,typeid(bool))) |
| 541 |
res = cast<bool>(value)?1:0; |
| 542 |
else |
| 543 |
return false; |
| 544 |
return true; |
| 545 |
} |
| 546 |
|
| 547 |
static inline bool anyToDouble(double &res, const App::any &value) { |
| 548 |
if (is_type(value,typeid(double))) |
| 549 |
res = cast<double>(value); |
| 550 |
else if (is_type(value,typeid(float))) |
| 551 |
res = cast<float>(value); |
| 552 |
else if (is_type(value,typeid(long))) |
| 553 |
res = cast<long>(value); |
| 554 |
else if (is_type(value,typeid(int))) |
| 555 |
res = cast<int>(value); |
| 556 |
else if (is_type(value,typeid(bool))) |
| 557 |
res = cast<bool>(value)?1:0; |
| 558 |
else |
| 559 |
return false; |
| 560 |
return true; |
| 561 |
} |
| 562 |
|
| 563 |
bool isAnyEqual(const App::any &v1, const App::any &v2) { |
| 564 |
if(v1.empty()) |
| 565 |
return v2.empty(); |
| 566 |
else if(v2.empty()) |
| 567 |
return false; |
| 568 |
|
| 569 |
if(!is_type(v1,v2.type())) { |
| 570 |
if(is_type(v1,typeid(Quantity))) |
| 571 |
return cast<Quantity>(v1) == anyToQuantity(v2); |
| 572 |
else if(is_type(v2,typeid(Quantity))) |
| 573 |
return anyToQuantity(v1) == cast<Quantity>(v2); |
| 574 |
|
| 575 |
long l1,l2; |
| 576 |
double d1,d2; |
| 577 |
if(anyToLong(l1,v1)) { |
| 578 |
if(anyToLong(l2,v2)) |
| 579 |
return l1==l2; |
| 580 |
else if(anyToDouble(d2,v2)) |
| 581 |
return essentiallyEqual((double)l1,d2); |
| 582 |
else |
| 583 |
return false; |
| 584 |
}else if(anyToDouble(d1,v1)) |
| 585 |
return anyToDouble(d2,v2) && essentiallyEqual(d1,d2); |
| 586 |
|
| 587 |
if(is_type(v1,typeid(std::string))) { |
| 588 |
if(is_type(v2,typeid(const char*))) { |
| 589 |
auto c = cast<const char*>(v2); |
| 590 |
return c && cast<std::string>(v1)==c; |
| 591 |
} |
| 592 |
return false; |
| 593 |
}else if(is_type(v1,typeid(const char*))) { |
| 594 |
if(is_type(v2,typeid(std::string))) { |
| 595 |
auto c = cast<const char*>(v1); |
| 596 |
return c && cast<std::string>(v2)==c; |
| 597 |
} |
| 598 |
return false; |
| 599 |
} |
| 600 |
} |
| 601 |
|
| 602 |
if (is_type(v1,typeid(int))) |
| 603 |
return cast<int>(v1) == cast<int>(v2); |
| 604 |
if (is_type(v1,typeid(long))) |
| 605 |
return cast<long>(v1) == cast<long>(v2); |
| 606 |
if (is_type(v1,typeid(std::string))) |
| 607 |
return cast<std::string>(v1) == cast<std::string>(v2); |
| 608 |
if (is_type(v1,typeid(const char*))) { |
| 609 |
auto c1 = cast<const char*>(v1); |
| 610 |
auto c2 = cast<const char*>(v2); |
| 611 |
return c1==c2 || (c1 && c2 && strcmp(c1,c2)==0); |
| 612 |
} |
| 613 |
if (is_type(v1,typeid(bool))) |
| 614 |
return cast<bool>(v1) == cast<bool>(v2); |
| 615 |
if (is_type(v1,typeid(double))) |
| 616 |
return essentiallyEqual(cast<double>(v1), cast<double>(v2)); |
| 617 |
if (is_type(v1,typeid(float))) |
| 618 |
return essentiallyEqual(cast<float>(v1), cast<float>(v2)); |
| 619 |
|
| 620 |
if (is_type(v1,typeid(Quantity))) |
| 621 |
return cast<Quantity>(v1) == cast<Quantity>(v2); |
| 622 |
|
| 623 |
if (!isAnyPyObject(v1)) |
| 624 |
throw Base::TypeError("Unknown type"); |
| 625 |
|
| 626 |
Base::PyGILStateLocker lock; |
| 627 |
Py::Object o1 = __pyObjectFromAny(v1); |
| 628 |
Py::Object o2 = __pyObjectFromAny(v2); |
| 629 |
if(!o1.isType(o2.type())) |
| 630 |
return false; |
| 631 |
int res = PyObject_RichCompareBool(o1.ptr(),o2.ptr(),Py_EQ); |
| 632 |
if(res<0) |
| 633 |
PyException::throwException(); |
| 634 |
return !!res; |
| 635 |
} |
| 636 |
|
| 637 |
Expression* expressionFromPy(const DocumentObject *owner, const Py::Object &value) { |
| 638 |
if (value.isNone()) |
| 639 |
return new PyObjectExpression(owner); |
| 640 |
if(value.isString()) { |
| 641 |
return new StringExpression(owner,value.as_string()); |
| 642 |
} else if (PyObject_TypeCheck(value.ptr(),&QuantityPy::Type)) { |
| 643 |
return new NumberExpression(owner, |
| 644 |
*static_cast<QuantityPy*>(value.ptr())->getQuantityPtr()); |
| 645 |
} else if (value.isBoolean()) { |
| 646 |
if(value.isTrue()) |
| 647 |
return new ConstantExpression(owner,"True",Quantity(1.0)); |
| 648 |
else |
| 649 |
return new ConstantExpression(owner,"False",Quantity(0.0)); |
| 650 |
} else { |
| 651 |
Quantity q; |
| 652 |
if(pyToQuantity(q,value)) |
| 653 |
return new NumberExpression(owner,q); |
| 654 |
} |
| 655 |
return new PyObjectExpression(owner,value.ptr()); |
| 656 |
} |
| 657 |
|
| 658 |
} // namespace App |
| 659 |
|
| 660 |
// |
| 661 |
// Expression component |
| 662 |
// |
| 663 |
Expression::Component::Component(const std::string &n) |
| 664 |
:comp(ObjectIdentifier::SimpleComponent(n)) |
| 665 |
,e1(nullptr) ,e2(nullptr) ,e3(nullptr) |
| 666 |
{} |
| 667 |
|
| 668 |
Expression::Component::Component(Expression *_e1, Expression *_e2, Expression *_e3, bool isRange) |
| 669 |
:e1(_e1) ,e2(_e2) ,e3(_e3) |
| 670 |
{ |
| 671 |
if(isRange || e2 || e3) |
| 672 |
comp = ObjectIdentifier::RangeComponent(0); |
| 673 |
} |
| 674 |
|
| 675 |
Expression::Component::Component(const ObjectIdentifier::Component &comp) |
| 676 |
:comp(comp) |
| 677 |
,e1(nullptr) ,e2(nullptr) ,e3(nullptr) |
| 678 |
{} |
| 679 |
|
| 680 |
Expression::Component::Component(const Component &other) |
| 681 |
:comp(other.comp) |
| 682 |
,e1(other.e1?other.e1->copy():nullptr) |
| 683 |
,e2(other.e2?other.e2->copy():nullptr) |
| 684 |
,e3(other.e3?other.e3->copy():nullptr) |
| 685 |
{} |
| 686 |
|
| 687 |
Expression::Component::~Component() |
| 688 |
{ |
| 689 |
delete e1; |
| 690 |
delete e2; |
| 691 |
delete e3; |
| 692 |
} |
| 693 |
|
| 694 |
Expression::Component* Expression::Component::copy() const { |
| 695 |
return new Component(*this); |
| 696 |
} |
| 697 |
|
| 698 |
Expression::Component* Expression::Component::eval() const { |
| 699 |
auto res = new Component(comp); |
| 700 |
if(e1) res->e1 = e1->eval(); |
| 701 |
if(e2) res->e2 = e2->eval(); |
| 702 |
if(e3) res->e3 = e3->eval(); |
| 703 |
return res; |
| 704 |
} |
| 705 |
|
| 706 |
Py::Object Expression::Component::get(const Expression *owner, const Py::Object &pyobj) const { |
| 707 |
try { |
| 708 |
if(!e1 && !e2 && !e3) |
| 709 |
return comp.get(pyobj); |
| 710 |
if(!comp.isRange() && !e2 && !e3) { |
| 711 |
auto index = e1->getPyValue(); |
| 712 |
Py::Object res; |
| 713 |
if(pyobj.isMapping()) |
| 714 |
res = Py::Mapping(pyobj).getItem(index); |
| 715 |
else { |
| 716 |
Py_ssize_t i = PyNumber_AsSsize_t(index.ptr(), PyExc_IndexError); |
| 717 |
if(PyErr_Occurred()) |
| 718 |
throw Py::Exception(); |
| 719 |
res = Py::Sequence(pyobj).getItem(i); |
| 720 |
} |
| 721 |
if(!res.ptr()) |
| 722 |
throw Py::Exception(); |
| 723 |
return res; |
| 724 |
}else{ |
| 725 |
Py::Object v1,v2,v3; |
| 726 |
if(e1) v1 = e1->getPyValue(); |
| 727 |
if(e2) v2 = e2->getPyValue(); |
| 728 |
if(e3) v3 = e3->getPyValue(); |
| 729 |
PyObject *s = PySlice_New(e1?v1.ptr():nullptr, |
| 730 |
e2?v2.ptr():nullptr, |
| 731 |
e3?v3.ptr():nullptr); |
| 732 |
if(!s) |
| 733 |
throw Py::Exception(); |
| 734 |
Py::Object slice(s,true); |
| 735 |
PyObject *res = PyObject_GetItem(pyobj.ptr(),slice.ptr()); |
| 736 |
if(!res) |
| 737 |
throw Py::Exception(); |
| 738 |
return Py::asObject(res); |
| 739 |
} |
| 740 |
}catch(Py::Exception &) { |
| 741 |
EXPR_PY_THROW(owner); |
| 742 |
} |
| 743 |
return Py::Object(); |
| 744 |
} |
| 745 |
|
| 746 |
void Expression::Component::set(const Expression *owner, Py::Object &pyobj, const Py::Object &value) const |
| 747 |
{ |
| 748 |
if(!e1 && !e2 && !e3) |
| 749 |
return comp.set(pyobj,value); |
| 750 |
try { |
| 751 |
if(!comp.isRange() && !e2 && !e3) { |
| 752 |
auto index = e1->getPyValue(); |
| 753 |
if(pyobj.isMapping()) |
| 754 |
Py::Mapping(pyobj).setItem(index,value); |
| 755 |
else { |
| 756 |
Py_ssize_t i = PyNumber_AsSsize_t(pyobj.ptr(), PyExc_IndexError); |
| 757 |
if(PyErr_Occurred() || PySequence_SetItem(pyobj.ptr(),i,value.ptr())==-1) |
| 758 |
throw Py::Exception(); |
| 759 |
} |
| 760 |
}else{ |
| 761 |
Py::Object v1,v2,v3; |
| 762 |
if(e1) v1 = e1->getPyValue(); |
| 763 |
if(e2) v2 = e2->getPyValue(); |
| 764 |
if(e3) v3 = e3->getPyValue(); |
| 765 |
PyObject *s = PySlice_New(e1?v1.ptr():nullptr, |
| 766 |
e2?v2.ptr():nullptr, |
| 767 |
e3?v3.ptr():nullptr); |
| 768 |
if(!s) |
| 769 |
throw Py::Exception(); |
| 770 |
Py::Object slice(s,true); |
| 771 |
if(PyObject_SetItem(pyobj.ptr(),slice.ptr(),value.ptr())<0) |
| 772 |
throw Py::Exception(); |
| 773 |
} |
| 774 |
}catch(Py::Exception &) { |
| 775 |
EXPR_PY_THROW(owner); |
| 776 |
} |
| 777 |
} |
| 778 |
|
| 779 |
void Expression::Component::del(const Expression *owner, Py::Object &pyobj) const { |
| 780 |
try { |
| 781 |
if (!e1 && !e2 && !e3) { |
| 782 |
comp.del(pyobj); |
| 783 |
} |
| 784 |
else if (!comp.isRange() && !e2 && !e3) { |
| 785 |
auto index = e1->getPyValue(); |
| 786 |
if (pyobj.isMapping()) { |
| 787 |
Py::Mapping(pyobj).delItem(index); |
| 788 |
} |
| 789 |
else { |
| 790 |
Py_ssize_t i = PyNumber_AsSsize_t(pyobj.ptr(), PyExc_IndexError); |
| 791 |
if (PyErr_Occurred() || PySequence_DelItem(pyobj.ptr(),i)==-1) |
| 792 |
throw Py::Exception(); |
| 793 |
} |
| 794 |
} |
| 795 |
else { |
| 796 |
Py::Object v1,v2,v3; |
| 797 |
if(e1) v1 = e1->getPyValue(); |
| 798 |
if(e2) v2 = e2->getPyValue(); |
| 799 |
if(e3) v3 = e3->getPyValue(); |
| 800 |
PyObject *s = PySlice_New(e1?v1.ptr():nullptr, |
| 801 |
e2?v2.ptr():nullptr, |
| 802 |
e3?v3.ptr():nullptr); |
| 803 |
if (!s) |
| 804 |
throw Py::Exception(); |
| 805 |
Py::Object slice(s,true); |
| 806 |
if (PyObject_DelItem(pyobj.ptr(),slice.ptr())<0) |
| 807 |
throw Py::Exception(); |
| 808 |
} |
| 809 |
} |
| 810 |
catch(Py::Exception &) { |
| 811 |
EXPR_PY_THROW(owner); |
| 812 |
} |
| 813 |
} |
| 814 |
|
| 815 |
void Expression::Component::visit(ExpressionVisitor &v) { |
| 816 |
if(e1) e1->visit(v); |
| 817 |
if(e2) e2->visit(v); |
| 818 |
if(e3) e3->visit(v); |
| 819 |
} |
| 820 |
|
| 821 |
bool Expression::Component::isTouched() const { |
| 822 |
return (e1&&e1->isTouched()) || |
| 823 |
(e2&&e2->isTouched()) || |
| 824 |
(e3&&e3->isTouched()); |
| 825 |
} |
| 826 |
|
| 827 |
void Expression::Component::toString(std::ostream &ss, bool persistent) const { |
| 828 |
if(!e1 && !e2 && !e3) { |
| 829 |
if(comp.isSimple()) |
| 830 |
ss << '.'; |
| 831 |
comp.toString(ss,!persistent); |
| 832 |
return; |
| 833 |
} |
| 834 |
ss << '['; |
| 835 |
if(e1) |
| 836 |
e1->toString(ss,persistent); |
| 837 |
if(e2 || comp.isRange()) |
| 838 |
ss << ':'; |
| 839 |
if(e2) |
| 840 |
e2->toString(ss,persistent); |
| 841 |
if(e3) { |
| 842 |
ss << ':'; |
| 843 |
e3->toString(ss,persistent); |
| 844 |
} |
| 845 |
ss << ']'; |
| 846 |
} |
| 847 |
|
| 848 |
|
| 849 |
// |
| 850 |
// Expression base-class |
| 851 |
// |
| 852 |
|
| 853 |
TYPESYSTEM_SOURCE_ABSTRACT(App::Expression, Base::BaseClass) |
| 854 |
|
| 855 |
Expression::Expression(const DocumentObject *_owner) |
| 856 |
: owner(const_cast<App::DocumentObject*>(_owner)) |
| 857 |
{ |
| 858 |
|
| 859 |
} |
| 860 |
|
| 861 |
Expression::~Expression() |
| 862 |
{ |
| 863 |
for(auto c : components) |
| 864 |
delete c; |
| 865 |
} |
| 866 |
|
| 867 |
Expression::Component* Expression::createComponent(const std::string &n) { |
| 868 |
return new Component(n); |
| 869 |
} |
| 870 |
|
| 871 |
Expression::Component* Expression::createComponent( |
| 872 |
Expression* e1, Expression* e2, Expression* e3, bool isRange) |
| 873 |
{ |
| 874 |
return new Component(e1,e2,e3,isRange); |
| 875 |
} |
| 876 |
|
| 877 |
|
| 878 |
int Expression::priority() const { |
| 879 |
return 20; |
| 880 |
} |
| 881 |
|
| 882 |
Expression * Expression::parse(const DocumentObject *owner, const std::string &buffer) |
| 883 |
{ |
| 884 |
return ExpressionParser::parse(owner, buffer.c_str()); |
| 885 |
} |
| 886 |
|
| 887 |
void Expression::getDeps(ExpressionDeps &deps, int option) const { |
| 888 |
for(auto &v : getIdentifiers()) { |
| 889 |
bool hidden = v.second; |
| 890 |
const ObjectIdentifier &var = v.first; |
| 891 |
if((hidden && option==DepNormal) |
| 892 |
|| (!hidden && option==DepHidden)) |
| 893 |
continue; |
| 894 |
for(auto &dep : var.getDep(true)) { |
| 895 |
DocumentObject *obj = dep.first; |
| 896 |
for(auto &propName : dep.second) { |
| 897 |
deps[obj][propName].push_back(var); |
| 898 |
} |
| 899 |
} |
| 900 |
} |
| 901 |
} |
| 902 |
|
| 903 |
ExpressionDeps Expression::getDeps(int option) const { |
| 904 |
ExpressionDeps deps; |
| 905 |
getDeps(deps, option); |
| 906 |
return deps; |
| 907 |
} |
| 908 |
|
| 909 |
void Expression::getDepObjects( |
| 910 |
std::map<App::DocumentObject*,bool> &deps, std::vector<std::string> *labels) const |
| 911 |
{ |
| 912 |
for(auto &v : getIdentifiers()) { |
| 913 |
bool hidden = v.second; |
| 914 |
const ObjectIdentifier &var = v.first; |
| 915 |
std::vector<std::string> strings; |
| 916 |
for(auto &dep : var.getDep(false, &strings)) { |
| 917 |
DocumentObject *obj = dep.first; |
| 918 |
if (!obj->testStatus(ObjectStatus::Remove)) { |
| 919 |
if (labels) { |
| 920 |
std::copy(strings.begin(), strings.end(), std::back_inserter(*labels)); |
| 921 |
} |
| 922 |
|
| 923 |
auto res = deps.insert(std::make_pair(obj, hidden)); |
| 924 |
if (!hidden || res.second) |
| 925 |
res.first->second = hidden; |
| 926 |
} |
| 927 |
|
| 928 |
strings.clear(); |
| 929 |
} |
| 930 |
} |
| 931 |
} |
| 932 |
|
| 933 |
std::map<App::DocumentObject*,bool> Expression::getDepObjects(std::vector<std::string> *labels) const { |
| 934 |
std::map<App::DocumentObject*,bool> deps; |
| 935 |
getDepObjects(deps,labels); |
| 936 |
return deps; |
| 937 |
} |
| 938 |
|
| 939 |
class GetIdentifiersExpressionVisitor : public ExpressionVisitor { |
| 940 |
public: |
| 941 |
explicit GetIdentifiersExpressionVisitor(std::map<App::ObjectIdentifier,bool> &deps) |
| 942 |
:deps(deps) |
| 943 |
{} |
| 944 |
|
| 945 |
void visit(Expression &e) override { |
| 946 |
this->getIdentifiers(e,deps); |
| 947 |
} |
| 948 |
|
| 949 |
std::map<App::ObjectIdentifier,bool> &deps; |
| 950 |
}; |
| 951 |
|
| 952 |
void Expression::getIdentifiers(std::map<App::ObjectIdentifier,bool> &deps) const { |
| 953 |
GetIdentifiersExpressionVisitor v(deps); |
| 954 |
const_cast<Expression*>(this)->visit(v); |
| 955 |
} |
| 956 |
|
| 957 |
std::map<App::ObjectIdentifier,bool> Expression::getIdentifiers() const { |
| 958 |
std::map<App::ObjectIdentifier,bool> deps; |
| 959 |
getIdentifiers(deps); |
| 960 |
return deps; |
| 961 |
} |
| 962 |
|
| 963 |
class AdjustLinksExpressionVisitor : public ExpressionVisitor { |
| 964 |
public: |
| 965 |
explicit AdjustLinksExpressionVisitor(const std::set<App::DocumentObject*> &inList) |
| 966 |
:inList(inList) |
| 967 |
{} |
| 968 |
|
| 969 |
void visit(Expression &e) override { |
| 970 |
if(this->adjustLinks(e,inList)) |
| 971 |
res = true; |
| 972 |
} |
| 973 |
|
| 974 |
const std::set<App::DocumentObject*> &inList; |
| 975 |
bool res{false}; |
| 976 |
}; |
| 977 |
|
| 978 |
bool Expression::adjustLinks(const std::set<App::DocumentObject*> &inList) { |
| 979 |
AdjustLinksExpressionVisitor v(inList); |
| 980 |
visit(v); |
| 981 |
return v.res; |
| 982 |
} |
| 983 |
|
| 984 |
class ImportSubNamesExpressionVisitor : public ExpressionVisitor { |
| 985 |
public: |
| 986 |
explicit ImportSubNamesExpressionVisitor(const ObjectIdentifier::SubNameMap &subNameMap) |
| 987 |
:subNameMap(subNameMap) |
| 988 |
{} |
| 989 |
|
| 990 |
void visit(Expression &e) override { |
| 991 |
this->importSubNames(e,subNameMap); |
| 992 |
} |
| 993 |
|
| 994 |
const ObjectIdentifier::SubNameMap &subNameMap; |
| 995 |
}; |
| 996 |
|
| 997 |
ExpressionPtr Expression::importSubNames(const std::map<std::string,std::string> &nameMap) const { |
| 998 |
if(!owner || !owner->getDocument()) |
| 999 |
return nullptr; |
| 1000 |
ObjectIdentifier::SubNameMap subNameMap; |
| 1001 |
for(auto &dep : getDeps(DepAll)) { |
| 1002 |
for(auto &info : dep.second) { |
| 1003 |
for(auto &path : info.second) { |
| 1004 |
auto obj = path.getDocumentObject(); |
| 1005 |
if(!obj) |
| 1006 |
continue; |
| 1007 |
auto it = nameMap.find(obj->getExportName(true)); |
| 1008 |
if(it!=nameMap.end()) |
| 1009 |
subNameMap.emplace(std::make_pair(obj,std::string()),it->second); |
| 1010 |
auto key = std::make_pair(obj,path.getSubObjectName()); |
| 1011 |
if(key.second.empty() || subNameMap.contains(key)) |
| 1012 |
continue; |
| 1013 |
std::string imported = PropertyLinkBase::tryImportSubName( |
| 1014 |
obj,key.second.c_str(),owner->getDocument(), nameMap); |
| 1015 |
if(!imported.empty()) |
| 1016 |
subNameMap.emplace(std::move(key),std::move(imported)); |
| 1017 |
} |
| 1018 |
} |
| 1019 |
} |
| 1020 |
if(subNameMap.empty()) |
| 1021 |
return nullptr; |
| 1022 |
ImportSubNamesExpressionVisitor v(subNameMap); |
| 1023 |
auto res = copy(); |
| 1024 |
res->visit(v); |
| 1025 |
return ExpressionPtr(res); |
| 1026 |
} |
| 1027 |
|
| 1028 |
class UpdateLabelExpressionVisitor : public ExpressionVisitor { |
| 1029 |
public: |
| 1030 |
UpdateLabelExpressionVisitor(App::DocumentObject *obj, const std::string &ref, const char *newLabel) |
| 1031 |
:obj(obj),ref(ref),newLabel(newLabel) |
| 1032 |
{} |
| 1033 |
|
| 1034 |
void visit(Expression &e) override { |
| 1035 |
this->updateLabelReference(e,obj,ref,newLabel); |
| 1036 |
} |
| 1037 |
|
| 1038 |
App::DocumentObject *obj; |
| 1039 |
const std::string &ref; |
| 1040 |
const char *newLabel; |
| 1041 |
}; |
| 1042 |
|
| 1043 |
ExpressionPtr Expression::updateLabelReference( |
| 1044 |
App::DocumentObject *obj, const std::string &ref, const char *newLabel) const |
| 1045 |
{ |
| 1046 |
if(ref.size()<=2) |
| 1047 |
return {}; |
| 1048 |
std::vector<std::string> labels; |
| 1049 |
for(auto &v : getIdentifiers()) |
| 1050 |
v.first.getDepLabels(labels); |
| 1051 |
for(auto &label : labels) { |
| 1052 |
// ref contains something like $label. and we need to strip '$' and '.' |
| 1053 |
if(ref.compare(1,ref.size()-2,label)==0) { |
| 1054 |
UpdateLabelExpressionVisitor v(obj,ref,newLabel); |
| 1055 |
auto expr = copy(); |
| 1056 |
expr->visit(v); |
| 1057 |
return ExpressionPtr(expr); |
| 1058 |
} |
| 1059 |
} |
| 1060 |
return {}; |
| 1061 |
} |
| 1062 |
|
| 1063 |
class ReplaceObjectExpressionVisitor : public ExpressionVisitor { |
| 1064 |
public: |
| 1065 |
ReplaceObjectExpressionVisitor(const DocumentObject *parent, |
| 1066 |
DocumentObject *oldObj, DocumentObject *newObj) |
| 1067 |
: parent(parent),oldObj(oldObj),newObj(newObj) |
| 1068 |
{ |
| 1069 |
} |
| 1070 |
|
| 1071 |
void visit(Expression &e) override { |
| 1072 |
if(collect) |
| 1073 |
this->collectReplacement(e,paths,parent,oldObj,newObj); |
| 1074 |
else |
| 1075 |
this->renameObjectIdentifier(e,paths,dummy); |
| 1076 |
} |
| 1077 |
|
| 1078 |
const DocumentObject *parent; |
| 1079 |
DocumentObject *oldObj; |
| 1080 |
DocumentObject *newObj; |
| 1081 |
ObjectIdentifier dummy; |
| 1082 |
std::map<ObjectIdentifier, ObjectIdentifier> paths; |
| 1083 |
bool collect = true; |
| 1084 |
}; |
| 1085 |
|
| 1086 |
ExpressionPtr Expression::replaceObject(const DocumentObject *parent, |
| 1087 |
DocumentObject *oldObj, DocumentObject *newObj) const |
| 1088 |
{ |
| 1089 |
ReplaceObjectExpressionVisitor v(parent,oldObj,newObj); |
| 1090 |
|
| 1091 |
// First pass, collect any changes. We have to const_cast it, as visit() is |
| 1092 |
// not const. This is ugly... |
| 1093 |
const_cast<Expression*>(this)->visit(v); |
| 1094 |
|
| 1095 |
if(v.paths.empty()) |
| 1096 |
return {}; |
| 1097 |
|
| 1098 |
// Now make a copy and do the actual replacement |
| 1099 |
auto expr = copy(); |
| 1100 |
v.collect = false; |
| 1101 |
expr->visit(v); |
| 1102 |
return ExpressionPtr(expr); |
| 1103 |
} |
| 1104 |
|
| 1105 |
App::any Expression::getValueAsAny() const { |
| 1106 |
Base::PyGILStateLocker lock; |
| 1107 |
return pyObjectToAny(getPyValue()); |
| 1108 |
} |
| 1109 |
|
| 1110 |
Py::Object Expression::getPyValue() const { |
| 1111 |
try { |
| 1112 |
Py::Object pyobj = _getPyValue(); |
| 1113 |
if(!components.empty()) { |
| 1114 |
for(auto &c : components) |
| 1115 |
pyobj = c->get(this,pyobj); |
| 1116 |
} |
| 1117 |
return pyobj; |
| 1118 |
}catch(Py::Exception &) { |
| 1119 |
EXPR_PY_THROW(this); |
| 1120 |
} |
| 1121 |
return Py::Object(); |
| 1122 |
} |
| 1123 |
|
| 1124 |
void Expression::addComponent(Component *component) { |
| 1125 |
assert(component); |
| 1126 |
components.push_back(component); |
| 1127 |
} |
| 1128 |
|
| 1129 |
void Expression::visit(ExpressionVisitor &v) { |
| 1130 |
_visit(v); |
| 1131 |
for(auto &c : components) |
| 1132 |
c->visit(v); |
| 1133 |
v.visit(*this); |
| 1134 |
} |
| 1135 |
|
| 1136 |
Expression* Expression::eval() const { |
| 1137 |
Base::PyGILStateLocker lock; |
| 1138 |
return expressionFromPy(owner,getPyValue()); |
| 1139 |
} |
| 1140 |
|
| 1141 |
bool Expression::isSame(const Expression &other, bool checkComment) const { |
| 1142 |
if(&other == this) |
| 1143 |
return true; |
| 1144 |
if(getTypeId()!=other.getTypeId()) |
| 1145 |
return false; |
| 1146 |
return (!checkComment || comment==other.comment) |
| 1147 |
&& toString(true,true) == other.toString(true,true); |
| 1148 |
} |
| 1149 |
|
| 1150 |
std::string Expression::toString(bool persistent, bool checkPriority, int indent) const { |
| 1151 |
std::ostringstream ss; |
| 1152 |
toString(ss,persistent,checkPriority,indent); |
| 1153 |
return ss.str(); |
| 1154 |
} |
| 1155 |
|
| 1156 |
void Expression::toString(std::ostream &ss, bool persistent, bool checkPriority, int indent) const { |
| 1157 |
if(components.empty()) { |
| 1158 |
bool needsParens = checkPriority && priority()<20; |
| 1159 |
if(needsParens) |
| 1160 |
ss << '('; |
| 1161 |
_toString(ss,persistent,indent); |
| 1162 |
if(needsParens) |
| 1163 |
ss << ')'; |
| 1164 |
return; |
| 1165 |
} |
| 1166 |
if(!_isIndexable()) { |
| 1167 |
ss << '('; |
| 1168 |
_toString(ss,persistent,indent); |
| 1169 |
ss << ')'; |
| 1170 |
}else |
| 1171 |
_toString(ss,persistent,indent); |
| 1172 |
for(auto &c : components) |
| 1173 |
c->toString(ss,persistent); |
| 1174 |
} |
| 1175 |
|
| 1176 |
Expression* Expression::copy() const { |
| 1177 |
auto expr = _copy(); |
| 1178 |
copy_vector(expr->components,components); |
| 1179 |
expr->comment = comment; |
| 1180 |
return expr; |
| 1181 |
} |
| 1182 |
|
| 1183 |
|
| 1184 |
// |
| 1185 |
// UnitExpression class |
| 1186 |
// |
| 1187 |
|
| 1188 |
TYPESYSTEM_SOURCE(App::UnitExpression, App::Expression) |
| 1189 |
|
| 1190 |
UnitExpression::UnitExpression(const DocumentObject *_owner, const Base::Quantity & _quantity, const std::string &_unitStr) |
| 1191 |
: Expression(_owner) |
| 1192 |
, quantity(_quantity) |
| 1193 |
, unitStr(_unitStr) |
| 1194 |
{ |
| 1195 |
} |
| 1196 |
|
| 1197 |
UnitExpression::~UnitExpression() { |
| 1198 |
if(cache) { |
| 1199 |
Base::PyGILStateLocker lock; |
| 1200 |
Py::_XDECREF(cache); |
| 1201 |
} |
| 1202 |
} |
| 1203 |
|
| 1204 |
void UnitExpression::setQuantity(const Quantity &_quantity) |
| 1205 |
{ |
| 1206 |
quantity = _quantity; |
| 1207 |
if(cache) { |
| 1208 |
Base::PyGILStateLocker lock; |
| 1209 |
Py::_XDECREF(cache); |
| 1210 |
cache = nullptr; |
| 1211 |
} |
| 1212 |
} |
| 1213 |
|
| 1214 |
/** |
| 1215 |
* Set unit information. |
| 1216 |
* |
| 1217 |
* @param _unit A unit object |
| 1218 |
* @param _unitstr The unit expressed as a string |
| 1219 |
* @param _scaler Scale factor to convert unit into internal unit. |
| 1220 |
*/ |
| 1221 |
|
| 1222 |
void UnitExpression::setUnit(const Quantity &_quantity) |
| 1223 |
{ |
| 1224 |
quantity = _quantity; |
| 1225 |
if(cache) { |
| 1226 |
Base::PyGILStateLocker lock; |
| 1227 |
Py::_XDECREF(cache); |
| 1228 |
cache = nullptr; |
| 1229 |
} |
| 1230 |
} |
| 1231 |
|
| 1232 |
/** |
| 1233 |
* Simplify the expression. In this case, a NumberExpression is returned, |
| 1234 |
* as it cannot be simplified any more. |
| 1235 |
*/ |
| 1236 |
|
| 1237 |
Expression *UnitExpression::simplify() const |
| 1238 |
{ |
| 1239 |
return new NumberExpression(owner, quantity); |
| 1240 |
} |
| 1241 |
|
| 1242 |
/** |
| 1243 |
* Return a string representation, in this case the unit string. |
| 1244 |
*/ |
| 1245 |
|
| 1246 |
/** |
| 1247 |
* Return a string representation of the expression. |
| 1248 |
*/ |
| 1249 |
|
| 1250 |
void UnitExpression::_toString(std::ostream &ss, bool,int) const |
| 1251 |
{ |
| 1252 |
ss << unitStr; |
| 1253 |
} |
| 1254 |
|
| 1255 |
/** |
| 1256 |
* Return a copy of the expression. |
| 1257 |
*/ |
| 1258 |
|
| 1259 |
Expression *UnitExpression::_copy() const |
| 1260 |
{ |
| 1261 |
return new UnitExpression(owner, quantity, unitStr); |
| 1262 |
} |
| 1263 |
|
| 1264 |
Py::Object UnitExpression::_getPyValue() const { |
| 1265 |
if(!cache) |
| 1266 |
cache = Py::new_reference_to(pyFromQuantity(quantity)); |
| 1267 |
return Py::Object(cache); |
| 1268 |
} |
| 1269 |
|
| 1270 |
// |
| 1271 |
// NumberExpression class |
| 1272 |
// |
| 1273 |
|
| 1274 |
TYPESYSTEM_SOURCE(App::NumberExpression, App::Expression) |
| 1275 |
|
| 1276 |
NumberExpression::NumberExpression(const DocumentObject *_owner, const Quantity &_quantity) |
| 1277 |
: UnitExpression(_owner, _quantity) |
| 1278 |
{ |
| 1279 |
} |
| 1280 |
|
| 1281 |
/** |
| 1282 |
* Simplify the expression. For NumberExpressions, we return a copy(), as it cannot |
| 1283 |
* be simplified any more. |
| 1284 |
*/ |
| 1285 |
|
| 1286 |
Expression *NumberExpression::simplify() const |
| 1287 |
{ |
| 1288 |
return copy(); |
| 1289 |
} |
| 1290 |
|
| 1291 |
/** |
| 1292 |
* Create and return a copy of the expression. |
| 1293 |
*/ |
| 1294 |
|
| 1295 |
Expression *NumberExpression::_copy() const |
| 1296 |
{ |
| 1297 |
return new NumberExpression(owner, getQuantity()); |
| 1298 |
} |
| 1299 |
|
| 1300 |
/** |
| 1301 |
* Negate the stored value. |
| 1302 |
*/ |
| 1303 |
|
| 1304 |
void NumberExpression::negate() |
| 1305 |
{ |
| 1306 |
setQuantity(-getQuantity()); |
| 1307 |
} |
| 1308 |
|
| 1309 |
void NumberExpression::_toString(std::ostream &ss, bool,int) const |
| 1310 |
{ |
| 1311 |
// Restore the old implementation because using digits10 + 2 causes |
| 1312 |
// undesired side-effects: |
| 1313 |
// https://forum.freecad.org/viewtopic.php?f=3&t=44057&p=375882#p375882 |
| 1314 |
// See also: |
| 1315 |
// https://en.cppreference.com/w/cpp/types/numeric_limits/digits10 |
| 1316 |
// https://en.cppreference.com/w/cpp/types/numeric_limits/max_digits10 |
| 1317 |
// https://www.boost.org/doc/libs/1_63_0/libs/multiprecision/doc/html/boost_multiprecision/tut/limits/constants.html |
| 1318 |
boost::io::ios_flags_saver ifs(ss); |
| 1319 |
ss << std::setprecision(std::numeric_limits<double>::digits10) << getValue(); |
| 1320 |
|
| 1321 |
/* Trim of any extra spaces */ |
| 1322 |
//while (s.size() > 0 && s[s.size() - 1] == ' ') |
| 1323 |
// s.erase(s.size() - 1); |
| 1324 |
} |
| 1325 |
|
| 1326 |
bool NumberExpression::isInteger(long *l) const { |
| 1327 |
long _l; |
| 1328 |
if(!l) |
| 1329 |
l = &_l; |
| 1330 |
return essentiallyInteger(getValue(),*l); |
| 1331 |
} |
| 1332 |
|
| 1333 |
// |
| 1334 |
// OperatorExpression class |
| 1335 |
// |
| 1336 |
|
| 1337 |
TYPESYSTEM_SOURCE(App::OperatorExpression, App::Expression) |
| 1338 |
|
| 1339 |
OperatorExpression::OperatorExpression(const App::DocumentObject *_owner, Expression * _left, Operator _op, Expression * _right) |
| 1340 |
: UnitExpression(_owner) |
| 1341 |
, op(_op) |
| 1342 |
, left(_left) |
| 1343 |
, right(_right) |
| 1344 |
{ |
| 1345 |
|
| 1346 |
} |
| 1347 |
|
| 1348 |
OperatorExpression::~OperatorExpression() |
| 1349 |
{ |
| 1350 |
delete left; |
| 1351 |
delete right; |
| 1352 |
} |
| 1353 |
|
| 1354 |
/** |
| 1355 |
* Determine whether the expression is touched or not, i.e relies on properties that are touched. |
| 1356 |
*/ |
| 1357 |
|
| 1358 |
bool OperatorExpression::isTouched() const |
| 1359 |
{ |
| 1360 |
return left->isTouched() || right->isTouched(); |
| 1361 |
} |
| 1362 |
|
| 1363 |
static Py::Object calc(const Expression *expr, int op, |
| 1364 |
const Expression *left, const Expression *right, bool inplace) |
| 1365 |
{ |
| 1366 |
Py::Object l = left->getPyValue(); |
| 1367 |
|
| 1368 |
// For security reason, restrict supported types |
| 1369 |
if(!PyObject_TypeCheck(l.ptr(),&PyObjectBase::Type) |
| 1370 |
&& !l.isNumeric() && !l.isString() && !l.isList() && !l.isDict()) |
| 1371 |
{ |
| 1372 |
__EXPR_THROW(Base::TypeError,"Unsupported operator", expr); |
| 1373 |
} |
| 1374 |
|
| 1375 |
// check possible unary operation first |
| 1376 |
switch(op) { |
| 1377 |
case OperatorExpression::POS:{ |
| 1378 |
PyObject *res = PyNumber_Positive(l.ptr()); |
| 1379 |
if(!res) EXPR_PY_THROW(expr); |
| 1380 |
return Py::asObject(res); |
| 1381 |
} |
| 1382 |
case OperatorExpression::NEG:{ |
| 1383 |
PyObject *res = PyNumber_Negative(l.ptr()); |
| 1384 |
if(!res) EXPR_PY_THROW(expr); |
| 1385 |
return Py::asObject(res); |
| 1386 |
} default: |
| 1387 |
break; |
| 1388 |
} |
| 1389 |
|
| 1390 |
Py::Object r = right->getPyValue(); |
| 1391 |
// For security reason, restrict supported types |
| 1392 |
if((op!=OperatorExpression::MOD || !l.isString()) |
| 1393 |
&& !PyObject_TypeCheck(r.ptr(),&PyObjectBase::Type) |
| 1394 |
&& !r.isNumeric() |
| 1395 |
&& !r.isString() |
| 1396 |
&& !r.isList() |
| 1397 |
&& !r.isDict()) |
| 1398 |
{ |
| 1399 |
__EXPR_THROW(Base::TypeError,"Unsupported operator", expr); |
| 1400 |
} |
| 1401 |
|
| 1402 |
switch(op) { |
| 1403 |
#define RICH_COMPARE(_op,_pyop) \ |
| 1404 |
case OperatorExpression::_op: {\ |
| 1405 |
int res = PyObject_RichCompareBool(l.ptr(),r.ptr(),Py_##_pyop);\ |
| 1406 |
if(res<0) EXPR_PY_THROW(expr);\ |
| 1407 |
return Py::Boolean(!!res);\ |
| 1408 |
} |
| 1409 |
RICH_COMPARE(LT,LT) |
| 1410 |
RICH_COMPARE(LTE,LE) |
| 1411 |
RICH_COMPARE(GT,GT) |
| 1412 |
RICH_COMPARE(GTE,GE) |
| 1413 |
RICH_COMPARE(EQ,EQ) |
| 1414 |
RICH_COMPARE(NEQ,NE) |
| 1415 |
|
| 1416 |
#define _BINARY_OP(_pyop) \ |
| 1417 |
res = inplace?PyNumber_InPlace##_pyop(l.ptr(),r.ptr()):\ |
| 1418 |
PyNumber_##_pyop(l.ptr(),r.ptr());\ |
| 1419 |
if(!res) EXPR_PY_THROW(expr);\ |
| 1420 |
return Py::asObject(res); |
| 1421 |
|
| 1422 |
#define BINARY_OP(_op,_pyop) \ |
| 1423 |
case OperatorExpression::_op: {\ |
| 1424 |
PyObject *res;\ |
| 1425 |
_BINARY_OP(_pyop);\ |
| 1426 |
} |
| 1427 |
|
| 1428 |
BINARY_OP(SUB,Subtract) |
| 1429 |
BINARY_OP(MUL,Multiply) |
| 1430 |
BINARY_OP(UNIT,Multiply) |
| 1431 |
BINARY_OP(DIV,TrueDivide) |
| 1432 |
case OperatorExpression::ADD: { |
| 1433 |
PyObject *res; |
| 1434 |
if (PyUnicode_CheckExact(*l) && PyUnicode_CheckExact(*r)) { |
| 1435 |
if(inplace) { |
| 1436 |
res = Py::new_reference_to(l); |
| 1437 |
// Try to make sure ob_refcnt is 1, although unlike |
| 1438 |
// PyString_Resize above, PyUnicode_Append can handle other |
| 1439 |
// cases. |
| 1440 |
l = Py::Object(); |
| 1441 |
PyUnicode_Append(&res, r.ptr()); |
| 1442 |
}else |
| 1443 |
res = PyUnicode_Concat(l.ptr(),r.ptr()); |
| 1444 |
if(!res) EXPR_PY_THROW(expr); |
| 1445 |
return Py::asObject(res); |
| 1446 |
} |
| 1447 |
_BINARY_OP(Add); |
| 1448 |
} |
| 1449 |
case OperatorExpression::POW: { |
| 1450 |
PyObject *res; |
| 1451 |
if(inplace) |
| 1452 |
res = PyNumber_InPlacePower(l.ptr(),r.ptr(),Py::None().ptr()); |
| 1453 |
else |
| 1454 |
res = PyNumber_Power(l.ptr(),r.ptr(),Py::None().ptr()); |
| 1455 |
if(!res) EXPR_PY_THROW(expr); |
| 1456 |
return Py::asObject(res); |
| 1457 |
} |
| 1458 |
case OperatorExpression::MOD: { |
| 1459 |
PyObject *res; |
| 1460 |
if (PyUnicode_CheckExact(l.ptr()) && |
| 1461 |
(!PyUnicode_Check(r.ptr()) || PyUnicode_CheckExact(r.ptr()))) |
| 1462 |
res = PyUnicode_Format(l.ptr(), r.ptr()); |
| 1463 |
else if(inplace) |
| 1464 |
res = PyNumber_InPlaceRemainder(l.ptr(),r.ptr()); |
| 1465 |
else |
| 1466 |
res = PyNumber_InPlaceRemainder(l.ptr(),r.ptr()); |
| 1467 |
if(!res) EXPR_PY_THROW(expr); |
| 1468 |
return Py::asObject(res); |
| 1469 |
} |
| 1470 |
default: |
| 1471 |
__EXPR_THROW(RuntimeError,"Unsupported operator",expr); |
| 1472 |
} |
| 1473 |
} |
| 1474 |
|
| 1475 |
Py::Object OperatorExpression::_getPyValue() const { |
| 1476 |
return calc(this,op,left,right,false); |
| 1477 |
} |
| 1478 |
|
| 1479 |
/** |
| 1480 |
* Simplify the expression. For OperatorExpressions, we return a NumberExpression if |
| 1481 |
* both the left and right side can be simplified to NumberExpressions. In this case |
| 1482 |
* we can calculate the final value of the expression. |
| 1483 |
* |
| 1484 |
* @returns Simplified expression. |
| 1485 |
*/ |
| 1486 |
|
| 1487 |
Expression *OperatorExpression::simplify() const |
| 1488 |
{ |
| 1489 |
Expression * v1 = left->simplify(); |
| 1490 |
Expression * v2 = right->simplify(); |
| 1491 |
|
| 1492 |
// Both arguments reduced to numerics? Then evaluate and return answer |
| 1493 |
if (freecad_cast<NumberExpression*>(v1) && freecad_cast<NumberExpression*>(v2)) { |
| 1494 |
delete v1; |
| 1495 |
delete v2; |
| 1496 |
return eval(); |
| 1497 |
} |
| 1498 |
else |
| 1499 |
return new OperatorExpression(owner, v1, op, v2); |
| 1500 |
} |
| 1501 |
|
| 1502 |
/** |
| 1503 |
* Create a string representation of the expression. |
| 1504 |
* |
| 1505 |
* @returns A string representing the expression. |
| 1506 |
*/ |
| 1507 |
|
| 1508 |
void OperatorExpression::_toString(std::ostream &s, bool persistent,int) const |
| 1509 |
{ |
| 1510 |
bool needsParens; |
| 1511 |
Operator leftOperator(NONE), rightOperator(NONE); |
| 1512 |
|
| 1513 |
needsParens = false; |
| 1514 |
if (freecad_cast<OperatorExpression*>(left)) |
| 1515 |
leftOperator = static_cast<OperatorExpression*>(left)->op; |
| 1516 |
if (left->priority() < priority()) // Check on operator priority first |
| 1517 |
needsParens = true; |
| 1518 |
else if (leftOperator == op) { // Same operator ? |
| 1519 |
if (!isLeftAssociative()) |
| 1520 |
needsParens = true; |
| 1521 |
//else if (!isCommutative()) |
| 1522 |
// needsParens = true; |
| 1523 |
} |
| 1524 |
|
| 1525 |
switch (op) { |
| 1526 |
case NEG: |
| 1527 |
s << "-" << (needsParens ? "(" : "") << left->toString(persistent) << (needsParens ? ")" : ""); |
| 1528 |
return; |
| 1529 |
case POS: |
| 1530 |
s << "+" << (needsParens ? "(" : "") << left->toString(persistent) << (needsParens ? ")" : ""); |
| 1531 |
return; |
| 1532 |
default: |
| 1533 |
break; |
| 1534 |
} |
| 1535 |
|
| 1536 |
if (needsParens) |
| 1537 |
s << "(" << left->toString(persistent) << ")"; |
| 1538 |
else |
| 1539 |
s << left->toString(persistent); |
| 1540 |
|
| 1541 |
switch (op) { |
| 1542 |
case ADD: |
| 1543 |
s << " + "; |
| 1544 |
break; |
| 1545 |
case SUB: |
| 1546 |
s << " - "; |
| 1547 |
break; |
| 1548 |
case MUL: |
| 1549 |
s << " * "; |
| 1550 |
break; |
| 1551 |
case DIV: |
| 1552 |
s << " / "; |
| 1553 |
break; |
| 1554 |
case MOD: |
| 1555 |
s << " % "; |
| 1556 |
break; |
| 1557 |
case POW: |
| 1558 |
s << " ^ "; |
| 1559 |
break; |
| 1560 |
case EQ: |
| 1561 |
s << " == "; |
| 1562 |
break; |
| 1563 |
case NEQ: |
| 1564 |
s << " != "; |
| 1565 |
break; |
| 1566 |
case LT: |
| 1567 |
s << " < "; |
| 1568 |
break; |
| 1569 |
case GT: |
| 1570 |
s << " > "; |
| 1571 |
break; |
| 1572 |
case LTE: |
| 1573 |
s << " <= "; |
| 1574 |
break; |
| 1575 |
case GTE: |
| 1576 |
s << " >= "; |
| 1577 |
break; |
| 1578 |
case UNIT: |
| 1579 |
s << " "; |
| 1580 |
break; |
| 1581 |
default: |
| 1582 |
assert(0); |
| 1583 |
} |
| 1584 |
|
| 1585 |
needsParens = false; |
| 1586 |
if (freecad_cast<OperatorExpression*>(right)) |
| 1587 |
rightOperator = static_cast<OperatorExpression*>(right)->op; |
| 1588 |
if (right->priority() < priority()) // Check on operator priority first |
| 1589 |
needsParens = true; |
| 1590 |
else if (rightOperator == op) { // Same operator ? |
| 1591 |
if (!isRightAssociative()) |
| 1592 |
needsParens = true; |
| 1593 |
else if (!isCommutative()) |
| 1594 |
needsParens = true; |
| 1595 |
} |
| 1596 |
else if (right->priority() == priority()) { // Same priority ? |
| 1597 |
if (!isRightAssociative() || rightOperator == MOD) |
| 1598 |
needsParens = true; |
| 1599 |
} |
| 1600 |
|
| 1601 |
if (needsParens) { |
| 1602 |
s << "("; |
| 1603 |
right->toString(s,persistent); |
| 1604 |
s << ")"; |
| 1605 |
}else |
| 1606 |
right->toString(s,persistent); |
| 1607 |
} |
| 1608 |
|
| 1609 |
/** |
| 1610 |
* A deep copy of the expression. |
| 1611 |
*/ |
| 1612 |
|
| 1613 |
Expression *OperatorExpression::_copy() const |
| 1614 |
{ |
| 1615 |
return new OperatorExpression(owner, left->copy(), op, right->copy()); |
| 1616 |
} |
| 1617 |
|
| 1618 |
/** |
| 1619 |
* Return the operators priority. This is used to add parentheses where |
| 1620 |
* needed when creating a string representation of the expression. |
| 1621 |
* |
| 1622 |
* @returns The operator's priority. |
| 1623 |
*/ |
| 1624 |
|
| 1625 |
int OperatorExpression::priority() const |
| 1626 |
{ |
| 1627 |
switch (op) { |
| 1628 |
case EQ: |
| 1629 |
case NEQ: |
| 1630 |
case LT: |
| 1631 |
case GT: |
| 1632 |
case LTE: |
| 1633 |
case GTE: |
| 1634 |
return 1; |
| 1635 |
case ADD: |
| 1636 |
case SUB: |
| 1637 |
return 3; |
| 1638 |
case MUL: |
| 1639 |
case DIV: |
| 1640 |
case MOD: |
| 1641 |
return 4; |
| 1642 |
case POW: |
| 1643 |
return 5; |
| 1644 |
case UNIT: |
| 1645 |
case NEG: |
| 1646 |
case POS: |
| 1647 |
return 6; |
| 1648 |
default: |
| 1649 |
assert(false); |
| 1650 |
return 0; |
| 1651 |
} |
| 1652 |
} |
| 1653 |
|
| 1654 |
void OperatorExpression::_visit(ExpressionVisitor &v) |
| 1655 |
{ |
| 1656 |
if (left) |
| 1657 |
left->visit(v); |
| 1658 |
if (right) |
| 1659 |
right->visit(v); |
| 1660 |
} |
| 1661 |
|
| 1662 |
bool OperatorExpression::isCommutative() const |
| 1663 |
{ |
| 1664 |
switch (op) { |
| 1665 |
case EQ: |
| 1666 |
case NEQ: |
| 1667 |
case ADD: |
| 1668 |
case MUL: |
| 1669 |
return true; |
| 1670 |
default: |
| 1671 |
return false; |
| 1672 |
} |
| 1673 |
} |
| 1674 |
|
| 1675 |
bool OperatorExpression::isLeftAssociative() const |
| 1676 |
{ |
| 1677 |
return true; |
| 1678 |
} |
| 1679 |
|
| 1680 |
bool OperatorExpression::isRightAssociative() const |
| 1681 |
{ |
| 1682 |
switch (op) { |
| 1683 |
case ADD: |
| 1684 |
case MUL: |
| 1685 |
return true; |
| 1686 |
default: |
| 1687 |
return false; |
| 1688 |
} |
| 1689 |
} |
| 1690 |
|
| 1691 |
// |
| 1692 |
// FunctionExpression class. This class handles functions with one or two parameters. |
| 1693 |
// |
| 1694 |
|
| 1695 |
TYPESYSTEM_SOURCE(App::FunctionExpression, App::UnitExpression) |
| 1696 |
|
| 1697 |
static int _HiddenReference; |
| 1698 |
|
| 1699 |
struct HiddenReference { |
| 1700 |
explicit HiddenReference(bool cond) |
| 1701 |
:cond(cond) |
| 1702 |
{ |
| 1703 |
if(cond) |
| 1704 |
++_HiddenReference; |
| 1705 |
} |
| 1706 |
~HiddenReference() { |
| 1707 |
if(cond) |
| 1708 |
--_HiddenReference; |
| 1709 |
} |
| 1710 |
|
| 1711 |
static bool check(int option) { |
| 1712 |
return (option==Expression::DepNormal && _HiddenReference) |
| 1713 |
|| (option==Expression::DepHidden && !_HiddenReference); |
| 1714 |
} |
| 1715 |
|
| 1716 |
static bool isHidden() { |
| 1717 |
return _HiddenReference!=0; |
| 1718 |
} |
| 1719 |
|
| 1720 |
bool cond; |
| 1721 |
}; |
| 1722 |
|
| 1723 |
FunctionExpression::FunctionExpression(const DocumentObject *_owner, Function _f, std::string &&name, std::vector<Expression *> _args) |
| 1724 |
: UnitExpression(_owner) |
| 1725 |
, f(_f) |
| 1726 |
, fname(std::move(name)) |
| 1727 |
, args(std::move(_args)) |
| 1728 |
{ |
| 1729 |
switch (f) { |
| 1730 |
case ABS: |
| 1731 |
case ACOS: |
| 1732 |
case ASIN: |
| 1733 |
case ATAN: |
| 1734 |
case CBRT: |
| 1735 |
case CEIL: |
| 1736 |
case COS: |
| 1737 |
case COSH: |
| 1738 |
case EXP: |
| 1739 |
case FLOOR: |
| 1740 |
case HIDDENREF: |
| 1741 |
case HREF: |
| 1742 |
case LOG: |
| 1743 |
case LOG10: |
| 1744 |
case MINVERT: |
| 1745 |
case ROTATIONX: |
| 1746 |
case ROTATIONY: |
| 1747 |
case ROTATIONZ: |
| 1748 |
case ROUND: |
| 1749 |
case SIN: |
| 1750 |
case SINH: |
| 1751 |
case SQRT: |
| 1752 |
case STR: |
| 1753 |
case PARSEQUANT: |
| 1754 |
case TAN: |
| 1755 |
case TANH: |
| 1756 |
case TRUNC: |
| 1757 |
case VNORMALIZE: |
| 1758 |
case NOT: |
| 1759 |
if (args.size() != 1) |
| 1760 |
ARGUMENT_THROW("exactly one required."); |
| 1761 |
break; |
| 1762 |
case PLACEMENT: |
| 1763 |
if (args.size() > 3) |
| 1764 |
ARGUMENT_THROW("exactly one, two, or three required."); |
| 1765 |
break; |
| 1766 |
case TRANSLATIONM: |
| 1767 |
if (args.size() != 1 && args.size() != 3) |
| 1768 |
ARGUMENT_THROW("exactly one or three required."); |
| 1769 |
break; |
| 1770 |
case ATAN2: |
| 1771 |
case MOD: |
| 1772 |
case MROTATEX: |
| 1773 |
case MROTATEY: |
| 1774 |
case MROTATEZ: |
| 1775 |
case POW: |
| 1776 |
case VANGLE: |
| 1777 |
case VCROSS: |
| 1778 |
case VDOT: |
| 1779 |
case VSCALEX: |
| 1780 |
case VSCALEY: |
| 1781 |
case VSCALEZ: |
| 1782 |
if (args.size() != 2) |
| 1783 |
ARGUMENT_THROW("exactly two required."); |
| 1784 |
break; |
| 1785 |
case CATH: |
| 1786 |
case HYPOT: |
| 1787 |
case ROTATION: |
| 1788 |
if (args.size() < 2 || args.size() > 3) |
| 1789 |
ARGUMENT_THROW("exactly two, or three required."); |
| 1790 |
break; |
| 1791 |
case MTRANSLATE: |
| 1792 |
case MSCALE: |
| 1793 |
if (args.size() != 2 && args.size() != 4) |
| 1794 |
ARGUMENT_THROW("exactly two or four required."); |
| 1795 |
break; |
| 1796 |
case MROTATE: |
| 1797 |
if (args.size() < 2 || args.size() > 4) |
| 1798 |
ARGUMENT_THROW("exactly two, three, or four required."); |
| 1799 |
break; |
| 1800 |
case VECTOR: |
| 1801 |
case VLINEDIST: |
| 1802 |
case VLINESEGDIST: |
| 1803 |
case VLINEPROJ: |
| 1804 |
case VPLANEDIST: |
| 1805 |
case VPLANEPROJ: |
| 1806 |
if (args.size() != 3) |
| 1807 |
ARGUMENT_THROW("exactly three required."); |
| 1808 |
break; |
| 1809 |
case VSCALE: |
| 1810 |
if (args.size() != 4) |
| 1811 |
ARGUMENT_THROW("exactly four required."); |
| 1812 |
break; |
| 1813 |
case MATRIX: |
| 1814 |
if (args.size() > 16) |
| 1815 |
ARGUMENT_THROW("exactly 16 or less required."); |
| 1816 |
break; |
| 1817 |
case AVERAGE: |
| 1818 |
case COUNT: |
| 1819 |
case CREATE: |
| 1820 |
case MAX: |
| 1821 |
case MIN: |
| 1822 |
case STDDEV: |
| 1823 |
case SUM: |
| 1824 |
case AND: |
| 1825 |
case OR: |
| 1826 |
if (args.empty()) |
| 1827 |
ARGUMENT_THROW("at least one required."); |
| 1828 |
break; |
| 1829 |
case LIST: |
| 1830 |
case TUPLE: |
| 1831 |
break; |
| 1832 |
case AGGREGATES: |
| 1833 |
case LAST: |
| 1834 |
case NONE: |
| 1835 |
default: |
| 1836 |
PARSER_THROW("Unknown function"); |
| 1837 |
break; |
| 1838 |
} |
| 1839 |
} |
| 1840 |
|
| 1841 |
FunctionExpression::~FunctionExpression() |
| 1842 |
{ |
| 1843 |
std::vector<Expression*>::iterator i = args.begin(); |
| 1844 |
|
| 1845 |
while (i != args.end()) { |
| 1846 |
delete *i; |
| 1847 |
++i; |
| 1848 |
} |
| 1849 |
} |
| 1850 |
|
| 1851 |
/** |
| 1852 |
* Determine whether the expressions is considered touched, i.e one or both of its arguments |
| 1853 |
* are touched. |
| 1854 |
* |
| 1855 |
* @return True if touched, false if not. |
| 1856 |
*/ |
| 1857 |
|
| 1858 |
bool FunctionExpression::isTouched() const |
| 1859 |
{ |
| 1860 |
std::vector<Expression*>::const_iterator i = args.begin(); |
| 1861 |
|
| 1862 |
while (i != args.end()) { |
| 1863 |
if ((*i)->isTouched()) |
| 1864 |
return true; |
| 1865 |
++i; |
| 1866 |
} |
| 1867 |
return false; |
| 1868 |
} |
| 1869 |
|
| 1870 |
/* Various collectors for aggregate functions */ |
| 1871 |
|
| 1872 |
class Collector { |
| 1873 |
public: |
| 1874 |
Collector() = default; |
| 1875 |
virtual ~Collector() = default; |
| 1876 |
virtual void collect(Quantity value) { |
| 1877 |
if (first) |
| 1878 |
q.setUnit(value.getUnit()); |
| 1879 |
} |
| 1880 |
virtual Quantity getQuantity() const { |
| 1881 |
return q; |
| 1882 |
} |
| 1883 |
protected: |
| 1884 |
bool first{true}; |
| 1885 |
Quantity q; |
| 1886 |
}; |
| 1887 |
|
| 1888 |
class SumCollector : public Collector { |
| 1889 |
public: |
| 1890 |
SumCollector() : Collector() { } |
| 1891 |
|
| 1892 |
void collect(Quantity value) override { |
| 1893 |
Collector::collect(value); |
| 1894 |
q += value; |
| 1895 |
first = false; |
| 1896 |
} |
| 1897 |
|
| 1898 |
}; |
| 1899 |
|
| 1900 |
class AverageCollector : public Collector { |
| 1901 |
public: |
| 1902 |
AverageCollector() : Collector() { } |
| 1903 |
|
| 1904 |
void collect(Quantity value) override { |
| 1905 |
Collector::collect(value); |
| 1906 |
q += value; |
| 1907 |
++n; |
| 1908 |
first = false; |
| 1909 |
} |
| 1910 |
|
| 1911 |
Quantity getQuantity() const override { return q/(double)n; } |
| 1912 |
|
| 1913 |
private: |
| 1914 |
unsigned int n{0}; |
| 1915 |
}; |
| 1916 |
|
| 1917 |
class StdDevCollector : public Collector { |
| 1918 |
public: |
| 1919 |
StdDevCollector() : Collector() { } |
| 1920 |
|
| 1921 |
void collect(Quantity value) override { |
| 1922 |
Collector::collect(value); |
| 1923 |
if (first) { |
| 1924 |
M2 = Quantity(0, value.getUnit() * value.getUnit()); |
| 1925 |
mean = Quantity(0, value.getUnit()); |
| 1926 |
n = 0; |
| 1927 |
} |
| 1928 |
|
| 1929 |
const Quantity delta = value - mean; |
| 1930 |
++n; |
| 1931 |
mean = mean + delta / n; |
| 1932 |
M2 = M2 + delta * (value - mean); |
| 1933 |
first = false; |
| 1934 |
} |
| 1935 |
|
| 1936 |
Quantity getQuantity() const override { |
| 1937 |
if (n < 2) |
| 1938 |
throw ExpressionError("Invalid number of entries: at least two required."); |
| 1939 |
else |
| 1940 |
return Quantity((M2 / (n - 1.0)).pow(Quantity(0.5)).getValue(), mean.getUnit()); |
| 1941 |
} |
| 1942 |
|
| 1943 |
private: |
| 1944 |
unsigned int n{0}; |
| 1945 |
Quantity mean; |
| 1946 |
Quantity M2; |
| 1947 |
}; |
| 1948 |
|
| 1949 |
class CountCollector : public Collector { |
| 1950 |
public: |
| 1951 |
CountCollector() : Collector() { } |
| 1952 |
|
| 1953 |
void collect(Quantity value) override { |
| 1954 |
Collector::collect(value); |
| 1955 |
++n; |
| 1956 |
first = false; |
| 1957 |
} |
| 1958 |
|
| 1959 |
Quantity getQuantity() const override { return Quantity(n); } |
| 1960 |
|
| 1961 |
private: |
| 1962 |
unsigned int n{0}; |
| 1963 |
}; |
| 1964 |
|
| 1965 |
class MinCollector : public Collector { |
| 1966 |
public: |
| 1967 |
MinCollector() : Collector() { } |
| 1968 |
|
| 1969 |
void collect(Quantity value) override { |
| 1970 |
Collector::collect(value); |
| 1971 |
if (first || value < q) |
| 1972 |
q = value; |
| 1973 |
first = false; |
| 1974 |
} |
| 1975 |
}; |
| 1976 |
|
| 1977 |
class MaxCollector : public Collector { |
| 1978 |
public: |
| 1979 |
MaxCollector() : Collector() { } |
| 1980 |
|
| 1981 |
void collect(Quantity value) override { |
| 1982 |
Collector::collect(value); |
| 1983 |
if (first || value > q) |
| 1984 |
q = value; |
| 1985 |
first = false; |
| 1986 |
} |
| 1987 |
}; |
| 1988 |
|
| 1989 |
class AndCollector : public Collector { |
| 1990 |
public: |
| 1991 |
void collect(Quantity value) override |
| 1992 |
{ |
| 1993 |
if (first) { |
| 1994 |
q = Quantity(asBool(value.getValue()) ? 1 : 0); |
| 1995 |
first = false; |
| 1996 |
return; |
| 1997 |
} |
| 1998 |
if (!asBool(value.getValue())) { |
| 1999 |
q = Quantity(0); |
| 2000 |
} |
| 2001 |
} |
| 2002 |
}; |
| 2003 |
|
| 2004 |
class OrCollector : public Collector { |
| 2005 |
public: |
| 2006 |
void collect(Quantity value) override |
| 2007 |
{ |
| 2008 |
if (first) { |
| 2009 |
q = Quantity(asBool(value.getValue()) ? 1 : 0); |
| 2010 |
first = false; |
| 2011 |
return; |
| 2012 |
} |
| 2013 |
if (asBool(value.getValue())) { |
| 2014 |
q = Quantity(1); |
| 2015 |
} |
| 2016 |
} |
| 2017 |
}; |
| 2018 |
|
| 2019 |
Py::Object FunctionExpression::evalAggregate( |
| 2020 |
const Expression *owner, int f, const std::vector<Expression*> &args) |
| 2021 |
{ |
| 2022 |
std::unique_ptr<Collector> c; |
| 2023 |
|
| 2024 |
switch (f) { |
| 2025 |
case SUM: |
| 2026 |
c = std::make_unique<SumCollector>(); |
| 2027 |
break; |
| 2028 |
case AVERAGE: |
| 2029 |
c = std::make_unique<AverageCollector>(); |
| 2030 |
break; |
| 2031 |
case STDDEV: |
| 2032 |
c = std::make_unique<StdDevCollector>(); |
| 2033 |
break; |
| 2034 |
case COUNT: |
| 2035 |
c = std::make_unique<CountCollector>(); |
| 2036 |
break; |
| 2037 |
case MIN: |
| 2038 |
c = std::make_unique<MinCollector>(); |
| 2039 |
break; |
| 2040 |
case MAX: |
| 2041 |
c = std::make_unique<MaxCollector>(); |
| 2042 |
break; |
| 2043 |
case AND: |
| 2044 |
c = std::make_unique<AndCollector>(); |
| 2045 |
break; |
| 2046 |
case OR: |
| 2047 |
c = std::make_unique<OrCollector>(); |
| 2048 |
break; |
| 2049 |
default: |
| 2050 |
assert(false); |
| 2051 |
} |
| 2052 |
|
| 2053 |
for (auto &arg : args) { |
| 2054 |
if (arg->isDerivedFrom<RangeExpression>()) { |
| 2055 |
Range range(static_cast<const RangeExpression&>(*arg).getRange()); |
| 2056 |
|
| 2057 |
do { |
| 2058 |
Property * p = owner->getOwner()->getPropertyByName(range.address().c_str()); |
| 2059 |
PropertyQuantity * qp; |
| 2060 |
PropertyFloat * fp; |
| 2061 |
PropertyInteger * ip; |
| 2062 |
|
| 2063 |
if (!p) |
| 2064 |
continue; |
| 2065 |
|
| 2066 |
if ((qp = freecad_cast<PropertyQuantity*>(p))) |
| 2067 |
c->collect(qp->getQuantityValue()); |
| 2068 |
else if ((fp = freecad_cast<PropertyFloat*>(p))) |
| 2069 |
c->collect(Quantity(fp->getValue())); |
| 2070 |
else if ((ip = freecad_cast<PropertyInteger*>(p))) |
| 2071 |
c->collect(Quantity(ip->getValue())); |
| 2072 |
else |
| 2073 |
_EXPR_THROW("Invalid property type for aggregate.", owner); |
| 2074 |
} while (range.next()); |
| 2075 |
} |
| 2076 |
else { |
| 2077 |
Quantity q; |
| 2078 |
if(pyToQuantity(q,arg->getPyValue())) |
| 2079 |
c->collect(q); |
| 2080 |
} |
| 2081 |
} |
| 2082 |
|
| 2083 |
return pyFromQuantity(c->getQuantity()); |
| 2084 |
} |
| 2085 |
|
| 2086 |
Base::Vector3d FunctionExpression::evaluateSecondVectorArgument(const Expression *expression, const std::vector<Expression*> &arguments) |
| 2087 |
{ |
| 2088 |
Py::Tuple vectorValues; |
| 2089 |
Py::Object secondParameter = arguments[1]->getPyValue(); |
| 2090 |
|
| 2091 |
if (arguments.size() == 2) { |
| 2092 |
if (!secondParameter.isSequence()) |
| 2093 |
_EXPR_THROW("Second parameter is not a sequence type: '" << secondParameter.as_string() << "'.", expression); |
| 2094 |
if (PySequence_Size(secondParameter.ptr()) != 3) |
| 2095 |
_EXPR_THROW("Second parameter provided has " << PySequence_Size(secondParameter.ptr()) << " elements instead of 3.", expression); |
| 2096 |
|
| 2097 |
vectorValues = Py::Tuple(Py::Sequence(secondParameter)); |
| 2098 |
} else { |
| 2099 |
vectorValues = Py::Tuple(3); |
| 2100 |
vectorValues.setItem(0, secondParameter); |
| 2101 |
vectorValues.setItem(1, arguments[2]->getPyValue()); |
| 2102 |
vectorValues.setItem(2, arguments[3]->getPyValue()); |
| 2103 |
} |
| 2104 |
|
| 2105 |
Vector3d vector; |
| 2106 |
if (!PyArg_ParseTuple(vectorValues.ptr(), "ddd", &vector.x, &vector.y, &vector.z)) { |
| 2107 |
PyErr_Clear(); |
| 2108 |
_EXPR_THROW("Error parsing scale values.", expression); |
| 2109 |
} |
| 2110 |
|
| 2111 |
return vector; |
| 2112 |
} |
| 2113 |
|
| 2114 |
void FunctionExpression::initialiseObject(const Py::Object *object, const std::vector<Expression*> &arguments, const unsigned long offset) |
| 2115 |
{ |
| 2116 |
if (arguments.size() > offset) { |
| 2117 |
Py::Tuple constructorArguments(arguments.size() - offset); |
| 2118 |
for (unsigned i = offset; i < arguments.size(); ++i) |
| 2119 |
constructorArguments.setItem(i - offset, arguments[i]->getPyValue()); |
| 2120 |
Py::Dict kwd; |
| 2121 |
PyObjectBase::__PyInit(object->ptr(), constructorArguments.ptr(), kwd.ptr()); |
| 2122 |
} |
| 2123 |
} |
| 2124 |
|
| 2125 |
Py::Object FunctionExpression::transformFirstArgument( |
| 2126 |
const Expression* expression, |
| 2127 |
const std::vector<Expression*> &arguments, |
| 2128 |
const Base::Matrix4D* transformationMatrix |
| 2129 |
) |
| 2130 |
{ |
| 2131 |
Py::Object target = arguments[0]->getPyValue(); |
| 2132 |
|
| 2133 |
if (PyObject_TypeCheck(target.ptr(), &Base::MatrixPy::Type)) { |
| 2134 |
Base::Matrix4D matrix = static_cast<Base::MatrixPy*>(target.ptr())->value(); |
| 2135 |
return Py::asObject(new Base::MatrixPy(*transformationMatrix * matrix)); |
| 2136 |
} else if (PyObject_TypeCheck(target.ptr(), &Base::PlacementPy::Type)) { |
| 2137 |
Base::Matrix4D placementMatrix = |
| 2138 |
static_cast<Base::PlacementPy*>(target.ptr())->getPlacementPtr()->toMatrix(); |
| 2139 |
return Py::asObject(new Base::PlacementPy(Base::Placement(*transformationMatrix * placementMatrix))); |
| 2140 |
} else if (PyObject_TypeCheck(target.ptr(), &Base::RotationPy::Type)) { |
| 2141 |
Base::Matrix4D rotatioMatrix; |
| 2142 |
static_cast<Base::RotationPy*>(target.ptr())->getRotationPtr()->getValue(rotatioMatrix); |
| 2143 |
return Py::asObject(new Base::RotationPy(Base::Rotation(*transformationMatrix * rotatioMatrix))); |
| 2144 |
} |
| 2145 |
|
| 2146 |
_EXPR_THROW("Function requires the first argument to be either Matrix, Placement or Rotation.", expression); |
| 2147 |
} |
| 2148 |
|
| 2149 |
Py::Object FunctionExpression::translationMatrix(double x, double y, double z) |
| 2150 |
{ |
| 2151 |
Base::Matrix4D matrix; |
| 2152 |
matrix.move(x, y, z); |
| 2153 |
return Py::asObject(new Base::MatrixPy(matrix)); |
| 2154 |
} |
| 2155 |
|
| 2156 |
double FunctionExpression::extractLengthValueArgument( |
| 2157 |
const Expression *expression, |
| 2158 |
const std::vector<Expression*> &arguments, |
| 2159 |
int argumentIndex |
| 2160 |
) |
| 2161 |
{ |
| 2162 |
Quantity argumentQuantity = pyToQuantity(arguments[argumentIndex]->getPyValue(), expression); |
| 2163 |
|
| 2164 |
if (!(argumentQuantity.isDimensionlessOrUnit(Unit::Length))) { |
| 2165 |
_EXPR_THROW("Unit must be either empty or a length.", expression); |
| 2166 |
} |
| 2167 |
|
| 2168 |
return argumentQuantity.getValue(); |
| 2169 |
} |
| 2170 |
|
| 2171 |
Base::Vector3d FunctionExpression::extractVectorArgument( |
| 2172 |
const Expression *expression, |
| 2173 |
const std::vector<Expression*> &arguments, |
| 2174 |
int argumentIndex |
| 2175 |
) |
| 2176 |
{ |
| 2177 |
Py::Object argument = arguments[argumentIndex]->getPyValue(); |
| 2178 |
|
| 2179 |
if (!PyObject_TypeCheck(argument.ptr(), &Base::VectorPy::Type)) { |
| 2180 |
_EXPR_THROW("Argument must be a vector.", expression); |
| 2181 |
} |
| 2182 |
|
| 2183 |
return static_cast<Base::VectorPy*>(argument.ptr())->value(); |
| 2184 |
} |
| 2185 |
|
| 2186 |
Py::Object FunctionExpression::evaluate(const Expression *expr, int f, const std::vector<Expression*> &args) |
| 2187 |
{ |
| 2188 |
using std::numbers::pi; |
| 2189 |
|
| 2190 |
if(!expr || !expr->getOwner()) |
| 2191 |
_EXPR_THROW("Invalid owner.", expr); |
| 2192 |
|
| 2193 |
// Handle aggregate functions |
| 2194 |
if (f > AGGREGATES) |
| 2195 |
return evalAggregate(expr, f, args); |
| 2196 |
|
| 2197 |
switch (f) { |
| 2198 |
case LIST: { |
| 2199 |
if (args.size() == 1 && args[0]->isDerivedFrom<RangeExpression>()) |
| 2200 |
return args[0]->getPyValue(); |
| 2201 |
Py::List list(args.size()); |
| 2202 |
int i = 0; |
| 2203 |
for (auto &arg : args) |
| 2204 |
list.setItem(i++, arg->getPyValue()); |
| 2205 |
return list; |
| 2206 |
} |
| 2207 |
case TUPLE: { |
| 2208 |
if (args.size() == 1 && args[0]->isDerivedFrom<RangeExpression>()) |
| 2209 |
return Py::Tuple(args[0]->getPyValue()); |
| 2210 |
Py::Tuple tuple(args.size()); |
| 2211 |
int i = 0; |
| 2212 |
for (auto &arg : args) |
| 2213 |
tuple.setItem(i++, arg->getPyValue()); |
| 2214 |
return tuple; |
| 2215 |
} |
| 2216 |
} |
| 2217 |
|
| 2218 |
if(args.empty()) |
| 2219 |
_EXPR_THROW("Function requires at least one argument.",expr); |
| 2220 |
|
| 2221 |
switch (f) { |
| 2222 |
case MINVERT: { |
| 2223 |
Py::Object pyobj = args[0]->getPyValue(); |
| 2224 |
if (PyObject_TypeCheck(pyobj.ptr(), &Base::MatrixPy::Type)) { |
| 2225 |
auto m = static_cast<Base::MatrixPy*>(pyobj.ptr())->value(); |
| 2226 |
if (fabs(m.determinant()) <= std::numeric_limits<double>::epsilon()) |
| 2227 |
_EXPR_THROW("Cannot invert singular matrix.", expr); |
| 2228 |
m.inverseGauss(); |
| 2229 |
return Py::asObject(new Base::MatrixPy(m)); |
| 2230 |
} else if (PyObject_TypeCheck(pyobj.ptr(), &Base::PlacementPy::Type)) { |
| 2231 |
const auto &pla = *static_cast<Base::PlacementPy*>(pyobj.ptr())->getPlacementPtr(); |
| 2232 |
return Py::asObject(new Base::PlacementPy(pla.inverse())); |
| 2233 |
} else if (PyObject_TypeCheck(pyobj.ptr(), &Base::RotationPy::Type)) { |
| 2234 |
const auto &rot = *static_cast<Base::RotationPy*>(pyobj.ptr())->getRotationPtr(); |
| 2235 |
return Py::asObject(new Base::RotationPy(rot.inverse())); |
| 2236 |
} |
| 2237 |
_EXPR_THROW( |
| 2238 |
"Function requires the first argument to be either Matrix, Placement or Rotation.", |
| 2239 |
expr); |
| 2240 |
break; |
| 2241 |
} |
| 2242 |
case MROTATE: { |
| 2243 |
Py::Object rotationObject = args[1]->getPyValue(); |
| 2244 |
if (!PyObject_TypeCheck(rotationObject.ptr(), &Base::RotationPy::Type)) |
| 2245 |
{ |
| 2246 |
rotationObject = Py::asObject(new Base::RotationPy(Base::Rotation())); |
| 2247 |
initialiseObject(&rotationObject, args, 1); |
| 2248 |
} |
| 2249 |
|
| 2250 |
Base::Matrix4D rotationMatrix; |
| 2251 |
static_cast<Base::RotationPy*>(rotationObject.ptr())->getRotationPtr()->getValue(rotationMatrix); |
| 2252 |
|
| 2253 |
return transformFirstArgument(expr, args, &rotationMatrix); |
| 2254 |
} |
| 2255 |
case MROTATEX: |
| 2256 |
case MROTATEY: |
| 2257 |
case MROTATEZ: |
| 2258 |
{ |
| 2259 |
Py::Object rotationAngleParameter = args[1]->getPyValue(); |
| 2260 |
Quantity rotationAngle = pyToQuantity(rotationAngleParameter, expr, "Invalid rotation angle."); |
| 2261 |
|
| 2262 |
if (!(rotationAngle.isDimensionlessOrUnit(Unit::Angle))) |
| 2263 |
_EXPR_THROW("Unit must be either empty or an angle.", expr); |
| 2264 |
|
| 2265 |
Rotation rotation = Base::Rotation( |
| 2266 |
Vector3d(static_cast<double>(f == MROTATEX), static_cast<double>(f == MROTATEY), static_cast<double>(f == MROTATEZ)), |
| 2267 |
Base::toRadians(rotationAngle.getValue())); |
| 2268 |
Base::Matrix4D rotationMatrix; |
| 2269 |
rotation.getValue(rotationMatrix); |
| 2270 |
|
| 2271 |
return transformFirstArgument(expr, args, &rotationMatrix); |
| 2272 |
} |
| 2273 |
case MSCALE: { |
| 2274 |
Vector3d scaleValues = evaluateSecondVectorArgument(expr, args); |
| 2275 |
|
| 2276 |
Base::Matrix4D scaleMatrix; |
| 2277 |
scaleMatrix.scale(scaleValues); |
| 2278 |
|
| 2279 |
return transformFirstArgument(expr, args, &scaleMatrix); |
| 2280 |
} |
| 2281 |
case MTRANSLATE: { |
| 2282 |
Vector3d translateValues = evaluateSecondVectorArgument(expr, args); |
| 2283 |
|
| 2284 |
Base::Matrix4D translateMatrix; |
| 2285 |
translateMatrix.move(translateValues); |
| 2286 |
|
| 2287 |
Py::Object target = args[0]->getPyValue(); |
| 2288 |
if (PyObject_TypeCheck(target.ptr(), &Base::RotationPy::Type)) { |
| 2289 |
Base::Matrix4D targetRotatioMatrix; |
| 2290 |
static_cast<Base::RotationPy*>(target.ptr())->getRotationPtr()->getValue(targetRotatioMatrix); |
| 2291 |
return Py::asObject(new Base::PlacementPy(Base::Placement(translateMatrix * targetRotatioMatrix))); |
| 2292 |
} |
| 2293 |
|
| 2294 |
return transformFirstArgument(expr, args, &translateMatrix); |
| 2295 |
} |
| 2296 |
case CREATE: { |
| 2297 |
Py::Object pytype = args[0]->getPyValue(); |
| 2298 |
if (!pytype.isString()) |
| 2299 |
_EXPR_THROW("Function requires the first argument to be a string.", expr); |
| 2300 |
std::string type(pytype.as_string()); |
| 2301 |
Py::Object res; |
| 2302 |
if (boost::iequals(type, "matrix")) |
| 2303 |
res = Py::asObject(new Base::MatrixPy(Base::Matrix4D())); |
| 2304 |
else if (boost::iequals(type, "vector")) |
| 2305 |
res = Py::asObject(new Base::VectorPy(Base::Vector3d())); |
| 2306 |
else if (boost::iequals(type, "placement")) |
| 2307 |
res = Py::asObject(new Base::PlacementPy(Base::Placement())); |
| 2308 |
else if (boost::iequals(type, "rotation")) |
| 2309 |
res = Py::asObject(new Base::RotationPy(Base::Rotation())); |
| 2310 |
else |
| 2311 |
_EXPR_THROW("Unknown type '" << type << "'.", expr); |
| 2312 |
initialiseObject(&res, args, 1); |
| 2313 |
return res; |
| 2314 |
} |
| 2315 |
case MATRIX: { |
| 2316 |
Py::Object matrix = Py::asObject(new Base::MatrixPy(Base::Matrix4D())); |
| 2317 |
initialiseObject(&matrix, args); |
| 2318 |
return matrix; |
| 2319 |
} |
| 2320 |
case PLACEMENT: { |
| 2321 |
Py::Object placement = Py::asObject(new Base::PlacementPy(Base::Placement())); |
| 2322 |
initialiseObject(&placement, args); |
| 2323 |
return placement; |
| 2324 |
} |
| 2325 |
case ROTATION: { |
| 2326 |
Py::Object rotation = Py::asObject(new Base::RotationPy(Base::Rotation())); |
| 2327 |
initialiseObject(&rotation, args); |
| 2328 |
return rotation; |
| 2329 |
} |
| 2330 |
case STR: |
| 2331 |
return Py::String(args[0]->getPyValue().as_string()); |
| 2332 |
case PARSEQUANT: { |
| 2333 |
auto quantity_text = args[0]->getPyValue().as_string(); |
| 2334 |
auto quantity_object = Quantity::parse(quantity_text); |
| 2335 |
return Py::asObject(new QuantityPy(new Quantity(quantity_object))); |
| 2336 |
} |
| 2337 |
case TRANSLATIONM: { |
| 2338 |
if (args.size() != 1) |
| 2339 |
break; // Break and proceed to 3 size version. |
| 2340 |
Py::Object parameter = args[0]->getPyValue(); |
| 2341 |
if (!parameter.isSequence()) |
| 2342 |
_EXPR_THROW("Not sequence type: '" << parameter.as_string() << "'.", expr); |
| 2343 |
if (PySequence_Size(parameter.ptr()) != 3) |
| 2344 |
_EXPR_THROW("Sequence provided has " << PySequence_Size(parameter.ptr()) << " elements instead of 3.", expr); |
| 2345 |
double x, y, z; |
| 2346 |
if (!PyArg_ParseTuple(Py::Tuple(Py::Sequence(parameter)).ptr(), "ddd", &x, &y, &z)) { |
| 2347 |
PyErr_Clear(); |
| 2348 |
_EXPR_THROW("Error parsing sequence.", expr); |
| 2349 |
} |
| 2350 |
return translationMatrix(x, y, z); |
| 2351 |
} |
| 2352 |
case VECTOR: { |
| 2353 |
Py::Object vector = Py::asObject(new Base::VectorPy(Base::Vector3d())); |
| 2354 |
initialiseObject(&vector, args); |
| 2355 |
return vector; |
| 2356 |
} |
| 2357 |
case HIDDENREF: |
| 2358 |
case HREF: |
| 2359 |
return args[0]->getPyValue(); |
| 2360 |
case VANGLE: |
| 2361 |
case VCROSS: |
| 2362 |
case VDOT: |
| 2363 |
case VLINEDIST: |
| 2364 |
case VLINESEGDIST: |
| 2365 |
case VLINEPROJ: |
| 2366 |
case VNORMALIZE: |
| 2367 |
case VPLANEDIST: |
| 2368 |
case VPLANEPROJ: |
| 2369 |
case VSCALE: |
| 2370 |
case VSCALEX: |
| 2371 |
case VSCALEY: |
| 2372 |
case VSCALEZ: { |
| 2373 |
Base::Vector3d vector1 = extractVectorArgument(expr, args, 0); |
| 2374 |
|
| 2375 |
switch (f) { |
| 2376 |
case VNORMALIZE: |
| 2377 |
return Py::asObject(new Base::VectorPy(vector1.Normalize())); |
| 2378 |
case VSCALE: { |
| 2379 |
double scaleX = extractLengthValueArgument(expr, args, 1); |
| 2380 |
double scaleY = extractLengthValueArgument(expr, args, 2); |
| 2381 |
double scaleZ = extractLengthValueArgument(expr, args, 3); |
| 2382 |
vector1.Scale(scaleX, scaleY, scaleZ); |
| 2383 |
return Py::asObject(new Base::VectorPy(vector1)); |
| 2384 |
} |
| 2385 |
case VSCALEX: { |
| 2386 |
double scaleX = extractLengthValueArgument(expr, args, 1); |
| 2387 |
vector1.ScaleX(scaleX); |
| 2388 |
return Py::asObject(new Base::VectorPy(vector1)); |
| 2389 |
} |
| 2390 |
case VSCALEY: { |
| 2391 |
double scaleY = extractLengthValueArgument(expr, args, 1); |
| 2392 |
vector1.ScaleY(scaleY); |
| 2393 |
return Py::asObject(new Base::VectorPy(vector1)); |
| 2394 |
} |
| 2395 |
case VSCALEZ: { |
| 2396 |
double scaleZ = extractLengthValueArgument(expr, args, 1); |
| 2397 |
vector1.ScaleZ(scaleZ); |
| 2398 |
return Py::asObject(new Base::VectorPy(vector1)); |
| 2399 |
} |
| 2400 |
} |
| 2401 |
|
| 2402 |
Base::Vector3d vector2 = extractVectorArgument(expr, args, 1); |
| 2403 |
|
| 2404 |
switch (f) { |
| 2405 |
case VANGLE: |
| 2406 |
return Py::asObject(new QuantityPy(new Quantity(Base::toDegrees(vector1.GetAngle(vector2)), Unit::Angle))); |
| 2407 |
case VCROSS: |
| 2408 |
return Py::asObject(new Base::VectorPy(vector1.Cross(vector2))); |
| 2409 |
case VDOT: |
| 2410 |
return Py::Float(vector1.Dot(vector2)); |
| 2411 |
} |
| 2412 |
|
| 2413 |
Base::Vector3d vector3 = extractVectorArgument(expr, args, 2); |
| 2414 |
|
| 2415 |
switch (f) { |
| 2416 |
case VLINEDIST: |
| 2417 |
return Py::asObject(new QuantityPy(new Quantity(vector1.DistanceToLine(vector2, vector3), Unit::Length))); |
| 2418 |
case VLINESEGDIST: |
| 2419 |
return Py::asObject(new Base::VectorPy(vector1.DistanceToLineSegment(vector2, vector3))); |
| 2420 |
case VLINEPROJ: |
| 2421 |
vector1.ProjectToLine(vector2, vector3); |
| 2422 |
return Py::asObject(new Base::VectorPy(vector1)); |
| 2423 |
case VPLANEDIST: |
| 2424 |
return Py::asObject(new QuantityPy(new Quantity(vector1.DistanceToPlane(vector2, vector3), Unit::Length))); |
| 2425 |
case VPLANEPROJ: |
| 2426 |
vector1.ProjectToPlane(vector2, vector3); |
| 2427 |
return Py::asObject(new Base::VectorPy(vector1)); |
| 2428 |
} |
| 2429 |
} |
| 2430 |
} |
| 2431 |
|
| 2432 |
Py::Object e1 = args[0]->getPyValue(); |
| 2433 |
Quantity v1 = pyToQuantity(e1,expr,"Invalid first argument."); |
| 2434 |
Py::Object e2; |
| 2435 |
Quantity v2; |
| 2436 |
if (args.size() > 1) { |
| 2437 |
e2 = args[1]->getPyValue(); |
| 2438 |
v2 = pyToQuantity(e2,expr,"Invalid second argument."); |
| 2439 |
} |
| 2440 |
Py::Object e3; |
| 2441 |
Quantity v3; |
| 2442 |
if (args.size() > 2) { |
| 2443 |
e3 = args[2]->getPyValue(); |
| 2444 |
v3 = pyToQuantity(e3,expr,"Invalid third argument."); |
| 2445 |
} |
| 2446 |
|
| 2447 |
double output; |
| 2448 |
Unit unit; |
| 2449 |
double scaler = 1; |
| 2450 |
|
| 2451 |
double value = v1.getValue(); |
| 2452 |
|
| 2453 |
/* Check units and arguments */ |
| 2454 |
switch (f) { |
| 2455 |
case COS: |
| 2456 |
case SIN: |
| 2457 |
case TAN: |
| 2458 |
case ROTATIONX: |
| 2459 |
case ROTATIONY: |
| 2460 |
case ROTATIONZ: |
| 2461 |
if (!(v1.isDimensionlessOrUnit(Unit::Angle))) |
| 2462 |
_EXPR_THROW("Unit must be either empty or an angle.", expr); |
| 2463 |
|
| 2464 |
// Convert value to radians |
| 2465 |
value = Base::toRadians(value); |
| 2466 |
unit = Unit(); |
| 2467 |
break; |
| 2468 |
case ACOS: |
| 2469 |
case ASIN: |
| 2470 |
case ATAN: |
| 2471 |
if (!v1.isDimensionless()) |
| 2472 |
_EXPR_THROW("Unit must be empty.", expr); |
| 2473 |
unit = Unit::Angle; |
| 2474 |
scaler = 180.0 / pi; |
| 2475 |
break; |
| 2476 |
case EXP: |
| 2477 |
case LOG: |
| 2478 |
case LOG10: |
| 2479 |
case SINH: |
| 2480 |
case TANH: |
| 2481 |
case COSH: |
| 2482 |
if (!v1.isDimensionless()) |
| 2483 |
_EXPR_THROW("Unit must be empty.",expr); |
| 2484 |
unit = Unit(); |
| 2485 |
break; |
| 2486 |
case ROUND: |
| 2487 |
case TRUNC: |
| 2488 |
case CEIL: |
| 2489 |
case FLOOR: |
| 2490 |
case ABS: |
| 2491 |
unit = v1.getUnit(); |
| 2492 |
break; |
| 2493 |
case SQRT: |
| 2494 |
unit = v1.getUnit().sqrt(); |
| 2495 |
break; |
| 2496 |
case CBRT: |
| 2497 |
unit = v1.getUnit().cbrt(); |
| 2498 |
break; |
| 2499 |
case ATAN2: |
| 2500 |
if (e2.isNone()) |
| 2501 |
_EXPR_THROW("Invalid second argument.",expr); |
| 2502 |
|
| 2503 |
if (v1.getUnit() != v2.getUnit()) |
| 2504 |
_EXPR_THROW("Units must be equal.",expr); |
| 2505 |
unit = Unit::Angle; |
| 2506 |
scaler = 180.0 / pi; |
| 2507 |
break; |
| 2508 |
case MOD: |
| 2509 |
if (e2.isNone()) |
| 2510 |
_EXPR_THROW("Invalid second argument.",expr); |
| 2511 |
if (v1.getUnit() != v2.getUnit() && !v1.isDimensionless() && !v2.isDimensionless()) |
| 2512 |
_EXPR_THROW("Units must be equal or dimensionless.",expr); |
| 2513 |
unit = v1.getUnit(); |
| 2514 |
break; |
| 2515 |
case POW: { |
| 2516 |
if (e2.isNone()) |
| 2517 |
_EXPR_THROW("Invalid second argument.",expr); |
| 2518 |
|
| 2519 |
if (!v2.isDimensionless()) |
| 2520 |
_EXPR_THROW("Exponent is not allowed to have a unit.",expr); |
| 2521 |
|
| 2522 |
// Compute new unit for exponentiation |
| 2523 |
double exponent = v2.getValue(); |
| 2524 |
if (!v1.isDimensionless()) { |
| 2525 |
if (exponent - boost::math::round(exponent) < 1e-9) |
| 2526 |
unit = v1.getUnit().pow(exponent); |
| 2527 |
else |
| 2528 |
_EXPR_THROW("Exponent must be an integer when used with a unit.",expr); |
| 2529 |
} |
| 2530 |
break; |
| 2531 |
} |
| 2532 |
case HYPOT: |
| 2533 |
case CATH: |
| 2534 |
if (e2.isNone()) |
| 2535 |
_EXPR_THROW("Invalid second argument.",expr); |
| 2536 |
if (v1.getUnit() != v2.getUnit()) |
| 2537 |
_EXPR_THROW("Units must be equal.",expr); |
| 2538 |
|
| 2539 |
if (args.size() > 2) { |
| 2540 |
if (e3.isNone()) |
| 2541 |
_EXPR_THROW("Invalid second argument.",expr); |
| 2542 |
if (v2.getUnit() != v3.getUnit()) |
| 2543 |
_EXPR_THROW("Units must be equal.",expr); |
| 2544 |
} |
| 2545 |
unit = v1.getUnit(); |
| 2546 |
break; |
| 2547 |
case TRANSLATIONM: |
| 2548 |
if (v1.isDimensionlessOrUnit(Unit::Length) && v2.isDimensionlessOrUnit(Unit::Length) && v3.isDimensionlessOrUnit(Unit::Length)) |
| 2549 |
break; |
| 2550 |
_EXPR_THROW("Translation units must be a length or dimensionless.", expr); |
| 2551 |
case NOT: |
| 2552 |
unit = Unit(); |
| 2553 |
break; |
| 2554 |
default: |
| 2555 |
_EXPR_THROW("Unknown function: " << f,0); |
| 2556 |
} |
| 2557 |
|
| 2558 |
/* Compute result */ |
| 2559 |
switch (f) { |
| 2560 |
case ACOS: |
| 2561 |
output = acos(value); |
| 2562 |
break; |
| 2563 |
case ASIN: |
| 2564 |
output = asin(value); |
| 2565 |
break; |
| 2566 |
case ATAN: |
| 2567 |
output = atan(value); |
| 2568 |
break; |
| 2569 |
case ABS: |
| 2570 |
output = fabs(value); |
| 2571 |
break; |
| 2572 |
case EXP: |
| 2573 |
output = exp(value); |
| 2574 |
break; |
| 2575 |
case LOG: |
| 2576 |
output = log(value); |
| 2577 |
break; |
| 2578 |
case LOG10: |
| 2579 |
output = log(value) / log(10.0); |
| 2580 |
break; |
| 2581 |
case SIN: |
| 2582 |
output = sin(value); |
| 2583 |
break; |
| 2584 |
case SINH: |
| 2585 |
output = sinh(value); |
| 2586 |
break; |
| 2587 |
case TAN: |
| 2588 |
output = tan(value); |
| 2589 |
break; |
| 2590 |
case TANH: |
| 2591 |
output = tanh(value); |
| 2592 |
break; |
| 2593 |
case SQRT: |
| 2594 |
output = sqrt(value); |
| 2595 |
break; |
| 2596 |
case CBRT: |
| 2597 |
output = cbrt(value); |
| 2598 |
break; |
| 2599 |
case COS: |
| 2600 |
output = cos(value); |
| 2601 |
break; |
| 2602 |
case COSH: |
| 2603 |
output = cosh(value); |
| 2604 |
break; |
| 2605 |
case MOD: { |
| 2606 |
output = fmod(value, v2.getValue()); |
| 2607 |
break; |
| 2608 |
} |
| 2609 |
case ATAN2: { |
| 2610 |
output = atan2(value, v2.getValue()); |
| 2611 |
break; |
| 2612 |
} |
| 2613 |
case POW: { |
| 2614 |
output = pow(value, v2.getValue()); |
| 2615 |
break; |
| 2616 |
} |
| 2617 |
case HYPOT: { |
| 2618 |
output = sqrt(pow(v1.getValue(), 2) + pow(v2.getValue(), 2) + (!e3.isNone() ? pow(v3.getValue(), 2) : 0)); |
| 2619 |
break; |
| 2620 |
} |
| 2621 |
case CATH: { |
| 2622 |
output = sqrt(pow(v1.getValue(), 2) - pow(v2.getValue(), 2) - (!e3.isNone() ? pow(v3.getValue(), 2) : 0)); |
| 2623 |
break; |
| 2624 |
} |
| 2625 |
case ROUND: |
| 2626 |
output = boost::math::round(value); |
| 2627 |
break; |
| 2628 |
case TRUNC: |
| 2629 |
output = boost::math::trunc(value); |
| 2630 |
break; |
| 2631 |
case CEIL: |
| 2632 |
output = ceil(value); |
| 2633 |
break; |
| 2634 |
case FLOOR: |
| 2635 |
output = floor(value); |
| 2636 |
break; |
| 2637 |
case ROTATIONX: |
| 2638 |
case ROTATIONY: |
| 2639 |
case ROTATIONZ: |
| 2640 |
return Py::asObject(new Base::RotationPy(Base::Rotation( |
| 2641 |
Vector3d(static_cast<double>(f == ROTATIONX), static_cast<double>(f == ROTATIONY), static_cast<double>(f == ROTATIONZ)), |
| 2642 |
value))); |
| 2643 |
case TRANSLATIONM: |
| 2644 |
return translationMatrix(v1.getValue(), v2.getValue(), v3.getValue()); |
| 2645 |
case NOT: |
| 2646 |
output = asBool(value) ? 0 : 1; |
| 2647 |
break; |
| 2648 |
default: |
| 2649 |
_EXPR_THROW("Unknown function: " << f,0); |
| 2650 |
} |
| 2651 |
|
| 2652 |
return Py::asObject(new QuantityPy(new Quantity(scaler * output, unit))); |
| 2653 |
} |
| 2654 |
|
| 2655 |
Py::Object FunctionExpression::_getPyValue() const { |
| 2656 |
return evaluate(this,f,args); |
| 2657 |
} |
| 2658 |
|
| 2659 |
/** |
| 2660 |
* Try to simplify the expression, i.e calculate all constant expressions. |
| 2661 |
* |
| 2662 |
* @returns A simplified expression. |
| 2663 |
*/ |
| 2664 |
|
| 2665 |
Expression *FunctionExpression::simplify() const |
| 2666 |
{ |
| 2667 |
size_t numerics = 0; |
| 2668 |
std::vector<Expression*> simplifiedArgs; |
| 2669 |
|
| 2670 |
// Try to simplify each argument to function |
| 2671 |
for (auto it : args) { |
| 2672 |
Expression * v = it->simplify(); |
| 2673 |
|
| 2674 |
if (freecad_cast<NumberExpression*>(v)) |
| 2675 |
++numerics; |
| 2676 |
simplifiedArgs.push_back(v); |
| 2677 |
} |
| 2678 |
|
| 2679 |
if (numerics == args.size()) { |
| 2680 |
// All constants, then evaluation must also be constant |
| 2681 |
|
| 2682 |
// Clean-up the simplified arguments |
| 2683 |
for (auto it : simplifiedArgs) |
| 2684 |
delete it; |
| 2685 |
|
| 2686 |
return eval(); |
| 2687 |
} |
| 2688 |
else |
| 2689 |
return new FunctionExpression(owner, f, std::string(fname), |
| 2690 |
std::move(simplifiedArgs)); |
| 2691 |
} |
| 2692 |
|
| 2693 |
/** |
| 2694 |
* Create a string representation of the expression. |
| 2695 |
* |
| 2696 |
* @returns A string representing the expression. |
| 2697 |
*/ |
| 2698 |
|
| 2699 |
void FunctionExpression::_toString(std::ostream &ss, bool persistent,int) const |
| 2700 |
{ |
| 2701 |
switch (f) { |
| 2702 |
case ABS: |
| 2703 |
ss << "abs("; break;; |
| 2704 |
case ACOS: |
| 2705 |
ss << "acos("; break;; |
| 2706 |
case ASIN: |
| 2707 |
ss << "asin("; break;; |
| 2708 |
case ATAN: |
| 2709 |
ss << "atan("; break;; |
| 2710 |
case ATAN2: |
| 2711 |
ss << "atan2("; break;; |
| 2712 |
case CATH: |
| 2713 |
ss << "cath("; break;; |
| 2714 |
case CBRT: |
| 2715 |
ss << "cbrt("; break;; |
| 2716 |
case CEIL: |
| 2717 |
ss << "ceil("; break;; |
| 2718 |
case COS: |
| 2719 |
ss << "cos("; break;; |
| 2720 |
case COSH: |
| 2721 |
ss << "cosh("; break;; |
| 2722 |
case EXP: |
| 2723 |
ss << "exp("; break;; |
| 2724 |
case FLOOR: |
| 2725 |
ss << "floor("; break;; |
| 2726 |
case HYPOT: |
| 2727 |
ss << "hypot("; break;; |
| 2728 |
case LOG: |
| 2729 |
ss << "log("; break;; |
| 2730 |
case LOG10: |
| 2731 |
ss << "log10("; break;; |
| 2732 |
case MOD: |
| 2733 |
ss << "mod("; break;; |
| 2734 |
case POW: |
| 2735 |
ss << "pow("; break;; |
| 2736 |
case ROUND: |
| 2737 |
ss << "round("; break;; |
| 2738 |
case SIN: |
| 2739 |
ss << "sin("; break;; |
| 2740 |
case SINH: |
| 2741 |
ss << "sinh("; break;; |
| 2742 |
case SQRT: |
| 2743 |
ss << "sqrt("; break;; |
| 2744 |
case TAN: |
| 2745 |
ss << "tan("; break;; |
| 2746 |
case TANH: |
| 2747 |
ss << "tanh("; break;; |
| 2748 |
case TRUNC: |
| 2749 |
ss << "trunc("; break;; |
| 2750 |
case VANGLE: |
| 2751 |
ss << "vangle("; break;; |
| 2752 |
case VCROSS: |
| 2753 |
ss << "vcross("; break;; |
| 2754 |
case VDOT: |
| 2755 |
ss << "vdot("; break;; |
| 2756 |
case VLINEDIST: |
| 2757 |
ss << "vlinedist("; break;; |
| 2758 |
case VLINESEGDIST: |
| 2759 |
ss << "vlinesegdist("; break;; |
| 2760 |
case VLINEPROJ: |
| 2761 |
ss << "vlineproj("; break;; |
| 2762 |
case VNORMALIZE: |
| 2763 |
ss << "vnormalize("; break;; |
| 2764 |
case VPLANEDIST: |
| 2765 |
ss << "vplanedist("; break;; |
| 2766 |
case VPLANEPROJ: |
| 2767 |
ss << "vplaneproj("; break;; |
| 2768 |
case VSCALE: |
| 2769 |
ss << "vscale("; break;; |
| 2770 |
case VSCALEX: |
| 2771 |
ss << "vscalex("; break;; |
| 2772 |
case VSCALEY: |
| 2773 |
ss << "vscaley("; break;; |
| 2774 |
case VSCALEZ: |
| 2775 |
ss << "vscalez("; break;; |
| 2776 |
case MINVERT: |
| 2777 |
ss << "minvert("; break;; |
| 2778 |
case MROTATE: |
| 2779 |
ss << "mrotate("; break;; |
| 2780 |
case MROTATEX: |
| 2781 |
ss << "mrotatex("; break;; |
| 2782 |
case MROTATEY: |
| 2783 |
ss << "mrotatey("; break;; |
| 2784 |
case MROTATEZ: |
| 2785 |
ss << "mrotatez("; break;; |
| 2786 |
case MSCALE: |
| 2787 |
ss << "mscale("; break;; |
| 2788 |
case MTRANSLATE: |
| 2789 |
ss << "mtranslate("; break;; |
| 2790 |
case CREATE: |
| 2791 |
ss << "create("; break;; |
| 2792 |
case LIST: |
| 2793 |
ss << "list("; break;; |
| 2794 |
case MATRIX: |
| 2795 |
ss << "matrix("; break;; |
| 2796 |
case PLACEMENT: |
| 2797 |
ss << "placement("; break;; |
| 2798 |
case ROTATION: |
| 2799 |
ss << "rotation("; break;; |
| 2800 |
case ROTATIONX: |
| 2801 |
ss << "rotationx("; break;; |
| 2802 |
case ROTATIONY: |
| 2803 |
ss << "rotationy("; break;; |
| 2804 |
case ROTATIONZ: |
| 2805 |
ss << "rotationz("; break;; |
| 2806 |
case STR: |
| 2807 |
ss << "str("; break;; |
| 2808 |
case PARSEQUANT: |
| 2809 |
ss << "parsequant("; break;; |
| 2810 |
case TRANSLATIONM: |
| 2811 |
ss << "translationm("; break;; |
| 2812 |
case TUPLE: |
| 2813 |
ss << "tuple("; break;; |
| 2814 |
case VECTOR: |
| 2815 |
ss << "vector("; break;; |
| 2816 |
case HIDDENREF: |
| 2817 |
ss << "hiddenref("; break;; |
| 2818 |
case HREF: |
| 2819 |
ss << "href("; break;; |
| 2820 |
case AVERAGE: |
| 2821 |
ss << "average("; break;; |
| 2822 |
case COUNT: |
| 2823 |
ss << "count("; break;; |
| 2824 |
case MAX: |
| 2825 |
ss << "max("; break;; |
| 2826 |
case MIN: |
| 2827 |
ss << "min("; break;; |
| 2828 |
case STDDEV: |
| 2829 |
ss << "stddev("; break;; |
| 2830 |
case SUM: |
| 2831 |
ss << "sum("; break;; |
| 2832 |
case AND: |
| 2833 |
ss << "and("; break;; |
| 2834 |
case OR: |
| 2835 |
ss << "or("; break;; |
| 2836 |
case NOT: |
| 2837 |
ss << "not("; break;; |
| 2838 |
default: |
| 2839 |
ss << fname << "("; break;; |
| 2840 |
} |
| 2841 |
for (size_t i = 0; i < args.size(); ++i) { |
| 2842 |
ss << args[i]->toString(persistent); |
| 2843 |
if (i != args.size() - 1) |
| 2844 |
ss << "; "; |
| 2845 |
} |
| 2846 |
ss << ')'; |
| 2847 |
} |
| 2848 |
|
| 2849 |
/** |
| 2850 |
* Create a copy of the expression. |
| 2851 |
* |
| 2852 |
* @returns A deep copy of the expression. |
| 2853 |
*/ |
| 2854 |
|
| 2855 |
Expression *FunctionExpression::_copy() const |
| 2856 |
{ |
| 2857 |
std::vector<Expression*>::const_iterator i = args.begin(); |
| 2858 |
std::vector<Expression*> a; |
| 2859 |
|
| 2860 |
while (i != args.end()) { |
| 2861 |
a.push_back((*i)->copy()); |
| 2862 |
++i; |
| 2863 |
} |
| 2864 |
return new FunctionExpression(owner, f, std::string(fname), std::move(a)); |
| 2865 |
} |
| 2866 |
|
| 2867 |
void FunctionExpression::_visit(ExpressionVisitor &v) |
| 2868 |
{ |
| 2869 |
std::vector<Expression*>::const_iterator i = args.begin(); |
| 2870 |
|
| 2871 |
HiddenReference ref(f == HIDDENREF || f == HREF); |
| 2872 |
while (i != args.end()) { |
| 2873 |
(*i)->visit(v); |
| 2874 |
++i; |
| 2875 |
} |
| 2876 |
} |
| 2877 |
|
| 2878 |
// |
| 2879 |
// VariableExpression class |
| 2880 |
// |
| 2881 |
|
| 2882 |
TYPESYSTEM_SOURCE(App::VariableExpression, App::UnitExpression) |
| 2883 |
|
| 2884 |
VariableExpression::VariableExpression(const DocumentObject *_owner, const ObjectIdentifier& _var) |
| 2885 |
: UnitExpression(_owner) |
| 2886 |
, var(_var) |
| 2887 |
{ |
| 2888 |
} |
| 2889 |
|
| 2890 |
VariableExpression::~VariableExpression() = default; |
| 2891 |
|
| 2892 |
/** |
| 2893 |
* Determine if the expression is touched or not, i.e whether the Property object it |
| 2894 |
* refers to is touched(). |
| 2895 |
* |
| 2896 |
* @returns True if the Property object is touched, false if not. |
| 2897 |
*/ |
| 2898 |
|
| 2899 |
bool VariableExpression::isTouched() const |
| 2900 |
{ |
| 2901 |
return var.isTouched(); |
| 2902 |
} |
| 2903 |
|
| 2904 |
/** |
| 2905 |
* Find the property this expression referse to. |
| 2906 |
* |
| 2907 |
* Unqualified names (i.e the name only without any dots) are resolved in the owning DocumentObjects. |
| 2908 |
* Qualified names are looked up in the owning Document. It is first looked up by its internal name. |
| 2909 |
* If not found, the DocumentObjects' labels searched. |
| 2910 |
* |
| 2911 |
* If something fails, an exception is thrown. |
| 2912 |
* |
| 2913 |
* @returns The Property object if it is derived from either PropertyInteger, PropertyFloat, or PropertyString. |
| 2914 |
*/ |
| 2915 |
|
| 2916 |
const Property * VariableExpression::getProperty() const |
| 2917 |
{ |
| 2918 |
const Property * prop = var.getProperty(); |
| 2919 |
|
| 2920 |
if (prop) |
| 2921 |
return prop; |
| 2922 |
else |
| 2923 |
throw Expression::Exception(var.resolveErrorString().c_str()); |
| 2924 |
} |
| 2925 |
|
| 2926 |
void VariableExpression::addComponent(Component *c) { |
| 2927 |
do { |
| 2928 |
if(!components.empty()) |
| 2929 |
break; |
| 2930 |
if(!c->e1 && !c->e2) { |
| 2931 |
var << c->comp; |
| 2932 |
return; |
| 2933 |
} |
| 2934 |
long l1=0,l2=0,l3=1; |
| 2935 |
if(c->e3) { |
| 2936 |
auto n3 = freecad_cast<NumberExpression*>(c->e3); |
| 2937 |
if(!n3 || !essentiallyEqual(n3->getValue(),(double)l3)) |
| 2938 |
break; |
| 2939 |
} |
| 2940 |
if(c->e1) { |
| 2941 |
auto n1 = freecad_cast<NumberExpression*>(c->e1); |
| 2942 |
if(!n1) { |
| 2943 |
if(c->e2 || c->e3) |
| 2944 |
break; |
| 2945 |
auto s = freecad_cast<StringExpression*>(c->e1); |
| 2946 |
if(!s) |
| 2947 |
break; |
| 2948 |
var << ObjectIdentifier::MapComponent( |
| 2949 |
ObjectIdentifier::String(s->getText(),true)); |
| 2950 |
return; |
| 2951 |
} |
| 2952 |
if(!essentiallyInteger(n1->getValue(),l1)) |
| 2953 |
break; |
| 2954 |
if(!c->comp.isRange()) { |
| 2955 |
var << ObjectIdentifier::ArrayComponent(l1); |
| 2956 |
return; |
| 2957 |
} else if(!c->e2) { |
| 2958 |
var << ObjectIdentifier::RangeComponent(l1,l2,l3); |
| 2959 |
return; |
| 2960 |
} |
| 2961 |
} |
| 2962 |
auto n2 = freecad_cast<NumberExpression*>(c->e2); |
| 2963 |
if(n2 && essentiallyInteger(n2->getValue(),l2)) { |
| 2964 |
var << ObjectIdentifier::RangeComponent(l1,l2,l3); |
| 2965 |
return; |
| 2966 |
} |
| 2967 |
}while(false); |
| 2968 |
|
| 2969 |
Expression::addComponent(c); |
| 2970 |
} |
| 2971 |
|
| 2972 |
bool VariableExpression::_isIndexable() const { |
| 2973 |
return true; |
| 2974 |
} |
| 2975 |
|
| 2976 |
Py::Object VariableExpression::_getPyValue() const { |
| 2977 |
return var.getPyValue(true); |
| 2978 |
} |
| 2979 |
|
| 2980 |
void VariableExpression::_toString(std::ostream &ss, bool persistent,int) const { |
| 2981 |
if(persistent) |
| 2982 |
ss << var.toPersistentString(); |
| 2983 |
else |
| 2984 |
ss << var.toString(); |
| 2985 |
} |
| 2986 |
|
| 2987 |
/** |
| 2988 |
* Simplify the expression. Simplification of VariableExpression objects is |
| 2989 |
* not possible (if it is instantiated it would be an evaluation instead). |
| 2990 |
* |
| 2991 |
* @returns A copy of the expression. |
| 2992 |
*/ |
| 2993 |
|
| 2994 |
Expression *VariableExpression::simplify() const |
| 2995 |
{ |
| 2996 |
return copy(); |
| 2997 |
} |
| 2998 |
|
| 2999 |
/** |
| 3000 |
* Return a copy of the expression. |
| 3001 |
*/ |
| 3002 |
|
| 3003 |
Expression *VariableExpression::_copy() const |
| 3004 |
{ |
| 3005 |
return new VariableExpression(owner, var); |
| 3006 |
} |
| 3007 |
|
| 3008 |
void VariableExpression::_getIdentifiers(std::map<App::ObjectIdentifier,bool> &deps) const |
| 3009 |
{ |
| 3010 |
bool hidden = HiddenReference::isHidden(); |
| 3011 |
auto res = deps.insert(std::make_pair(var,hidden)); |
| 3012 |
if(!hidden || res.second) |
| 3013 |
res.first->second = hidden; |
| 3014 |
} |
| 3015 |
|
| 3016 |
bool VariableExpression::_relabeledDocument(const std::string &oldName, |
| 3017 |
const std::string &newName, ExpressionVisitor &v) |
| 3018 |
{ |
| 3019 |
return var.relabeledDocument(v, oldName, newName); |
| 3020 |
} |
| 3021 |
|
| 3022 |
bool VariableExpression::_adjustLinks( |
| 3023 |
const std::set<App::DocumentObject *> &inList, ExpressionVisitor &v) |
| 3024 |
{ |
| 3025 |
return var.adjustLinks(v,inList); |
| 3026 |
} |
| 3027 |
|
| 3028 |
void VariableExpression::_importSubNames(const ObjectIdentifier::SubNameMap &subNameMap) |
| 3029 |
{ |
| 3030 |
var.importSubNames(subNameMap); |
| 3031 |
} |
| 3032 |
|
| 3033 |
void VariableExpression::_updateLabelReference( |
| 3034 |
App::DocumentObject *obj, const std::string &ref, const char *newLabel) |
| 3035 |
{ |
| 3036 |
var.updateLabelReference(obj,ref,newLabel); |
| 3037 |
} |
| 3038 |
|
| 3039 |
bool VariableExpression::_updateElementReference( |
| 3040 |
App::DocumentObject *feature, bool reverse, ExpressionVisitor &v) |
| 3041 |
{ |
| 3042 |
return var.updateElementReference(v,feature,reverse); |
| 3043 |
} |
| 3044 |
|
| 3045 |
bool VariableExpression::_renameObjectIdentifier( |
| 3046 |
const std::map<ObjectIdentifier, ObjectIdentifier>& paths, |
| 3047 |
const ObjectIdentifier& path, |
| 3048 |
ExpressionVisitor& visitor) |
| 3049 |
{ |
| 3050 |
const auto& oldPath = var.canonicalPath(); |
| 3051 |
auto it = paths.find(oldPath); |
| 3052 |
if (it != paths.end()) { |
| 3053 |
visitor.aboutToChange(); |
| 3054 |
const bool originalHasDocumentObjectName = var.hasDocumentObjectName(); |
| 3055 |
ObjectIdentifier::String originalDocumentObjectName = var.getDocumentObjectName(); |
| 3056 |
std::string originalSubObjectName = var.getSubObjectName(); |
| 3057 |
if (path.getOwner()) { |
| 3058 |
var = it->second.relativeTo(path); |
| 3059 |
} |
| 3060 |
else { |
| 3061 |
var = it->second; |
| 3062 |
} |
| 3063 |
if (originalHasDocumentObjectName) { |
| 3064 |
var.setDocumentObjectName(std::move(originalDocumentObjectName), |
| 3065 |
true, |
| 3066 |
originalSubObjectName); |
| 3067 |
} |
| 3068 |
return true; |
| 3069 |
} |
| 3070 |
return false; |
| 3071 |
} |
| 3072 |
|
| 3073 |
void VariableExpression::_collectReplacement( |
| 3074 |
std::map<ObjectIdentifier,ObjectIdentifier> &paths, |
| 3075 |
const App::DocumentObject *parent, |
| 3076 |
App::DocumentObject *oldObj, |
| 3077 |
App::DocumentObject *newObj) const |
| 3078 |
{ |
| 3079 |
ObjectIdentifier path; |
| 3080 |
if(var.replaceObject(path,parent,oldObj,newObj)) |
| 3081 |
paths[var.canonicalPath()] = std::move(path); |
| 3082 |
} |
| 3083 |
|
| 3084 |
void VariableExpression::_moveCells(const CellAddress &address, |
| 3085 |
int rowCount, int colCount, ExpressionVisitor &v) |
| 3086 |
{ |
| 3087 |
if(var.hasDocumentObjectName(true)) |
| 3088 |
return; |
| 3089 |
|
| 3090 |
int idx = 0; |
| 3091 |
const auto &comp = var.getPropertyComponent(0,&idx); |
| 3092 |
CellAddress addr = stringToAddress(comp.getName().c_str(),true); |
| 3093 |
if(!addr.isValid()) |
| 3094 |
return; |
| 3095 |
|
| 3096 |
int thisRow = addr.row(); |
| 3097 |
int thisCol = addr.col(); |
| 3098 |
if (thisRow >= address.row() || thisCol >= address.col()) { |
| 3099 |
v.aboutToChange(); |
| 3100 |
addr.setRow(thisRow + rowCount); |
| 3101 |
addr.setCol(thisCol + colCount); |
| 3102 |
var.setComponent(idx,ObjectIdentifier::SimpleComponent(addr.toString())); |
| 3103 |
} |
| 3104 |
} |
| 3105 |
|
| 3106 |
void VariableExpression::_offsetCells(int rowOffset, int colOffset, ExpressionVisitor &v) { |
| 3107 |
if(var.hasDocumentObjectName(true)) |
| 3108 |
return; |
| 3109 |
|
| 3110 |
int idx = 0; |
| 3111 |
const auto &comp = var.getPropertyComponent(0,&idx); |
| 3112 |
CellAddress addr = stringToAddress(comp.getName().c_str(),true); |
| 3113 |
if(!addr.isValid() || (addr.isAbsoluteCol() && addr.isAbsoluteRow())) |
| 3114 |
return; |
| 3115 |
|
| 3116 |
if(!addr.isAbsoluteCol()) |
| 3117 |
addr.setCol(addr.col()+colOffset); |
| 3118 |
if(!addr.isAbsoluteRow()) |
| 3119 |
addr.setRow(addr.row()+rowOffset); |
| 3120 |
if(!addr.isValid()) { |
| 3121 |
FC_WARN("Not changing relative cell reference '" |
| 3122 |
<< comp.getName() << "' due to invalid offset " |
| 3123 |
<< '(' << colOffset << ", " << rowOffset << ')'); |
| 3124 |
} else { |
| 3125 |
v.aboutToChange(); |
| 3126 |
var.setComponent(idx,ObjectIdentifier::SimpleComponent(addr.toString())); |
| 3127 |
} |
| 3128 |
} |
| 3129 |
|
| 3130 |
void VariableExpression::setPath(const ObjectIdentifier &path) |
| 3131 |
{ |
| 3132 |
var = path; |
| 3133 |
} |
| 3134 |
|
| 3135 |
// |
| 3136 |
// PyObjectExpression class |
| 3137 |
// |
| 3138 |
|
| 3139 |
TYPESYSTEM_SOURCE(App::PyObjectExpression, App::Expression) |
| 3140 |
|
| 3141 |
PyObjectExpression::~PyObjectExpression() { |
| 3142 |
if(pyObj) { |
| 3143 |
Base::PyGILStateLocker lock; |
| 3144 |
Py::_XDECREF(pyObj); |
| 3145 |
} |
| 3146 |
} |
| 3147 |
|
| 3148 |
Py::Object PyObjectExpression::_getPyValue() const { |
| 3149 |
if(!pyObj) |
| 3150 |
return Py::Object(); |
| 3151 |
return Py::Object(pyObj); |
| 3152 |
} |
| 3153 |
|
| 3154 |
void PyObjectExpression::setPyValue(Py::Object obj) { |
| 3155 |
Py::_XDECREF(pyObj); |
| 3156 |
pyObj = obj.ptr(); |
| 3157 |
Py::_XINCREF(pyObj); |
| 3158 |
} |
| 3159 |
|
| 3160 |
void PyObjectExpression::setPyValue(PyObject *obj, bool owned) { |
| 3161 |
if(pyObj == obj) |
| 3162 |
return; |
| 3163 |
Py::_XDECREF(pyObj); |
| 3164 |
pyObj = obj; |
| 3165 |
if(!owned) |
| 3166 |
Py::_XINCREF(pyObj); |
| 3167 |
} |
| 3168 |
|
| 3169 |
void PyObjectExpression::_toString(std::ostream &ss, bool,int) const |
| 3170 |
{ |
| 3171 |
if(!pyObj) |
| 3172 |
ss << "None"; |
| 3173 |
else { |
| 3174 |
Base::PyGILStateLocker lock; |
| 3175 |
ss << Py::Object(pyObj).as_string(); |
| 3176 |
} |
| 3177 |
} |
| 3178 |
|
| 3179 |
Expression* PyObjectExpression::_copy() const |
| 3180 |
{ |
| 3181 |
return new PyObjectExpression(owner,pyObj,false); |
| 3182 |
} |
| 3183 |
|
| 3184 |
// |
| 3185 |
// StringExpression class |
| 3186 |
// |
| 3187 |
|
| 3188 |
TYPESYSTEM_SOURCE(App::StringExpression, App::Expression) |
| 3189 |
|
| 3190 |
StringExpression::StringExpression(const DocumentObject *_owner, const std::string &_text) |
| 3191 |
: Expression(_owner) |
| 3192 |
, text(_text) |
| 3193 |
{ |
| 3194 |
} |
| 3195 |
|
| 3196 |
StringExpression::~StringExpression() { |
| 3197 |
if(cache) { |
| 3198 |
Base::PyGILStateLocker lock; |
| 3199 |
Py::_XDECREF(cache); |
| 3200 |
} |
| 3201 |
} |
| 3202 |
|
| 3203 |
/** |
| 3204 |
* Simplify the expression. For strings, this is a simple copy of the object. |
| 3205 |
*/ |
| 3206 |
|
| 3207 |
Expression *StringExpression::simplify() const |
| 3208 |
{ |
| 3209 |
return copy(); |
| 3210 |
} |
| 3211 |
|
| 3212 |
void StringExpression::_toString(std::ostream &ss, bool,int) const |
| 3213 |
{ |
| 3214 |
ss << quote(text); |
| 3215 |
} |
| 3216 |
|
| 3217 |
/** |
| 3218 |
* Return a copy of the expression. |
| 3219 |
*/ |
| 3220 |
|
| 3221 |
Expression *StringExpression::_copy() const |
| 3222 |
{ |
| 3223 |
return new StringExpression(owner, text); |
| 3224 |
} |
| 3225 |
|
| 3226 |
Py::Object StringExpression::_getPyValue() const { |
| 3227 |
return Py::String(text); |
| 3228 |
} |
| 3229 |
|
| 3230 |
TYPESYSTEM_SOURCE(App::ConditionalExpression, App::Expression) |
| 3231 |
|
| 3232 |
ConditionalExpression::ConditionalExpression(const DocumentObject *_owner, Expression *_condition, Expression *_trueExpr, Expression *_falseExpr) |
| 3233 |
: Expression(_owner) |
| 3234 |
, condition(_condition) |
| 3235 |
, trueExpr(_trueExpr) |
| 3236 |
, falseExpr(_falseExpr) |
| 3237 |
{ |
| 3238 |
} |
| 3239 |
|
| 3240 |
ConditionalExpression::~ConditionalExpression() |
| 3241 |
{ |
| 3242 |
delete condition; |
| 3243 |
delete trueExpr; |
| 3244 |
delete falseExpr; |
| 3245 |
} |
| 3246 |
|
| 3247 |
bool ConditionalExpression::isTouched() const |
| 3248 |
{ |
| 3249 |
return condition->isTouched() || trueExpr->isTouched() || falseExpr->isTouched(); |
| 3250 |
} |
| 3251 |
|
| 3252 |
Py::Object ConditionalExpression::_getPyValue() const { |
| 3253 |
if(condition->getPyValue().isTrue()) |
| 3254 |
return trueExpr->getPyValue(); |
| 3255 |
else |
| 3256 |
return falseExpr->getPyValue(); |
| 3257 |
} |
| 3258 |
|
| 3259 |
Expression *ConditionalExpression::simplify() const |
| 3260 |
{ |
| 3261 |
std::unique_ptr<Expression> e(condition->simplify()); |
| 3262 |
NumberExpression * v = freecad_cast<NumberExpression*>(e.get()); |
| 3263 |
|
| 3264 |
if (!v) |
| 3265 |
return new ConditionalExpression(owner, condition->simplify(), trueExpr->simplify(), falseExpr->simplify()); |
| 3266 |
else { |
| 3267 |
if (fabs(v->getValue()) >= Base::Precision::Confusion()) |
| 3268 |
return trueExpr->simplify(); |
| 3269 |
else |
| 3270 |
return falseExpr->simplify(); |
| 3271 |
} |
| 3272 |
} |
| 3273 |
|
| 3274 |
void ConditionalExpression::_toString(std::ostream &ss, bool persistent,int) const |
| 3275 |
{ |
| 3276 |
condition->toString(ss,persistent); |
| 3277 |
ss << " ? "; |
| 3278 |
if (trueExpr->priority() <= priority()) { |
| 3279 |
ss << '('; |
| 3280 |
trueExpr->toString(ss,persistent); |
| 3281 |
ss << ')'; |
| 3282 |
} else |
| 3283 |
trueExpr->toString(ss,persistent); |
| 3284 |
|
| 3285 |
ss << " : "; |
| 3286 |
|
| 3287 |
if (falseExpr->priority() <= priority()) { |
| 3288 |
ss << '('; |
| 3289 |
falseExpr->toString(ss,persistent); |
| 3290 |
ss << ')'; |
| 3291 |
} else |
| 3292 |
falseExpr->toString(ss,persistent); |
| 3293 |
} |
| 3294 |
|
| 3295 |
Expression *ConditionalExpression::_copy() const |
| 3296 |
{ |
| 3297 |
return new ConditionalExpression(owner, condition->copy(), trueExpr->copy(), falseExpr->copy()); |
| 3298 |
} |
| 3299 |
|
| 3300 |
int ConditionalExpression::priority() const |
| 3301 |
{ |
| 3302 |
return 2; |
| 3303 |
} |
| 3304 |
|
| 3305 |
void ConditionalExpression::_visit(ExpressionVisitor &v) |
| 3306 |
{ |
| 3307 |
condition->visit(v); |
| 3308 |
trueExpr->visit(v); |
| 3309 |
falseExpr->visit(v); |
| 3310 |
} |
| 3311 |
|
| 3312 |
TYPESYSTEM_SOURCE(App::ConstantExpression, App::NumberExpression) |
| 3313 |
|
| 3314 |
ConstantExpression::ConstantExpression(const DocumentObject *_owner, |
| 3315 |
const char *_name, const Quantity & _quantity) |
| 3316 |
: NumberExpression(_owner, _quantity) |
| 3317 |
, name(_name) |
| 3318 |
{ |
| 3319 |
} |
| 3320 |
|
| 3321 |
Expression *ConstantExpression::_copy() const |
| 3322 |
{ |
| 3323 |
return new ConstantExpression(owner, name, getQuantity()); |
| 3324 |
} |
| 3325 |
|
| 3326 |
void ConstantExpression::_toString(std::ostream &ss, bool,int) const |
| 3327 |
{ |
| 3328 |
ss << name; |
| 3329 |
} |
| 3330 |
|
| 3331 |
Py::Object ConstantExpression::_getPyValue() const { |
| 3332 |
if(!cache) { |
| 3333 |
if(strcmp(name,"None")==0) |
| 3334 |
cache = Py::new_reference_to(Py::None()); |
| 3335 |
else if(strcmp(name,"True")==0) |
| 3336 |
cache = Py::new_reference_to(Py::True()); |
| 3337 |
else if(strcmp(name, "False")==0) |
| 3338 |
cache = Py::new_reference_to(Py::False()); |
| 3339 |
else |
| 3340 |
return NumberExpression::_getPyValue(); |
| 3341 |
} |
| 3342 |
return Py::Object(cache); |
| 3343 |
} |
| 3344 |
|
| 3345 |
bool ConstantExpression::isNumber() const { |
| 3346 |
return strcmp(name,"None") |
| 3347 |
&& strcmp(name,"True") |
| 3348 |
&& strcmp(name, "False"); |
| 3349 |
} |
| 3350 |
|
| 3351 |
TYPESYSTEM_SOURCE(App::RangeExpression, App::Expression) |
| 3352 |
|
| 3353 |
RangeExpression::RangeExpression(const DocumentObject *_owner, const std::string &begin, const std::string &end) |
| 3354 |
: Expression(_owner), begin(begin), end(end) |
| 3355 |
{ |
| 3356 |
} |
| 3357 |
|
| 3358 |
bool RangeExpression::isTouched() const |
| 3359 |
{ |
| 3360 |
Range i(getRange()); |
| 3361 |
|
| 3362 |
do { |
| 3363 |
Property * prop = owner->getPropertyByName(i.address().c_str()); |
| 3364 |
|
| 3365 |
if (prop && prop->isTouched()) |
| 3366 |
return true; |
| 3367 |
} while (i.next()); |
| 3368 |
|
| 3369 |
return false; |
| 3370 |
} |
| 3371 |
|
| 3372 |
Py::Object RangeExpression::_getPyValue() const { |
| 3373 |
Py::List list; |
| 3374 |
Range range(getRange()); |
| 3375 |
do { |
| 3376 |
Property * p = owner->getPropertyByName(range.address().c_str()); |
| 3377 |
if(p) |
| 3378 |
list.append(Py::asObject(p->getPyObject())); |
| 3379 |
} while (range.next()); |
| 3380 |
return list; |
| 3381 |
} |
| 3382 |
|
| 3383 |
void RangeExpression::_toString(std::ostream &ss, bool,int) const |
| 3384 |
{ |
| 3385 |
ss << begin << ":" << end; |
| 3386 |
} |
| 3387 |
|
| 3388 |
Expression *RangeExpression::_copy() const |
| 3389 |
{ |
| 3390 |
return new RangeExpression(owner, begin, end); |
| 3391 |
} |
| 3392 |
|
| 3393 |
Expression *RangeExpression::simplify() const |
| 3394 |
{ |
| 3395 |
return copy(); |
| 3396 |
} |
| 3397 |
|
| 3398 |
void RangeExpression::_getIdentifiers(std::map<App::ObjectIdentifier,bool> &deps) const |
| 3399 |
{ |
| 3400 |
bool hidden = HiddenReference::isHidden(); |
| 3401 |
|
| 3402 |
assert(owner); |
| 3403 |
|
| 3404 |
Range i(getRange()); |
| 3405 |
|
| 3406 |
do { |
| 3407 |
ObjectIdentifier var(owner,i.address()); |
| 3408 |
auto res = deps.insert(std::make_pair(var,hidden)); |
| 3409 |
if(!hidden || res.second) |
| 3410 |
res.first->second = hidden; |
| 3411 |
} while (i.next()); |
| 3412 |
} |
| 3413 |
|
| 3414 |
Range RangeExpression::getRange() const |
| 3415 |
{ |
| 3416 |
auto c1 = stringToAddress(begin.c_str(),true); |
| 3417 |
auto c2 = stringToAddress(end.c_str(),true); |
| 3418 |
if(c1.isValid() && c2.isValid()) |
| 3419 |
return Range(c1,c2); |
| 3420 |
|
| 3421 |
Base::PyGILStateLocker lock; |
| 3422 |
static const std::string attr("getCellFromAlias"); |
| 3423 |
Py::Object pyobj(owner->getPyObject(),true); |
| 3424 |
if(!pyobj.hasAttr(attr)) |
| 3425 |
EXPR_THROW("Invalid cell range " << begin << ':' << end); |
| 3426 |
Py::Callable callable(pyobj.getAttr(attr)); |
| 3427 |
if(!c1.isValid()) { |
| 3428 |
try { |
| 3429 |
Py::Tuple arg(1); |
| 3430 |
arg.setItem(0,Py::String(begin)); |
| 3431 |
c1 = CellAddress(callable.apply(arg).as_string().c_str()); |
| 3432 |
} catch(Py::Exception &) { |
| 3433 |
_EXPR_PY_THROW("Invalid cell address '" << begin << "': ",this); |
| 3434 |
} catch(Base::Exception &e) { |
| 3435 |
_EXPR_RETHROW(e,"Invalid cell address '" << begin << "': ",this); |
| 3436 |
} |
| 3437 |
} |
| 3438 |
if(!c2.isValid()) { |
| 3439 |
try { |
| 3440 |
Py::Tuple arg(1); |
| 3441 |
arg.setItem(0,Py::String(end)); |
| 3442 |
c2 = CellAddress(callable.apply(arg).as_string().c_str()); |
| 3443 |
} catch(Py::Exception &) { |
| 3444 |
_EXPR_PY_THROW("Invalid cell address '" << end << "': ", this); |
| 3445 |
} catch(Base::Exception &e) { |
| 3446 |
_EXPR_RETHROW(e,"Invalid cell address '" << end << "': ", this); |
| 3447 |
} |
| 3448 |
} |
| 3449 |
return Range(c1,c2); |
| 3450 |
} |
| 3451 |
|
| 3452 |
bool RangeExpression::_renameObjectIdentifier( |
| 3453 |
const std::map<ObjectIdentifier,ObjectIdentifier> &paths, |
| 3454 |
const ObjectIdentifier &path, ExpressionVisitor &v) |
| 3455 |
{ |
| 3456 |
(void)path; |
| 3457 |
bool touched =false; |
| 3458 |
auto it = paths.find(ObjectIdentifier(owner,begin)); |
| 3459 |
if (it != paths.end()) { |
| 3460 |
v.aboutToChange(); |
| 3461 |
begin = it->second.getPropertyName(); |
| 3462 |
touched = true; |
| 3463 |
} |
| 3464 |
it = paths.find(ObjectIdentifier(owner,end)); |
| 3465 |
if (it != paths.end()) { |
| 3466 |
v.aboutToChange(); |
| 3467 |
end = it->second.getPropertyName(); |
| 3468 |
touched = true; |
| 3469 |
} |
| 3470 |
return touched; |
| 3471 |
} |
| 3472 |
|
| 3473 |
void RangeExpression::_moveCells(const CellAddress &address, |
| 3474 |
int rowCount, int colCount, ExpressionVisitor &v) |
| 3475 |
{ |
| 3476 |
CellAddress addr = stringToAddress(begin.c_str(),true); |
| 3477 |
if(addr.isValid()) { |
| 3478 |
int thisRow = addr.row(); |
| 3479 |
int thisCol = addr.col(); |
| 3480 |
if (thisRow >= address.row() || thisCol >= address.col()) { |
| 3481 |
v.aboutToChange(); |
| 3482 |
addr.setRow(thisRow+rowCount); |
| 3483 |
addr.setCol(thisCol+colCount); |
| 3484 |
begin = addr.toString(); |
| 3485 |
} |
| 3486 |
} |
| 3487 |
addr = stringToAddress(end.c_str(),true); |
| 3488 |
if(addr.isValid()) { |
| 3489 |
int thisRow = addr.row(); |
| 3490 |
int thisCol = addr.col(); |
| 3491 |
if (thisRow >= address.row() || thisCol >= address.col()) { |
| 3492 |
v.aboutToChange(); |
| 3493 |
addr.setRow(thisRow + rowCount); |
| 3494 |
addr.setCol(thisCol + colCount); |
| 3495 |
end = addr.toString(); |
| 3496 |
} |
| 3497 |
} |
| 3498 |
} |
| 3499 |
|
| 3500 |
void RangeExpression::_offsetCells(int rowOffset, int colOffset, ExpressionVisitor &v) |
| 3501 |
{ |
| 3502 |
CellAddress addr = stringToAddress(begin.c_str(),true); |
| 3503 |
if(addr.isValid() && (!addr.isAbsoluteRow() || !addr.isAbsoluteCol())) { |
| 3504 |
v.aboutToChange(); |
| 3505 |
if(!addr.isAbsoluteRow()) |
| 3506 |
addr.setRow(addr.row()+rowOffset); |
| 3507 |
if(!addr.isAbsoluteCol()) |
| 3508 |
addr.setCol(addr.col()+colOffset); |
| 3509 |
begin = addr.toString(); |
| 3510 |
} |
| 3511 |
addr = stringToAddress(end.c_str(),true); |
| 3512 |
if(addr.isValid() && (!addr.isAbsoluteRow() || !addr.isAbsoluteCol())) { |
| 3513 |
v.aboutToChange(); |
| 3514 |
if(!addr.isAbsoluteRow()) |
| 3515 |
addr.setRow(addr.row()+rowOffset); |
| 3516 |
if(!addr.isAbsoluteCol()) |
| 3517 |
addr.setCol(addr.col()+colOffset); |
| 3518 |
end = addr.toString(); |
| 3519 |
} |
| 3520 |
} |
| 3521 |
|
| 3522 |
|
| 3523 |
//////////////////////////////////////////////////////////////////////////////////// |
| 3524 |
|
| 3525 |
static Base::XMLReader *_Reader = nullptr; |
| 3526 |
ExpressionParser::ExpressionImporter::ExpressionImporter(Base::XMLReader &reader) { |
| 3527 |
assert(!_Reader); |
| 3528 |
_Reader = &reader; |
| 3529 |
} |
| 3530 |
|
| 3531 |
ExpressionParser::ExpressionImporter::~ExpressionImporter() { |
| 3532 |
assert(_Reader); |
| 3533 |
_Reader = nullptr; |
| 3534 |
} |
| 3535 |
|
| 3536 |
Base::XMLReader *ExpressionParser::ExpressionImporter::reader() { |
| 3537 |
return _Reader; |
| 3538 |
} |
| 3539 |
|
| 3540 |
namespace App { |
| 3541 |
|
| 3542 |
namespace ExpressionParser { |
| 3543 |
|
| 3544 |
bool isModuleImported(PyObject *module) { |
| 3545 |
(void)module; |
| 3546 |
return false; |
| 3547 |
} |
| 3548 |
|
| 3549 |
/** |
| 3550 |
* Error function for parser. Throws a generic Base::Exception with the parser error. |
| 3551 |
*/ |
| 3552 |
|
| 3553 |
void ExpressionParser_yyerror(const char *errorinfo) |
| 3554 |
{ |
| 3555 |
(void)errorinfo; |
| 3556 |
} |
| 3557 |
|
| 3558 |
/* helper function for tuning number strings with groups in a locale agnostic way... */ |
| 3559 |
double num_change(char* yytext,char dez_delim,char grp_delim) |
| 3560 |
{ |
| 3561 |
double ret_val; |
| 3562 |
char temp[40]; |
| 3563 |
int i = 0; |
| 3564 |
for(char* c=yytext;*c!='\0';c++){ |
| 3565 |
// skip group delimiter |
| 3566 |
if(*c==grp_delim) continue; |
| 3567 |
// check for a dez delimiter other then dot |
| 3568 |
if(*c==dez_delim && dez_delim !='.') |
| 3569 |
temp[i++] = '.'; |
| 3570 |
else |
| 3571 |
temp[i++] = *c; |
| 3572 |
// check buffer overflow |
| 3573 |
if (i>39) |
| 3574 |
return 0.0; |
| 3575 |
} |
| 3576 |
temp[i] = '\0'; |
| 3577 |
|
| 3578 |
errno = 0; |
| 3579 |
ret_val = strtod( temp, nullptr ); |
| 3580 |
if (ret_val == 0 && errno == ERANGE) |
| 3581 |
throw Base::UnderflowError("Number underflow."); |
| 3582 |
if (ret_val == HUGE_VAL || ret_val == -HUGE_VAL) |
| 3583 |
throw Base::OverflowError("Number overflow."); |
| 3584 |
|
| 3585 |
return ret_val; |
| 3586 |
} |
| 3587 |
|
| 3588 |
static Expression * ScanResult = nullptr; /**< The resulting expression after a successful parsing */ |
| 3589 |
static const App::DocumentObject * DocumentObject = nullptr; /**< The DocumentObject that will own the expression */ |
| 3590 |
static bool unitExpression = false; /**< True if the parsed string is a unit only */ |
| 3591 |
static bool valueExpression = false; /**< True if the parsed string is a full expression */ |
| 3592 |
static std::stack<std::string> labels; /**< Label string primitive */ |
| 3593 |
static std::map<std::string, FunctionExpression::Function> registered_functions; /**< Registered functions */ |
| 3594 |
static int last_column; |
| 3595 |
static int column; |
| 3596 |
|
| 3597 |
// show the parser the lexer method |
| 3598 |
#define yylex ExpressionParserlex |
| 3599 |
int ExpressionParserlex(); |
| 3600 |
|
| 3601 |
#if defined(__clang__) |
| 3602 |
# pragma clang diagnostic push |
| 3603 |
# pragma clang diagnostic ignored "-Wsign-compare" |
| 3604 |
# pragma clang diagnostic ignored "-Wunneeded-internal-declaration" |
| 3605 |
#elif defined (__GNUC__) |
| 3606 |
# pragma GCC diagnostic push |
| 3607 |
# pragma GCC diagnostic ignored "-Wsign-compare" |
| 3608 |
# pragma GCC diagnostic ignored "-Wfree-nonheap-object" |
| 3609 |
#endif |
| 3610 |
|
| 3611 |
// Parser, defined in Expression.y |
| 3612 |
# define YYTOKENTYPE |
| 3613 |
#include "Expression.tab.c" |
| 3614 |
|
| 3615 |
#ifndef DOXYGEN_SHOULD_SKIP_THIS |
| 3616 |
// Scanner, defined in Expression.l |
| 3617 |
#include "Expression.lex.c" |
| 3618 |
#endif // DOXYGEN_SHOULD_SKIP_THIS |
| 3619 |
|
| 3620 |
class StringBufferCleaner |
| 3621 |
{ |
| 3622 |
public: |
| 3623 |
explicit StringBufferCleaner(YY_BUFFER_STATE buffer) |
| 3624 |
: my_string_buffer {buffer} |
| 3625 |
{} |
| 3626 |
~StringBufferCleaner() |
| 3627 |
{ |
| 3628 |
// free the scan buffer |
| 3629 |
yy_delete_buffer(my_string_buffer); |
| 3630 |
} |
| 3631 |
|
| 3632 |
StringBufferCleaner(const StringBufferCleaner&) = delete; |
| 3633 |
StringBufferCleaner(StringBufferCleaner&&) = delete; |
| 3634 |
StringBufferCleaner& operator=(const StringBufferCleaner&) = delete; |
| 3635 |
StringBufferCleaner& operator=(StringBufferCleaner&&) = delete; |
| 3636 |
|
| 3637 |
private: |
| 3638 |
YY_BUFFER_STATE my_string_buffer; |
| 3639 |
}; |
| 3640 |
|
| 3641 |
#if defined(__clang__) |
| 3642 |
# pragma clang diagnostic pop |
| 3643 |
#elif defined (__GNUC__) |
| 3644 |
# pragma GCC diagnostic pop |
| 3645 |
#endif |
| 3646 |
|
| 3647 |
#ifdef _MSC_VER |
| 3648 |
# define strdup _strdup |
| 3649 |
#endif |
| 3650 |
|
| 3651 |
static void initParser(const App::DocumentObject *owner) |
| 3652 |
{ |
| 3653 |
static bool has_registered_functions = false; |
| 3654 |
|
| 3655 |
using namespace App::ExpressionParser; |
| 3656 |
|
| 3657 |
ScanResult = nullptr; |
| 3658 |
App::ExpressionParser::DocumentObject = owner; |
| 3659 |
labels = std::stack<std::string>(); |
| 3660 |
column = 0; |
| 3661 |
unitExpression = valueExpression = false; |
| 3662 |
|
| 3663 |
if (!has_registered_functions) { |
| 3664 |
registered_functions["abs"] = FunctionExpression::ABS; |
| 3665 |
registered_functions["acos"] = FunctionExpression::ACOS; |
| 3666 |
registered_functions["asin"] = FunctionExpression::ASIN; |
| 3667 |
registered_functions["atan"] = FunctionExpression::ATAN; |
| 3668 |
registered_functions["atan2"] = FunctionExpression::ATAN2; |
| 3669 |
registered_functions["cath"] = FunctionExpression::CATH; |
| 3670 |
registered_functions["cbrt"] = FunctionExpression::CBRT; |
| 3671 |
registered_functions["ceil"] = FunctionExpression::CEIL; |
| 3672 |
registered_functions["cos"] = FunctionExpression::COS; |
| 3673 |
registered_functions["cosh"] = FunctionExpression::COSH; |
| 3674 |
registered_functions["exp"] = FunctionExpression::EXP; |
| 3675 |
registered_functions["floor"] = FunctionExpression::FLOOR; |
| 3676 |
registered_functions["hypot"] = FunctionExpression::HYPOT; |
| 3677 |
registered_functions["log"] = FunctionExpression::LOG; |
| 3678 |
registered_functions["log10"] = FunctionExpression::LOG10; |
| 3679 |
registered_functions["mod"] = FunctionExpression::MOD; |
| 3680 |
registered_functions["pow"] = FunctionExpression::POW; |
| 3681 |
registered_functions["round"] = FunctionExpression::ROUND; |
| 3682 |
registered_functions["sin"] = FunctionExpression::SIN; |
| 3683 |
registered_functions["sinh"] = FunctionExpression::SINH; |
| 3684 |
registered_functions["sqrt"] = FunctionExpression::SQRT; |
| 3685 |
registered_functions["tan"] = FunctionExpression::TAN; |
| 3686 |
registered_functions["tanh"] = FunctionExpression::TANH; |
| 3687 |
registered_functions["trunc"] = FunctionExpression::TRUNC; |
| 3688 |
registered_functions["vangle"] = FunctionExpression::VANGLE; |
| 3689 |
registered_functions["vcross"] = FunctionExpression::VCROSS; |
| 3690 |
registered_functions["vdot"] = FunctionExpression::VDOT; |
| 3691 |
registered_functions["vlinedist"] = FunctionExpression::VLINEDIST; |
| 3692 |
registered_functions["vlinesegdist"] = FunctionExpression::VLINESEGDIST; |
| 3693 |
registered_functions["vlineproj"] = FunctionExpression::VLINEPROJ; |
| 3694 |
registered_functions["vnormalize"] = FunctionExpression::VNORMALIZE; |
| 3695 |
registered_functions["vplanedist"] = FunctionExpression::VPLANEDIST; |
| 3696 |
registered_functions["vplaneproj"] = FunctionExpression::VPLANEPROJ; |
| 3697 |
registered_functions["vscale"] = FunctionExpression::VSCALE; |
| 3698 |
registered_functions["vscalex"] = FunctionExpression::VSCALEX; |
| 3699 |
registered_functions["vscaley"] = FunctionExpression::VSCALEY; |
| 3700 |
registered_functions["vscalez"] = FunctionExpression::VSCALEZ; |
| 3701 |
|
| 3702 |
registered_functions["minvert"] = FunctionExpression::MINVERT; |
| 3703 |
registered_functions["mrotate"] = FunctionExpression::MROTATE; |
| 3704 |
registered_functions["mrotatex"] = FunctionExpression::MROTATEX; |
| 3705 |
registered_functions["mrotatey"] = FunctionExpression::MROTATEY; |
| 3706 |
registered_functions["mrotatez"] = FunctionExpression::MROTATEZ; |
| 3707 |
registered_functions["mscale"] = FunctionExpression::MSCALE; |
| 3708 |
registered_functions["mtranslate"] = FunctionExpression::MTRANSLATE; |
| 3709 |
|
| 3710 |
registered_functions["create"] = FunctionExpression::CREATE; |
| 3711 |
registered_functions["list"] = FunctionExpression::LIST; |
| 3712 |
registered_functions["matrix"] = FunctionExpression::MATRIX; |
| 3713 |
registered_functions["placement"] = FunctionExpression::PLACEMENT; |
| 3714 |
registered_functions["rotation"] = FunctionExpression::ROTATION; |
| 3715 |
registered_functions["rotationx"] = FunctionExpression::ROTATIONX; |
| 3716 |
registered_functions["rotationy"] = FunctionExpression::ROTATIONY; |
| 3717 |
registered_functions["rotationz"] = FunctionExpression::ROTATIONZ; |
| 3718 |
registered_functions["str"] = FunctionExpression::STR; |
| 3719 |
registered_functions["parsequant"] = FunctionExpression::PARSEQUANT; |
| 3720 |
registered_functions["translationm"] = FunctionExpression::TRANSLATIONM; |
| 3721 |
registered_functions["tuple"] = FunctionExpression::TUPLE; |
| 3722 |
registered_functions["vector"] = FunctionExpression::VECTOR; |
| 3723 |
|
| 3724 |
registered_functions["hiddenref"] = FunctionExpression::HIDDENREF; |
| 3725 |
registered_functions["href"] = FunctionExpression::HREF; |
| 3726 |
|
| 3727 |
registered_functions["not"] = FunctionExpression::NOT; |
| 3728 |
|
| 3729 |
// Aggregates |
| 3730 |
registered_functions["average"] = FunctionExpression::AVERAGE; |
| 3731 |
registered_functions["count"] = FunctionExpression::COUNT; |
| 3732 |
registered_functions["max"] = FunctionExpression::MAX; |
| 3733 |
registered_functions["min"] = FunctionExpression::MIN; |
| 3734 |
registered_functions["stddev"] = FunctionExpression::STDDEV; |
| 3735 |
registered_functions["sum"] = FunctionExpression::SUM; |
| 3736 |
registered_functions["and"] = FunctionExpression::AND; |
| 3737 |
registered_functions["or"] = FunctionExpression::OR; |
| 3738 |
|
| 3739 |
has_registered_functions = true; |
| 3740 |
} |
| 3741 |
} |
| 3742 |
|
| 3743 |
std::vector<std::tuple<int, int, std::string> > tokenize(const std::string &str) |
| 3744 |
{ |
| 3745 |
ExpressionParser::YY_BUFFER_STATE buf = ExpressionParser_scan_string(str.c_str()); |
| 3746 |
ExpressionParser::StringBufferCleaner cleaner(buf); |
| 3747 |
std::vector<std::tuple<int, int, std::string> > result; |
| 3748 |
int token; |
| 3749 |
|
| 3750 |
column = 0; |
| 3751 |
try { |
| 3752 |
while ( (token = ExpressionParserlex()) != 0) |
| 3753 |
result.emplace_back(token, ExpressionParser::last_column, yytext); |
| 3754 |
} |
| 3755 |
catch (...) { |
| 3756 |
// Ignore all exceptions |
| 3757 |
} |
| 3758 |
|
| 3759 |
return result; |
| 3760 |
} |
| 3761 |
|
| 3762 |
} |
| 3763 |
|
| 3764 |
} |
| 3765 |
|
| 3766 |
/** |
| 3767 |
* Parse the expression given by \a buffer, and use \a owner as the owner of the |
| 3768 |
* returned expression. If the parser fails for some reason, and exception is thrown. |
| 3769 |
* |
| 3770 |
* @param owner The DocumentObject that will own the expression. |
| 3771 |
* @param buffer The string buffer to parse. |
| 3772 |
* |
| 3773 |
* @returns A pointer to an expression. |
| 3774 |
* |
| 3775 |
*/ |
| 3776 |
|
| 3777 |
Expression * App::ExpressionParser::parse(const App::DocumentObject *owner, const char* buffer) |
| 3778 |
{ |
| 3779 |
// parse from buffer |
| 3780 |
ExpressionParser::YY_BUFFER_STATE my_string_buffer = ExpressionParser::ExpressionParser_scan_string (buffer); |
| 3781 |
ExpressionParser::StringBufferCleaner cleaner(my_string_buffer); |
| 3782 |
|
| 3783 |
initParser(owner); |
| 3784 |
|
| 3785 |
// run the parser |
| 3786 |
int result = ExpressionParser::ExpressionParser_yyparse (); |
| 3787 |
|
| 3788 |
if (result != 0) { |
| 3789 |
throw ParserError(fmt::format("Failed to parse expression '{}'", buffer)); |
| 3790 |
} |
| 3791 |
|
| 3792 |
if (!ScanResult) { |
| 3793 |
throw ParserError(fmt::format("Unknown error in expression '{}'", buffer)); |
| 3794 |
} |
| 3795 |
|
| 3796 |
if (valueExpression) { |
| 3797 |
return ScanResult; |
| 3798 |
} |
| 3799 |
else { |
| 3800 |
delete ScanResult; |
| 3801 |
throw Expression::Exception("Expression can not evaluate to a value."); |
| 3802 |
} |
| 3803 |
} |
| 3804 |
|
| 3805 |
UnitExpression * ExpressionParser::parseUnit(const App::DocumentObject *owner, const char* buffer) |
| 3806 |
{ |
| 3807 |
// parse from buffer |
| 3808 |
ExpressionParser::YY_BUFFER_STATE my_string_buffer = ExpressionParser::ExpressionParser_scan_string (buffer); |
| 3809 |
ExpressionParser::StringBufferCleaner cleaner(my_string_buffer); |
| 3810 |
|
| 3811 |
initParser(owner); |
| 3812 |
|
| 3813 |
// run the parser |
| 3814 |
int result = ExpressionParser::ExpressionParser_yyparse (); |
| 3815 |
|
| 3816 |
if (result != 0) |
| 3817 |
throw ParserError("Failed to parse expression."); |
| 3818 |
|
| 3819 |
if (!ScanResult) |
| 3820 |
throw ParserError("Unknown error in expression"); |
| 3821 |
|
| 3822 |
// Simplify expression |
| 3823 |
Expression * simplified = ScanResult->simplify(); |
| 3824 |
|
| 3825 |
if (!unitExpression) { |
| 3826 |
OperatorExpression * fraction = freecad_cast<OperatorExpression*>(ScanResult); |
| 3827 |
|
| 3828 |
if (fraction && fraction->getOperator() == OperatorExpression::DIV) { |
| 3829 |
NumberExpression * nom = freecad_cast<NumberExpression*>(fraction->getLeft()); |
| 3830 |
UnitExpression * denom = freecad_cast<UnitExpression*>(fraction->getRight()); |
| 3831 |
|
| 3832 |
// If not initially a unit expression, but value is equal to 1, it means the expression is something like 1/unit |
| 3833 |
if (denom && nom && essentiallyEqual(nom->getValue(), 1.0)) |
| 3834 |
unitExpression = true; |
| 3835 |
} |
| 3836 |
} |
| 3837 |
delete ScanResult; |
| 3838 |
|
| 3839 |
if (unitExpression) { |
| 3840 |
NumberExpression * num = freecad_cast<NumberExpression*>(simplified); |
| 3841 |
|
| 3842 |
if (num) { |
| 3843 |
simplified = new UnitExpression(num->getOwner(), num->getQuantity()); |
| 3844 |
delete num; |
| 3845 |
} |
| 3846 |
return freecad_cast<UnitExpression*>(simplified); |
| 3847 |
} |
| 3848 |
else { |
| 3849 |
delete simplified; |
| 3850 |
throw Expression::Exception("Expression is not a unit."); |
| 3851 |
} |
| 3852 |
} |
| 3853 |
|
| 3854 |
namespace { |
| 3855 |
std::tuple<int, int> getTokenAndStatus(const std::string & str) |
| 3856 |
{ |
| 3857 |
ExpressionParser::YY_BUFFER_STATE buf = ExpressionParser::ExpressionParser_scan_string(str.c_str()); |
| 3858 |
ExpressionParser::StringBufferCleaner cleaner(buf); |
| 3859 |
int token = ExpressionParser::ExpressionParserlex(); |
| 3860 |
int status = ExpressionParser::ExpressionParserlex(); |
| 3861 |
|
| 3862 |
return std::make_tuple(token, status); |
| 3863 |
} |
| 3864 |
} |
| 3865 |
|
| 3866 |
bool ExpressionParser::isTokenAnIndentifier(const std::string & str) |
| 3867 |
{ |
| 3868 |
int token{}, status{}; |
| 3869 |
std::tie(token, status) = getTokenAndStatus(str); |
| 3870 |
return (status == 0 && (token == IDENTIFIER || token == CELLADDRESS)); |
| 3871 |
} |
| 3872 |
|
| 3873 |
bool ExpressionParser::isTokenAConstant(const std::string & str) |
| 3874 |
{ |
| 3875 |
int token{}, status{}; |
| 3876 |
std::tie(token, status) = getTokenAndStatus(str); |
| 3877 |
return (status == 0 && token == CONSTANT); |
| 3878 |
} |
| 3879 |
|
| 3880 |
bool ExpressionParser::isTokenAUnit(const std::string & str) |
| 3881 |
{ |
| 3882 |
int token{}, status{}; |
| 3883 |
std::tie(token, status) = getTokenAndStatus(str); |
| 3884 |
return (status == 0 && token == UNIT); |
| 3885 |
} |
| 3886 |
|
| 3887 |
#if defined(__clang__) |
| 3888 |
# pragma clang diagnostic pop |
| 3889 |
#endif |