Debian Codegraph @

src/App/ExpressionParser.h

raw
1 /****************************************************************************
2 * Copyright (c) 2015 Eivind Kvedalen <[email protected]> *
3 * Copyright (c) 2019 Zheng Lei (realthunder) <[email protected]> *
4 * *
5 * This file is part of the FreeCAD CAx development system. *
6 * *
7 * This library is free software; you can redistribute it and/or *
8 * modify it under the terms of the GNU Library General Public *
9 * License as published by the Free Software Foundation; either *
10 * version 2 of the License, or (at your option) any later version. *
11 * *
12 * This library is distributed in the hope that it will be useful, *
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
15 * GNU Library General Public License for more details. *
16 * *
17 * You should have received a copy of the GNU Library General Public *
18 * License along with this library; see the file COPYING.LIB. If not, *
19 * write to the Free Software Foundation, Inc., 59 Temple Place, *
20 * Suite 330, Boston, MA 02111-1307, USA *
21 * *
22 ****************************************************************************/
23
24
25 #ifndef EXPRESSION_PARSER_H
26 #define EXPRESSION_PARSER_H
27
28 #include "Expression.h"
29 #include <Base/Matrix.h>
30 #include <Base/Quantity.h>
31 #include <Base/Vector3D.h>
32
33 namespace App
34 {
35
36 ////////////////////////////////////////////////////////////////////////////////////
37 // Expecting the extended expression is going to be constantly amended (to
38 // conform to Python), we move most of the class declarations here to avoid
39 // constant recompiling of the whole FC code base, as the expression header is
40 // included by everyone
41 ///////////////////////////////////////////////////////////////////////////////////
42
43 struct AppExport Expression::Component
44 {
45 ObjectIdentifier::Component comp;
46 Expression* e1;
47 Expression* e2;
48 Expression* e3;
49
50 explicit Component(const std::string& n);
51 Component(Expression* e1, Expression* e2, Expression* e3, bool isRange = false);
52 explicit Component(const ObjectIdentifier::Component& comp);
53 Component(const Component& other);
54 ~Component();
55 Component& operator=(const Component&) = delete;
56
57 void visit(ExpressionVisitor& v);
58 bool isTouched() const;
59 void toString(std::ostream& ss, bool persistent) const;
60 Component* copy() const;
61 Component* eval() const;
62
63 Py::Object get(const Expression* owner, const Py::Object& pyobj) const;
64 void set(const Expression* owner, Py::Object& pyobj, const Py::Object& value) const;
65 void del(const Expression* owner, Py::Object& pyobj) const;
66 };
67
68 ////////////////////////////////////////////////////////////////////////////////////
69
70 /**
71 * Part of an expressions that contains a unit.
72 *
73 */
74
75 class AppExport UnitExpression: public Expression
76 {
77 TYPESYSTEM_HEADER_WITH_OVERRIDE();
78
79 public:
80 explicit UnitExpression(const App::DocumentObject* _owner = nullptr,
81 const Base::Quantity& _quantity = Base::Quantity(),
82 const std::string& _unitStr = std::string());
83
84 ~UnitExpression() override;
85
86 Expression* simplify() const override;
87
88 void setUnit(const Base::Quantity& _quantity);
89
90 void setQuantity(const Base::Quantity& _quantity);
91
92 double getValue() const
93 {
94 return quantity.getValue();
95 }
96
97 const Base::Unit& getUnit() const
98 {
99 return quantity.getUnit();
100 }
101
102 const Base::Quantity& getQuantity() const
103 {
104 return quantity;
105 }
106
107 const std::string getUnitString() const
108 {
109 return unitStr;
110 }
111
112 double getScaler() const
113 {
114 return quantity.getValue();
115 }
116
117 protected:
118 Expression* _copy() const override;
119 void _toString(std::ostream& ss, bool persistent, int indent) const override;
120 Py::Object _getPyValue() const override;
121
122 protected:
123 mutable PyObject* cache = nullptr;
124
125 private:
126 Base::Quantity quantity;
127 std::string unitStr; /**< The unit string from the original parsed string */
128 };
129
130 /**
131 * Class implementing a number with an optional unit
132 */
133
134 class AppExport NumberExpression: public UnitExpression
135 {
136 TYPESYSTEM_HEADER_WITH_OVERRIDE();
137
138 public:
139 explicit NumberExpression(const App::DocumentObject* _owner = nullptr,
140 const Base::Quantity& quantity = Base::Quantity());
141
142 Expression* simplify() const override;
143
144 void negate();
145
146 bool isInteger(long* v = nullptr) const;
147
148 protected:
149 Expression* _copy() const override;
150 void _toString(std::ostream& ss, bool persistent, int indent) const override;
151 };
152
153 class AppExport ConstantExpression: public NumberExpression
154 {
155 TYPESYSTEM_HEADER_WITH_OVERRIDE();
156
157 public:
158 explicit ConstantExpression(const App::DocumentObject* _owner = nullptr,
159 const char* _name = "",
160 const Base::Quantity& _quantity = Base::Quantity());
161
162 std::string getName() const
163 {
164 return name;
165 }
166
167 bool isNumber() const;
168
169 protected:
170 Py::Object _getPyValue() const override;
171 void _toString(std::ostream& ss, bool persistent, int indent) const override;
172 Expression* _copy() const override;
173
174 protected:
175 const char* name;
176 };
177
178 /**
179 * Class implementing an infix expression.
180 *
181 */
182
183 class AppExport OperatorExpression: public UnitExpression
184 {
185 TYPESYSTEM_HEADER_WITH_OVERRIDE();
186
187 public:
188 enum Operator
189 {
190 NONE,
191 ADD,
192 SUB,
193 MUL,
194 DIV,
195 MOD,
196 POW,
197 EQ,
198 NEQ,
199 LT,
200 GT,
201 LTE,
202 GTE,
203 UNIT,
204 NEG,
205 POS
206 };
207 explicit OperatorExpression(const App::DocumentObject* _owner = nullptr,
208 Expression* _left = nullptr,
209 Operator _op = NONE,
210 Expression* _right = nullptr);
211
212 ~OperatorExpression() override;
213
214 bool isTouched() const override;
215
216 Expression* simplify() const override;
217
218 int priority() const override;
219
220 Operator getOperator() const
221 {
222 return op;
223 }
224
225 Expression* getLeft() const
226 {
227 return left;
228 }
229
230 Expression* getRight() const
231 {
232 return right;
233 }
234
235 protected:
236 Expression* _copy() const override;
237
238 Py::Object _getPyValue() const override;
239
240 void _toString(std::ostream& ss, bool persistent, int indent) const override;
241
242 void _visit(ExpressionVisitor& v) override;
243
244 virtual bool isCommutative() const;
245
246 virtual bool isLeftAssociative() const;
247
248 virtual bool isRightAssociative() const;
249
250 Operator op; /**< Operator working on left and right */
251 Expression* left; /**< Left operand */
252 Expression* right; /**< Right operand */
253 };
254
255 class AppExport ConditionalExpression: public Expression
256 {
257 TYPESYSTEM_HEADER_WITH_OVERRIDE();
258
259 public:
260 explicit ConditionalExpression(const App::DocumentObject* _owner = nullptr,
261 Expression* _condition = nullptr,
262 Expression* _trueExpr = nullptr,
263 Expression* _falseExpr = nullptr);
264
265 ~ConditionalExpression() override;
266
267 bool isTouched() const override;
268
269 Expression* simplify() const override;
270
271 int priority() const override;
272
273 protected:
274 Expression* _copy() const override;
275 void _visit(ExpressionVisitor& v) override;
276 void _toString(std::ostream& ss, bool persistent, int indent) const override;
277 Py::Object _getPyValue() const override;
278
279 protected:
280 Expression* condition; /**< Condition */
281 Expression* trueExpr; /**< Expression if abs(condition) is > 0.5 */
282 Expression* falseExpr; /**< Expression if abs(condition) is < 0.5 */
283 };
284
285 /**
286 * Class implementing various functions, e.g sin, cos, etc.
287 *
288 */
289
290 class AppExport FunctionExpression: public UnitExpression
291 {
292 TYPESYSTEM_HEADER_WITH_OVERRIDE();
293
294 public:
295 enum Function
296 {
297 NONE,
298
299 // Normal functions taking one or two arguments
300 ABS,
301 ACOS,
302 ASIN,
303 ATAN,
304 ATAN2,
305 CATH,
306 CBRT,
307 CEIL,
308 COS,
309 COSH,
310 EXP,
311 FLOOR,
312 HYPOT,
313 LOG,
314 LOG10,
315 MOD,
316 POW,
317 ROUND,
318 SIN,
319 SINH,
320 SQRT,
321 TAN,
322 TANH,
323 TRUNC,
324
325 // Vector
326 VANGLE,
327 VCROSS,
328 VDOT,
329 VLINEDIST,
330 VLINESEGDIST,
331 VLINEPROJ,
332 VNORMALIZE,
333 VPLANEDIST,
334 VPLANEPROJ,
335 VSCALE,
336 VSCALEX,
337 VSCALEY,
338 VSCALEZ,
339
340 // Matrix
341 MINVERT, // invert matrix/placement/rotation
342 MROTATE, // Rotate matrix/placement/rotation around axis, by rotation object, or by euler
343 // angles.
344 MROTATEX, // Rotate matrix/placement/rotation around x-axis.
345 MROTATEY, // Rotate matrix/placement/rotation around y-axis.
346 MROTATEZ, // Rotate matrix/placement/rotation around z-axis.
347 MSCALE, // matrix scale by vector
348 MTRANSLATE, // Translate matrix/placement.
349
350 // Object creation
351 CREATE, // Create new object of a given type.
352 LIST, // Create Python list.
353 MATRIX, // Create matrix object.
354 PLACEMENT, // Create placement object.
355 ROTATION, // Create rotation object.
356 ROTATIONX, // Create x-axis rotation object.
357 ROTATIONY, // Create y-axis rotation object.
358 ROTATIONZ, // Create z-axis rotation object.
359 STR, // stringify
360 PARSEQUANT, // parse string quantity
361 TRANSLATIONM, // Create translation matrix object.
362 TUPLE, // Create Python tuple.
363 VECTOR, // Create vector object.
364
365 HIDDENREF, // hidden reference that has no dependency check
366 HREF, // deprecated alias of HIDDENREF
367
368 // Non aggregated logical
369 NOT, // logical NOT
370
371 // Aggregates
372 AGGREGATES,
373
374 AVERAGE,
375 COUNT,
376 MAX,
377 MIN,
378 STDDEV,
379 SUM,
380
381 // Logical aggregates, evaluates to {0,1}
382 AND, // logical AND
383 OR, // logical OR
384
385 // Last one
386 LAST,
387 };
388
389 explicit FunctionExpression(const App::DocumentObject* _owner = nullptr,
390 Function _f = NONE,
391 std::string&& name = std::string(),
392 std::vector<Expression*> _args = std::vector<Expression*>());
393
394 ~FunctionExpression() override;
395
396 bool isTouched() const override;
397
398 Expression* simplify() const override;
399
400 static Py::Object
401 evaluate(const Expression* owner, int type, const std::vector<Expression*>& args);
402
403 Function getFunction() const
404 {
405 return f;
406 }
407 const std::vector<Expression*>& getArgs() const
408 {
409 return args;
410 }
411
412 protected:
413 static Py::Object
414 evalAggregate(const Expression* owner, int type, const std::vector<Expression*>& args);
415 static Base::Vector3d evaluateSecondVectorArgument(const Expression* expression,
416 const std::vector<Expression*>& arguments);
417 static double extractLengthValueArgument(const Expression* expression,
418 const std::vector<Expression*>& arguments,
419 int argumentIndex);
420 static Base::Vector3d extractVectorArgument(const Expression* expression,
421 const std::vector<Expression*>& arguments,
422 int argumentIndex);
423 static void initialiseObject(const Py::Object* object,
424 const std::vector<Expression*>& arguments,
425 const unsigned long offset = 0);
426 static Py::Object transformFirstArgument(const Expression* expression,
427 const std::vector<Expression*>& arguments,
428 const Base::Matrix4D* transformationMatrix);
429 static Py::Object translationMatrix(double x, double y, double z);
430 Py::Object _getPyValue() const override;
431 Expression* _copy() const override;
432 void _visit(ExpressionVisitor& v) override;
433 void _toString(std::ostream& ss, bool persistent, int indent) const override;
434
435 Function f; /**< Function to execute */
436 std::string fname;
437 std::vector<Expression*> args; /** Arguments to function*/
438 };
439
440 /**
441 * Class implementing a reference to a property. If the name is unqualified,
442 * the owner of the expression is searched. If it is qualified, the document
443 * that contains the owning document object is searched for other document
444 * objects to search. Both labels and internal document names are searched.
445 *
446 */
447
448 class AppExport VariableExpression: public UnitExpression
449 {
450 TYPESYSTEM_HEADER_WITH_OVERRIDE();
451
452 public:
453 explicit VariableExpression(const App::DocumentObject* _owner = nullptr,
454 const ObjectIdentifier& _var = ObjectIdentifier());
455
456 ~VariableExpression() override;
457
458 bool isTouched() const override;
459
460 Expression* simplify() const override;
461
462 std::string name() const
463 {
464 return var.getPropertyName();
465 }
466
467 ObjectIdentifier getPath() const
468 {
469 return var;
470 }
471
472 void setPath(const ObjectIdentifier& path);
473
474 const App::Property* getProperty() const;
475
476 void addComponent(Component* component) override;
477
478 protected:
479 Expression* _copy() const override;
480 Py::Object _getPyValue() const override;
481 void _toString(std::ostream& ss, bool persistent, int indent) const override;
482 bool _isIndexable() const override;
483 void _getIdentifiers(std::map<App::ObjectIdentifier, bool>&) const override;
484 bool _adjustLinks(const std::set<App::DocumentObject*>&, ExpressionVisitor&) override;
485 void _importSubNames(const ObjectIdentifier::SubNameMap&) override;
486 void _updateLabelReference(App::DocumentObject*, const std::string&, const char*) override;
487 bool _updateElementReference(App::DocumentObject*, bool, ExpressionVisitor&) override;
488 bool _relabeledDocument(const std::string&, const std::string&, ExpressionVisitor&) override;
489 bool _renameObjectIdentifier(const std::map<ObjectIdentifier, ObjectIdentifier>&,
490 const ObjectIdentifier&,
491 ExpressionVisitor&) override;
492 void _collectReplacement(std::map<ObjectIdentifier, ObjectIdentifier>&,
493 const App::DocumentObject* parent,
494 App::DocumentObject* oldObj,
495 App::DocumentObject* newObj) const override;
496 void _moveCells(const CellAddress&, int, int, ExpressionVisitor&) override;
497 void _offsetCells(int, int, ExpressionVisitor&) override;
498
499 protected:
500 ObjectIdentifier var; /**< Variable name */
501 };
502
503 //////////////////////////////////////////////////////////////////////
504
505 class AppExport PyObjectExpression: public Expression
506 {
507 TYPESYSTEM_HEADER_WITH_OVERRIDE();
508
509 public:
510 explicit PyObjectExpression(const App::DocumentObject* _owner = nullptr,
511 PyObject* pyobj = nullptr,
512 bool owned = false)
513 : Expression(_owner)
514 {
515 setPyValue(pyobj, owned);
516 }
517
518 ~PyObjectExpression() override;
519
520 void setPyValue(Py::Object pyobj);
521 void setPyValue(PyObject* pyobj, bool owned = false);
522 Expression* simplify() const override
523 {
524 return copy();
525 }
526
527 protected:
528 Expression* _copy() const override;
529 void _toString(std::ostream& ss, bool persistent, int indent) const override;
530 Py::Object _getPyValue() const override;
531
532 protected:
533 PyObject* pyObj = nullptr;
534 };
535
536 /**
537 * Class implementing a string. Used to signal either a genuine string or
538 * a failed evaluation of an expression.
539 */
540
541 class AppExport StringExpression: public Expression
542 {
543 TYPESYSTEM_HEADER_WITH_OVERRIDE();
544
545 public:
546 explicit StringExpression(const App::DocumentObject* _owner = nullptr,
547 const std::string& _text = std::string());
548 ~StringExpression() override;
549
550 Expression* simplify() const override;
551
552 virtual std::string getText() const
553 {
554 return text;
555 }
556
557 protected:
558 Expression* _copy() const override;
559 void _toString(std::ostream& ss, bool persistent, int indent) const override;
560 Py::Object _getPyValue() const override;
561 bool _isIndexable() const override
562 {
563 return true;
564 }
565
566 private:
567 std::string text; /**< Text string */
568 mutable PyObject* cache = nullptr;
569 };
570
571 class AppExport RangeExpression: public App::Expression
572 {
573 TYPESYSTEM_HEADER_WITH_OVERRIDE();
574
575 public:
576 explicit RangeExpression(const App::DocumentObject* _owner = nullptr,
577 const std::string& begin = std::string(),
578 const std::string& end = std::string());
579
580 ~RangeExpression() override = default;
581
582 bool isTouched() const override;
583
584 App::Expression* simplify() const override;
585
586 Range getRange() const;
587
588 protected:
589 Expression* _copy() const override;
590 void _toString(std::ostream& ss, bool persistent, int indent) const override;
591 Py::Object _getPyValue() const override;
592 void _getIdentifiers(std::map<App::ObjectIdentifier, bool>&) const override;
593 bool _renameObjectIdentifier(const std::map<ObjectIdentifier, ObjectIdentifier>&,
594 const ObjectIdentifier&,
595 ExpressionVisitor&) override;
596 void _moveCells(const CellAddress&, int, int, ExpressionVisitor&) override;
597 void _offsetCells(int, int, ExpressionVisitor&) override;
598
599 protected:
600 std::string begin;
601 std::string end;
602 };
603
604 /**
605 * @brief Namespace for parsing expressions.
606 *
607 * Contains functionality for parsing expressions, the units of
608 * expressions, whether a token is an identifier, unit, or constant.
609 */
610 namespace ExpressionParser
611 {
612 AppExport Expression* parse(const App::DocumentObject* owner, const char* buffer);
613 AppExport UnitExpression* parseUnit(const App::DocumentObject* owner, const char* buffer);
614 AppExport ObjectIdentifier parsePath(const App::DocumentObject* owner, const char* buffer);
615 AppExport bool isTokenAnIndentifier(const std::string& str);
616 AppExport bool isTokenAConstant(const std::string& str);
617 AppExport bool isTokenAUnit(const std::string& str);
618 AppExport std::vector<std::tuple<int, int, std::string>> tokenize(const std::string& str);
619
620 /// Convenient class to mark begin of importing
621 class AppExport ExpressionImporter
622 {
623 public:
624 explicit ExpressionImporter(Base::XMLReader& reader);
625 ~ExpressionImporter();
626 static Base::XMLReader* reader();
627 };
628
629 AppExport bool isModuleImported(PyObject*);
630
631 /**
632 * @brief The semantic_type class encapsulates the value in the parse tree during parsing.
633 */
634
635 class semantic_type
636 {
637 public:
638 struct
639 {
640 Base::Quantity scaler;
641 std::string unitStr;
642 } quantity;
643 Expression::Component* component {nullptr};
644 Expression* expr {nullptr};
645 ObjectIdentifier path;
646 std::deque<ObjectIdentifier::Component> components;
647 long long int ivalue {0};
648 double fvalue {0};
649 struct
650 {
651 const char* name = "";
652 double fvalue = 0;
653 } constant;
654 std::vector<Expression*> arguments;
655 std::vector<Expression*> list;
656 std::string string;
657 std::pair<FunctionExpression::Function, std::string> func;
658 ObjectIdentifier::String string_or_identifier;
659 semantic_type()
660 : func({FunctionExpression::NONE, std::string()})
661 {}
662 };
663
664 #define YYSTYPE semantic_type
665 #include "Expression.tab.h"
666 #undef YYTOKENTYPE
667 #undef YYSTYPE
668 #undef YYSTYPE_ISDECLARED
669 } // namespace ExpressionParser
670
671 } // namespace App
672
673 #endif // EXPRESSION_PARSER_H