KiCad PCB EDA Suite
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages Concepts
libeval_compiler.h
Go to the documentation of this file.
1/*
2 This file is part of libeval, a simple math expression evaluator
3
4 Copyright (C) 2007 Michael Geselbracht, mgeselbracht3@gmail.com
5 Copyright The KiCad Developers, see AUTHORS.txt for contributors.
6
7 This program is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
11
12 This program 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 General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <https://www.gnu.org/licenses/>.
19*/
20
21#ifndef __LIBEVAL_COMPILER_H
22#define __LIBEVAL_COMPILER_H
23
24#include <cstddef>
25#include <functional>
26#include <map>
27#include <string>
28#include <stack>
29
30#include <kicommon.h>
31#include <base_units.h>
32#include <wx/intl.h>
33
34#if defined(WIN32)
35// This gets leaked by python headers on MSVC only and will cause chaos
36#undef COMPILER
37#endif
38
39#define TR_OP_BINARY_MASK 0x200
40#define TR_OP_UNARY_MASK 0x100
41
42#define TR_OP_MUL 0x201
43#define TR_OP_DIV 0x202
44#define TR_OP_ADD 0x203
45#define TR_OP_SUB 0x204
46#define TR_OP_LESS 0x205
47#define TR_OP_GREATER 0x206
48#define TR_OP_LESS_EQUAL 0x207
49#define TR_OP_GREATER_EQUAL 0x208
50#define TR_OP_EQUAL 0x209
51#define TR_OP_NOT_EQUAL 0x20a
52#define TR_OP_BOOL_AND 0x20b
53#define TR_OP_BOOL_OR 0x20c
54#define TR_OP_BOOL_NOT 0x100
55#define TR_OP_FUNC_CALL 24
56#define TR_OP_METHOD_CALL 25
57#define TR_UOP_PUSH_VAR 1
58#define TR_UOP_PUSH_VALUE 2
59
60// This namespace is used for the lemon parser
61namespace LIBEVAL
62{
63
64class COMPILER;
65
67{
71};
72
74{
75 bool pendingError = false;
76
78 wxString message;
79 int srcPos;
80};
81
82
84{
91};
92
94{
103 TR_NULL = 8
105
106class UOP;
107class UCODE;
108class CONTEXT;
109class VAR_REF;
110
111typedef std::function<void( CONTEXT*, void* )> FUNC_CALL_REF;
112
114{
115 wxString* str;
116 double num;
117 int idx;
118};
119
120// Lemon can't handle c'tors and d'tors, so we provide a poor-man's version.
121constexpr T_TOKEN_VALUE defaultTokenValue = { nullptr, 0.0, 0 };
122
123
125{
126 int token;
128};
129
130// Lemon can't handle c'tors and d'tors, so we provide a poor-man's version.
132
133
135{
136public:
138
139 int op;
140 TREE_NODE* leaf[2];
142 bool valid;
146
147 void SetUop( int aOp, double aValue );
148 void SetUop( int aOp, const wxString& aValue, bool aStringIsWildcard );
149 void SetUop( int aOp, std::unique_ptr<VAR_REF> aRef = nullptr );
150 void SetUop( int aOp, FUNC_CALL_REF aFunc, std::unique_ptr<VAR_REF> aRef = nullptr );
151};
152
153
154TREE_NODE* newNode( LIBEVAL::COMPILER* compiler, int op,
155 const T_TOKEN_VALUE& value = defaultTokenValue );
156
158{
159public:
161 {
162 }
163
165 {
166 }
167
168 virtual const std::vector<wxString>& GetSupportedUnits() const
169 {
170 static const std::vector<wxString> nullUnits;
171
172 return nullUnits;
173 }
174
175 virtual wxString GetSupportedUnitsMessage() const
176 {
177 return wxEmptyString;
178 }
179
180 virtual double Convert( const wxString& aString, int unitType ) const
181 {
182 return 0.0;
183 };
184};
185
186
188{
189public:
191 m_type( VT_UNDEFINED ),
192 m_valueDbl( 0 ),
193 m_stringIsWildcard( false ),
194 m_isDeferredDbl( false ),
195 m_isDeferredStr( false )
196 {};
197
198 VALUE( const wxString& aStr, bool aIsWildcard = false ) :
199 m_type( VT_STRING ),
200 m_valueDbl( 0 ),
201 m_valueStr( aStr ),
202 m_stringIsWildcard( aIsWildcard ),
203 m_isDeferredDbl( false ),
204 m_isDeferredStr( false )
205 {};
206
207 VALUE( const double aVal ) :
208 m_type( VT_NUMERIC ),
209 m_valueDbl( aVal ),
210 m_stringIsWildcard( false ),
211 m_isDeferredDbl( false ),
212 m_isDeferredStr( false )
213 {};
214
216 {
217 VALUE* v = new VALUE();
218 v->m_type = VT_NULL;
219 return v;
220 }
221
222 virtual ~VALUE()
223 {};
224
225 virtual double AsDouble() const
226 {
227 if( m_isDeferredDbl )
228 {
229 m_valueDbl = m_lambdaDbl();
230 m_isDeferredDbl = false;
231 }
232
233 return m_valueDbl;
234 }
235
236 virtual const wxString& AsString() const
237 {
238 if( m_isDeferredStr )
239 {
240 m_valueStr = m_lambdaStr();
241 m_isDeferredStr = false;
242 }
243
244 return m_valueStr;
245 }
246
247 virtual bool EqualTo( CONTEXT* aCtx, const VALUE* b ) const;
248
249 // NB: this is not an inverse of EqualTo as they both return false for undefined values.
250 virtual bool NotEqualTo( CONTEXT* aCtx, const VALUE* b ) const;
251
252 VAR_TYPE_T GetType() const { return m_type; };
253
254 void Set( double aValue )
255 {
256 m_type = VT_NUMERIC;
257 m_valueDbl = aValue;
258 }
259
260 void SetDeferredEval( std::function<double()> aLambda )
261 {
262 m_type = VT_NUMERIC;
263 m_lambdaDbl = aLambda;
264 m_isDeferredDbl = true;
265 }
266
267 void SetDeferredEval( std::function<wxString()> aLambda )
268 {
269 m_type = VT_STRING;
270 m_lambdaStr = aLambda;
271 m_isDeferredStr = true;
272 }
273
274 void Set( const wxString& aValue )
275 {
276 m_type = VT_STRING;
277 m_valueStr = aValue;
278 }
279
280 void Set( const VALUE &val )
281 {
282 m_type = val.m_type;
283 m_valueDbl = val.m_valueDbl;
284
285 if( m_type == VT_STRING )
286 m_valueStr = val.m_valueStr;
287 }
288
289private:
291 mutable double m_valueDbl; // mutable to support deferred evaluation
292 mutable wxString m_valueStr; // mutable to support deferred evaluation
294
295 mutable bool m_isDeferredDbl;
296 std::function<double()> m_lambdaDbl;
297
298 mutable bool m_isDeferredStr;
299 std::function<wxString()> m_lambdaStr;
300};
301
303{
304public:
306 virtual ~VAR_REF() {};
307
308 virtual VAR_TYPE_T GetType() const = 0;
309 virtual VALUE* GetValue( CONTEXT* aCtx ) = 0;
310};
311
312
314{
315public:
317 m_stack(),
318 m_stackPtr( 0 )
319 {
320 m_ownedValues.reserve( 20 );
321 }
322
323 virtual ~CONTEXT()
324 {
325 for( VALUE* v : m_ownedValues )
326 {
327 delete v;
328 }
329 }
330
332 {
333 m_ownedValues.emplace_back( new VALUE );
334 return m_ownedValues.back();
335 }
336
338 {
339 m_ownedValues.emplace_back( aValue );
340 return m_ownedValues.back();
341 }
342
343 void Push( VALUE* v )
344 {
345 m_stack[ m_stackPtr++ ] = v;
346 }
347
349 {
350 if( m_stackPtr == 0 )
351 {
352 ReportError( _( "Malformed expression" ) );
353 return AllocValue();
354 }
355
356 return m_stack[ --m_stackPtr ];
357 }
358
359 int SP() const
360 {
361 return m_stackPtr;
362 };
363
364 void SetErrorCallback( std::function<void( const wxString& aMessage, int aOffset )> aCallback )
365 {
366 m_errorCallback = std::move( aCallback );
367 }
368
369 bool HasErrorCallback() { return m_errorCallback != nullptr; }
370
371 void ReportError( const wxString& aErrorMsg );
372
373private:
374 std::vector<VALUE*> m_ownedValues;
375 VALUE* m_stack[100]; // std::stack not performant enough
377
378 std::function<void( const wxString& aMessage, int aOffset )> m_errorCallback;
379};
380
381
383{
384public:
385 virtual ~UCODE();
386
387 void AddOp( UOP* uop )
388 {
389 m_ucode.push_back(uop);
390 }
391
392 VALUE* Run( CONTEXT* ctx );
393 wxString Dump() const;
394
395 virtual std::unique_ptr<VAR_REF> CreateVarRef( const wxString& var, const wxString& field )
396 {
397 return nullptr;
398 };
399
400 virtual FUNC_CALL_REF CreateFuncCall( const wxString& name )
401 {
402 return nullptr;
403 };
404
405protected:
406
407 std::vector<UOP*> m_ucode;
408};
409
410
412{
413public:
414 UOP( int op, std::unique_ptr<VALUE> value ) :
415 m_op( op ),
416 m_ref(nullptr),
417 m_value( std::move( value ) )
418 {};
419
420 UOP( int op, std::unique_ptr<VAR_REF> vref ) :
421 m_op( op ),
422 m_ref( std::move( vref ) ),
423 m_value(nullptr)
424 {};
425
426 UOP( int op, FUNC_CALL_REF func, std::unique_ptr<VAR_REF> vref = nullptr ) :
427 m_op( op ),
428 m_func( std::move( func ) ),
429 m_ref( std::move( vref ) ),
430 m_value(nullptr)
431 {};
432
434 {
435 }
436
437 void Exec( CONTEXT* ctx );
438
439 wxString Format() const;
440
441private:
442 int m_op;
443
445 std::unique_ptr<VAR_REF> m_ref;
446 std::unique_ptr<VALUE> m_value;
447};
448
450{
451public:
452 void Restart( const wxString& aStr )
453 {
454 m_str = aStr;
455 m_pos = 0;
456 }
457
458 void Clear()
459 {
460 m_str = "";
461 m_pos = 0;
462 }
463
464 int GetChar() const
465 {
466 if( m_pos >= m_str.length() )
467 return 0;
468
469 return m_str[m_pos];
470 }
471
472 bool Done() const
473 {
474 return m_pos >= m_str.length();
475 }
476
477 void NextChar( int aAdvance = 1 )
478 {
479 m_pos += aAdvance;
480 }
481
482 size_t GetPos() const
483 {
484 return m_pos;
485 }
486
487 wxString GetString();
488
489 wxString GetChars( const std::function<bool( wxUniChar )>& cond ) const;
490
491 bool MatchAhead( const wxString& match,
492 const std::function<bool( wxUniChar )>& stopCond ) const;
493
494private:
495 wxString m_str;
496 size_t m_pos = 0;
497};
498
499
501{
502public:
503 COMPILER();
504 virtual ~COMPILER();
505
506 /*
507 * clear() should be invoked by the client if a new input string is to be processed. It
508 * will reset the parser. User defined variables are retained.
509 */
510 void Clear();
511
512 /* Used by the lemon parser */
513 void parseError( const char* s );
514 void parseOk();
515
516 int GetSourcePos() const { return m_sourcePos; }
517
518 void setRoot( LIBEVAL::TREE_NODE *root );
519 void freeTree( LIBEVAL::TREE_NODE *tree );
520
521 bool Compile( const wxString& aString, UCODE* aCode, CONTEXT* aPreflightContext );
522
523 void SetErrorCallback( std::function<void( const wxString& aMessage, int aOffset )> aCallback )
524 {
525 m_errorCallback = std::move( aCallback );
526 }
527
528 bool IsErrorPending() const { return m_errorStatus.pendingError; }
529 const ERROR_STATUS& GetError() const { return m_errorStatus; }
530
531 void GcItem( TREE_NODE* aItem ) { m_gcItems.push_back( aItem ); }
532 void GcItem( wxString* aItem ) { m_gcStrings.push_back( aItem ); }
533
534protected:
536 {
537 LS_DEFAULT = 0,
538 LS_STRING = 1,
539 };
540
542
543 bool generateUCode( UCODE* aCode, CONTEXT* aPreflightContext );
544
545 void reportError( COMPILATION_STAGE stage, const wxString& aErrorMsg, int aPos = -1 );
546
547 /* Begin processing of a new input string */
548 void newString( const wxString& aString );
549
550 /* Tokenizer: Next token/value taken from input string. */
551 T_TOKEN getToken();
552 bool lexDefault( T_TOKEN& aToken );
553 bool lexString( T_TOKEN& aToken );
554
555 int resolveUnits();
556
557protected:
558 /* Token state for input string. */
559 void* m_parser; // the current lemon parser state machine
562
563 std::unique_ptr<UNIT_RESOLVER> m_unitResolver;
564
568
569 std::function<void( const wxString& aMessage, int aOffset )> m_errorCallback;
570
572
573 std::vector<TREE_NODE*> m_gcItems;
574 std::vector<wxString*> m_gcStrings;
575};
576
577
578} // namespace LIBEVAL
579
580#endif /* LIBEVAL_COMPILER_H_ */
const char * name
Definition: DXF_plotter.cpp:59
void SetErrorCallback(std::function< void(const wxString &aMessage, int aOffset)> aCallback)
bool IsErrorPending() const
std::unique_ptr< UNIT_RESOLVER > m_unitResolver
void GcItem(wxString *aItem)
void GcItem(TREE_NODE *aItem)
LEXER_STATE m_lexerState
std::function< void(const wxString &aMessage, int aOffset)> m_errorCallback
int GetSourcePos() const
std::vector< TREE_NODE * > m_gcItems
const ERROR_STATUS & GetError() const
std::vector< wxString * > m_gcStrings
ERROR_STATUS m_errorStatus
std::vector< VALUE * > m_ownedValues
VALUE * StoreValue(VALUE *aValue)
std::function< void(const wxString &aMessage, int aOffset)> m_errorCallback
void SetErrorCallback(std::function< void(const wxString &aMessage, int aOffset)> aCallback)
void Push(VALUE *v)
void NextChar(int aAdvance=1)
void Restart(const wxString &aStr)
size_t GetPos() const
virtual std::unique_ptr< VAR_REF > CreateVarRef(const wxString &var, const wxString &field)
void AddOp(UOP *uop)
std::vector< UOP * > m_ucode
virtual FUNC_CALL_REF CreateFuncCall(const wxString &name)
virtual wxString GetSupportedUnitsMessage() const
virtual double Convert(const wxString &aString, int unitType) const
virtual const std::vector< wxString > & GetSupportedUnits() const
UOP(int op, FUNC_CALL_REF func, std::unique_ptr< VAR_REF > vref=nullptr)
std::unique_ptr< VAR_REF > m_ref
FUNC_CALL_REF m_func
UOP(int op, std::unique_ptr< VALUE > value)
std::unique_ptr< VALUE > m_value
UOP(int op, std::unique_ptr< VAR_REF > vref)
void Set(double aValue)
virtual const wxString & AsString() const
void SetDeferredEval(std::function< wxString()> aLambda)
void Set(const wxString &aValue)
static VALUE * MakeNullValue()
std::function< double()> m_lambdaDbl
virtual double AsDouble() const
VAR_TYPE_T GetType() const
void Set(const VALUE &val)
VALUE(const double aVal)
void SetDeferredEval(std::function< double()> aLambda)
std::function< wxString()> m_lambdaStr
VALUE(const wxString &aStr, bool aIsWildcard=false)
virtual VALUE * GetValue(CONTEXT *aCtx)=0
virtual VAR_TYPE_T GetType() const =0
#define _(s)
#define KICOMMON_API
Definition: kicommon.h:28
TREE_NODE * newNode(LIBEVAL::COMPILER *compiler, int op, const T_TOKEN_VALUE &value)
constexpr T_TOKEN defaultToken
constexpr T_TOKEN_VALUE defaultTokenValue
std::function< void(CONTEXT *, void *)> FUNC_CALL_REF
STL namespace.
void Format(OUTPUTFORMATTER *out, int aNestLevel, int aCtl, const CPTREE &aTree)
Output a PTREE into s-expression format via an OUTPUTFORMATTER derivative.
Definition: ptree.cpp:198
COMPILATION_STAGE stage
T_TOKEN_VALUE value
@ VALUE
Field Value of part, i.e. "3.3K".