KiCad PCB EDA Suite
Loading...
Searching...
No Matches
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, [email protected]
5 Copyright (C) 2019-2020 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{
90};
91
93{
102 TR_NULL = 8
104
105class UOP;
106class UCODE;
107class CONTEXT;
108class VAR_REF;
109
110typedef std::function<void( CONTEXT*, void* )> FUNC_CALL_REF;
111
113{
114 wxString* str;
115 double num;
116 int idx;
117};
118
119// Lemon can't handle c'tors and d'tors, so we provide a poor-man's version.
120constexpr T_TOKEN_VALUE defaultTokenValue = { nullptr, 0.0, 0 };
121
122
124{
125 int token;
127};
128
129// Lemon can't handle c'tors and d'tors, so we provide a poor-man's version.
131
132
134{
135public:
137
138 int op;
139 TREE_NODE* leaf[2];
141 bool valid;
145
146 void SetUop( int aOp, double aValue );
147 void SetUop( int aOp, const wxString& aValue, bool aStringIsWildcard );
148 void SetUop( int aOp, std::unique_ptr<VAR_REF> aRef = nullptr );
149 void SetUop( int aOp, FUNC_CALL_REF aFunc, std::unique_ptr<VAR_REF> aRef = nullptr );
150};
151
152
153TREE_NODE* newNode( LIBEVAL::COMPILER* compiler, int op,
154 const T_TOKEN_VALUE& value = defaultTokenValue );
155
157{
158public:
160 {
161 }
162
164 {
165 }
166
167 virtual const std::vector<wxString>& GetSupportedUnits() const
168 {
169 static const std::vector<wxString> nullUnits;
170
171 return nullUnits;
172 }
173
174 virtual wxString GetSupportedUnitsMessage() const
175 {
176 return wxEmptyString;
177 }
178
179 virtual double Convert( const wxString& aString, int unitType ) const
180 {
181 return 0.0;
182 };
183};
184
185
187{
188public:
190 m_type( VT_UNDEFINED ),
191 m_valueDbl( 0 ),
192 m_stringIsWildcard( false ),
193 m_isDeferredDbl( false ),
194 m_isDeferredStr( false )
195 {};
196
197 VALUE( const wxString& aStr, bool aIsWildcard = false ) :
198 m_type( VT_STRING ),
199 m_valueDbl( 0 ),
200 m_valueStr( aStr ),
201 m_stringIsWildcard( aIsWildcard ),
202 m_isDeferredDbl( false ),
203 m_isDeferredStr( false )
204 {};
205
206 VALUE( const double aVal ) :
207 m_type( VT_NUMERIC ),
208 m_valueDbl( aVal ),
209 m_stringIsWildcard( false ),
210 m_isDeferredDbl( false ),
211 m_isDeferredStr( false )
212 {};
213
215 {
216 VALUE* v = new VALUE();
217 v->m_type = VT_NULL;
218 return v;
219 }
220
221 virtual ~VALUE()
222 {};
223
224 virtual double AsDouble() const
225 {
226 if( m_isDeferredDbl )
227 {
228 m_valueDbl = m_lambdaDbl();
229 m_isDeferredDbl = false;
230 }
231
232 return m_valueDbl;
233 }
234
235 virtual const wxString& AsString() const
236 {
237 if( m_isDeferredStr )
238 {
239 m_valueStr = m_lambdaStr();
240 m_isDeferredStr = false;
241 }
242
243 return m_valueStr;
244 }
245
246 virtual bool EqualTo( CONTEXT* aCtx, const VALUE* b ) const;
247
248 // NB: this is not an inverse of EqualTo as they both return false for undefined values.
249 virtual bool NotEqualTo( CONTEXT* aCtx, const VALUE* b ) const;
250
251 VAR_TYPE_T GetType() const { return m_type; };
252
253 void Set( double aValue )
254 {
255 m_type = VT_NUMERIC;
256 m_valueDbl = aValue;
257 }
258
259 void SetDeferredEval( std::function<double()> aLambda )
260 {
261 m_type = VT_NUMERIC;
262 m_lambdaDbl = aLambda;
263 m_isDeferredDbl = true;
264 }
265
266 void SetDeferredEval( std::function<wxString()> aLambda )
267 {
268 m_type = VT_STRING;
269 m_lambdaStr = aLambda;
270 m_isDeferredStr = true;
271 }
272
273 void Set( const wxString& aValue )
274 {
275 m_type = VT_STRING;
276 m_valueStr = aValue;
277 }
278
279 void Set( const VALUE &val )
280 {
281 m_type = val.m_type;
282 m_valueDbl = val.m_valueDbl;
283
284 if( m_type == VT_STRING )
285 m_valueStr = val.m_valueStr;
286 }
287
288private:
290 mutable double m_valueDbl; // mutable to support deferred evaluation
291 mutable wxString m_valueStr; // mutable to support deferred evaluation
293
294 mutable bool m_isDeferredDbl;
295 std::function<double()> m_lambdaDbl;
296
297 mutable bool m_isDeferredStr;
298 std::function<wxString()> m_lambdaStr;
299};
300
302{
303public:
305 virtual ~VAR_REF() {};
306
307 virtual VAR_TYPE_T GetType() const = 0;
308 virtual VALUE* GetValue( CONTEXT* aCtx ) = 0;
309};
310
311
313{
314public:
316 m_stack(),
317 m_stackPtr( 0 )
318 {
319 m_ownedValues.reserve( 20 );
320 }
321
322 virtual ~CONTEXT()
323 {
324 for( VALUE* v : m_ownedValues )
325 {
326 delete v;
327 }
328 }
329
331 {
332 m_ownedValues.emplace_back( new VALUE );
333 return m_ownedValues.back();
334 }
335
337 {
338 m_ownedValues.emplace_back( aValue );
339 return m_ownedValues.back();
340 }
341
342 void Push( VALUE* v )
343 {
344 m_stack[ m_stackPtr++ ] = v;
345 }
346
348 {
349 if( m_stackPtr == 0 )
350 {
351 ReportError( _( "Malformed expression" ) );
352 return AllocValue();
353 }
354
355 return m_stack[ --m_stackPtr ];
356 }
357
358 int SP() const
359 {
360 return m_stackPtr;
361 };
362
363 void SetErrorCallback( std::function<void( const wxString& aMessage, int aOffset )> aCallback )
364 {
365 m_errorCallback = std::move( aCallback );
366 }
367
368 bool HasErrorCallback() { return m_errorCallback != nullptr; }
369
370 void ReportError( const wxString& aErrorMsg );
371
372private:
373 std::vector<VALUE*> m_ownedValues;
374 VALUE* m_stack[100]; // std::stack not performant enough
376
377 std::function<void( const wxString& aMessage, int aOffset )> m_errorCallback;
378};
379
380
382{
383public:
384 virtual ~UCODE();
385
386 void AddOp( UOP* uop )
387 {
388 m_ucode.push_back(uop);
389 }
390
391 VALUE* Run( CONTEXT* ctx );
392 wxString Dump() const;
393
394 virtual std::unique_ptr<VAR_REF> CreateVarRef( const wxString& var, const wxString& field )
395 {
396 return nullptr;
397 };
398
399 virtual FUNC_CALL_REF CreateFuncCall( const wxString& name )
400 {
401 return nullptr;
402 };
403
404protected:
405
406 std::vector<UOP*> m_ucode;
407};
408
409
411{
412public:
413 UOP( int op, std::unique_ptr<VALUE> value ) :
414 m_op( op ),
415 m_ref(nullptr),
416 m_value( std::move( value ) )
417 {};
418
419 UOP( int op, std::unique_ptr<VAR_REF> vref ) :
420 m_op( op ),
421 m_ref( std::move( vref ) ),
422 m_value(nullptr)
423 {};
424
425 UOP( int op, FUNC_CALL_REF func, std::unique_ptr<VAR_REF> vref = nullptr ) :
426 m_op( op ),
427 m_func( std::move( func ) ),
428 m_ref( std::move( vref ) ),
429 m_value(nullptr)
430 {};
431
433 {
434 }
435
436 void Exec( CONTEXT* ctx );
437
438 wxString Format() const;
439
440private:
441 int m_op;
442
444 std::unique_ptr<VAR_REF> m_ref;
445 std::unique_ptr<VALUE> m_value;
446};
447
449{
450public:
451 void Restart( const wxString& aStr )
452 {
453 m_str = aStr;
454 m_pos = 0;
455 }
456
457 void Clear()
458 {
459 m_str = "";
460 m_pos = 0;
461 }
462
463 int GetChar() const
464 {
465 if( m_pos >= m_str.length() )
466 return 0;
467
468 return m_str[m_pos];
469 }
470
471 bool Done() const
472 {
473 return m_pos >= m_str.length();
474 }
475
476 void NextChar( int aAdvance = 1 )
477 {
478 m_pos += aAdvance;
479 }
480
481 size_t GetPos() const
482 {
483 return m_pos;
484 }
485
486 wxString GetString();
487
488 wxString GetChars( const std::function<bool( wxUniChar )>& cond ) const;
489
490 bool MatchAhead( const wxString& match,
491 const std::function<bool( wxUniChar )>& stopCond ) const;
492
493private:
494 wxString m_str;
495 size_t m_pos = 0;
496};
497
498
500{
501public:
502 COMPILER();
503 virtual ~COMPILER();
504
505 /*
506 * clear() should be invoked by the client if a new input string is to be processed. It
507 * will reset the parser. User defined variables are retained.
508 */
509 void Clear();
510
511 /* Used by the lemon parser */
512 void parseError( const char* s );
513 void parseOk();
514
515 int GetSourcePos() const { return m_sourcePos; }
516
517 void setRoot( LIBEVAL::TREE_NODE *root );
518 void freeTree( LIBEVAL::TREE_NODE *tree );
519
520 bool Compile( const wxString& aString, UCODE* aCode, CONTEXT* aPreflightContext );
521
522 void SetErrorCallback( std::function<void( const wxString& aMessage, int aOffset )> aCallback )
523 {
524 m_errorCallback = std::move( aCallback );
525 }
526
527 bool IsErrorPending() const { return m_errorStatus.pendingError; }
528 const ERROR_STATUS& GetError() const { return m_errorStatus; }
529
530 void GcItem( TREE_NODE* aItem ) { m_gcItems.push_back( aItem ); }
531 void GcItem( wxString* aItem ) { m_gcStrings.push_back( aItem ); }
532
533protected:
535 {
536 LS_DEFAULT = 0,
537 LS_STRING = 1,
538 };
539
541
542 bool generateUCode( UCODE* aCode, CONTEXT* aPreflightContext );
543
544 void reportError( COMPILATION_STAGE stage, const wxString& aErrorMsg, int aPos = -1 );
545
546 /* Begin processing of a new input string */
547 void newString( const wxString& aString );
548
549 /* Tokenizer: Next token/value taken from input string. */
550 T_TOKEN getToken();
551 bool lexDefault( T_TOKEN& aToken );
552 bool lexString( T_TOKEN& aToken );
553
554 int resolveUnits();
555
556protected:
557 /* Token state for input string. */
558 void* m_parser; // the current lemon parser state machine
561
562 std::unique_ptr<UNIT_RESOLVER> m_unitResolver;
563
567
568 std::function<void( const wxString& aMessage, int aOffset )> m_errorCallback;
569
571
572 std::vector<TREE_NODE*> m_gcItems;
573 std::vector<wxString*> m_gcStrings;
574};
575
576
577} // namespace LIBEVAL
578
579#endif /* LIBEVAL_COMPILER_H_ */
const char * name
Definition: DXF_plotter.cpp:57
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:200
COMPILATION_STAGE stage
T_TOKEN_VALUE value