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 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#pragma once
22
23#include <cstddef>
24#include <functional>
25#include <map>
26#include <string>
27#include <stack>
28
29#include <kicommon.h>
30#include <base_units.h>
31#include <wx/intl.h>
32
33#if defined(WIN32)
34// This gets leaked by python headers on MSVC only and will cause chaos
35#undef COMPILER
36#endif
37
38#define TR_OP_BINARY_MASK 0x200
39#define TR_OP_UNARY_MASK 0x100
40
41#define TR_OP_MUL 0x201
42#define TR_OP_DIV 0x202
43#define TR_OP_ADD 0x203
44#define TR_OP_SUB 0x204
45#define TR_OP_LESS 0x205
46#define TR_OP_GREATER 0x206
47#define TR_OP_LESS_EQUAL 0x207
48#define TR_OP_GREATER_EQUAL 0x208
49#define TR_OP_EQUAL 0x209
50#define TR_OP_NOT_EQUAL 0x20a
51#define TR_OP_BOOL_AND 0x20b
52#define TR_OP_BOOL_OR 0x20c
53#define TR_OP_BOOL_NOT 0x100
54#define TR_OP_FUNC_CALL 24
55#define TR_OP_METHOD_CALL 25
56#define TR_UOP_PUSH_VAR 1
57#define TR_UOP_PUSH_VALUE 2
58
59// This namespace is used for the lemon parser
60namespace LIBEVAL
61{
62
63class COMPILER;
64
71
80
81
91
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
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;
141 bool valid;
145
146 void SetUop( int aOp, double aValue, EDA_UNITS aUnits );
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
175 virtual const std::vector<EDA_UNITS>& GetSupportedUnitsTypes() const
176 {
177 static const std::vector<EDA_UNITS> nullUnits;
178
179 return nullUnits;
180 }
181
182 virtual wxString GetSupportedUnitsMessage() const
183 {
184 return wxEmptyString;
185 }
186
187 virtual double Convert( const wxString& aString, int unitType ) const
188 {
189 return 0.0;
190 }
191};
192
193
195{
196public:
199 m_valueDbl( 0 ),
200 m_stringIsWildcard( false ),
201 m_isDeferredDbl( false ),
202 m_isDeferredStr( false ),
204 {}
205
206 VALUE( const wxString& aStr, bool aIsWildcard = false ) :
207 m_type( VT_STRING ),
208 m_valueDbl( 0 ),
209 m_valueStr( aStr ),
210 m_stringIsWildcard( aIsWildcard ),
211 m_isDeferredDbl( false ),
212 m_isDeferredStr( false ),
214 {}
215
216 VALUE( const double aVal ) :
218 m_valueDbl( aVal ),
219 m_stringIsWildcard( false ),
220 m_isDeferredDbl( false ),
221 m_isDeferredStr( false ),
223 {}
224
226 {
227 VALUE* v = new VALUE();
228 v->m_type = VT_NULL;
229 return v;
230 }
231
232 virtual ~VALUE() = default;
233
234 virtual double AsDouble() const
235 {
236 if( m_isDeferredDbl )
237 {
239 m_isDeferredDbl = false;
240 }
241
242 return m_valueDbl;
243 }
244
245 virtual const wxString& AsString() const
246 {
247 if( m_isDeferredStr )
248 {
250 m_isDeferredStr = false;
251 }
252
253 return m_valueStr;
254 }
255
256 virtual bool EqualTo( CONTEXT* aCtx, const VALUE* b ) const;
257
258 // NB: this is not an inverse of EqualTo as they both return false for undefined values.
259 virtual bool NotEqualTo( CONTEXT* aCtx, const VALUE* b ) const;
260
261 VAR_TYPE_T GetType() const { return m_type; };
262
263 void Set( double aValue )
264 {
266 m_valueDbl = aValue;
267 }
268
269 void SetDeferredEval( std::function<double()> aLambda )
270 {
272 m_lambdaDbl = std::move( aLambda );
273 m_isDeferredDbl = true;
274 }
275
276 void SetDeferredEval( std::function<wxString()> aLambda )
277 {
279 m_lambdaStr = std::move( aLambda );
280 m_isDeferredStr = true;
281 }
282
283 void Set( const wxString& aValue )
284 {
286 m_valueStr = aValue;
287 }
288
289 void Set( const VALUE &val )
290 {
291 m_type = val.m_type;
294 m_units = val.m_units;
295
296 if( m_type == VT_STRING )
298 }
299
300 void SetUnits( const EDA_UNITS aUnits ) { m_units = aUnits; }
301
302 EDA_UNITS GetUnits() const { return m_units; }
303
304 bool StringIsWildcard() const { return m_stringIsWildcard; }
305
306private:
308 mutable double m_valueDbl; // mutable to support deferred evaluation
309 mutable wxString m_valueStr; // mutable to support deferred evaluation
311
312 mutable bool m_isDeferredDbl;
313 std::function<double()> m_lambdaDbl;
314
315 mutable bool m_isDeferredStr;
316 std::function<wxString()> m_lambdaStr;
317
319};
320
322{
323public:
325 {}
326
327 virtual ~VAR_REF() = default;
328
329 virtual VAR_TYPE_T GetType() const = 0;
330 virtual VALUE* GetValue( CONTEXT* aCtx ) = 0;
331};
332
333
335{
336public:
338 m_stack(),
339 m_stackPtr( 0 )
340 {
341 m_ownedValues.reserve( 20 );
342 }
343
344 virtual ~CONTEXT()
345 {
346 for( VALUE* v : m_ownedValues )
347 delete v;
348 }
349
350 // We own at least one list of raw pointers. Don't let the compiler fill in copy c'tors that
351 // will only land us in trouble.
352 CONTEXT( const CONTEXT& ) = delete;
353 CONTEXT& operator=( const CONTEXT& ) = delete;
354
356 {
357 m_ownedValues.emplace_back( new VALUE );
358 return m_ownedValues.back();
359 }
360
362 {
363 m_ownedValues.emplace_back( aValue );
364 return m_ownedValues.back();
365 }
366
367 void Push( VALUE* v )
368 {
369 m_stack[ m_stackPtr++ ] = v;
370 }
371
373 {
374 if( m_stackPtr == 0 )
375 {
376 ReportError( _( "Malformed expression" ) );
377 return AllocValue();
378 }
379
380 return m_stack[ --m_stackPtr ];
381 }
382
383 int SP() const
384 {
385 return m_stackPtr;
386 };
387
388 void SetErrorCallback( std::function<void( const wxString& aMessage, int aOffset )> aCallback )
389 {
390 m_errorCallback = std::move( aCallback );
391 }
392
393 bool HasErrorCallback() { return m_errorCallback != nullptr; }
394
395 void ReportError( const wxString& aErrorMsg );
396
397private:
398 std::vector<VALUE*> m_ownedValues;
399 VALUE* m_stack[100]; // std::stack not performant enough
401
402 std::function<void( const wxString& aMessage, int aOffset )> m_errorCallback;
403};
404
405
407{
408public:
410 {}
411
412 virtual ~UCODE();
413
414 // We own at least one list of raw pointers. Don't let the compiler fill in copy c'tors that
415 // will only land us in trouble.
416 UCODE( const UCODE& ) = delete;
417 UCODE& operator=( const UCODE& ) = delete;
418
419 void AddOp( UOP* uop )
420 {
421 m_ucode.push_back(uop);
422 }
423
424 VALUE* Run( CONTEXT* ctx );
425 wxString Dump() const;
426
427 virtual std::unique_ptr<VAR_REF> CreateVarRef( const wxString& var, const wxString& field )
428 {
429 return nullptr;
430 }
431
432 virtual FUNC_CALL_REF CreateFuncCall( const wxString& name )
433 {
434 return nullptr;
435 }
436
437protected:
438 std::vector<UOP*> m_ucode;
439};
440
441
443{
444public:
445 UOP( int op, std::unique_ptr<VALUE> value ) :
446 m_op( op ),
447 m_ref(nullptr),
448 m_value( std::move( value ) )
449 {}
450
451 UOP( int op, std::unique_ptr<VAR_REF> vref ) :
452 m_op( op ),
453 m_ref( std::move( vref ) ),
454 m_value(nullptr)
455 {}
456
457 UOP( int op, FUNC_CALL_REF func, std::unique_ptr<VAR_REF> vref = nullptr ) :
458 m_op( op ),
459 m_func( std::move( func ) ),
460 m_ref( std::move( vref ) ),
461 m_value(nullptr)
462 {}
463
464 virtual ~UOP() = default;
465
466 void Exec( CONTEXT* ctx );
467
468 wxString Format() const;
469
470private:
471 int m_op;
472
474 std::unique_ptr<VAR_REF> m_ref;
475 std::unique_ptr<VALUE> m_value;
476};
477
479{
480public:
481 void Restart( const wxString& aStr )
482 {
483 m_str = aStr;
484 m_pos = 0;
485 }
486
487 void Clear()
488 {
489 m_str = "";
490 m_pos = 0;
491 }
492
493 int GetChar() const
494 {
495 if( m_pos >= m_str.length() )
496 return 0;
497
498 return m_str[m_pos];
499 }
500
501 bool Done() const
502 {
503 return m_pos >= m_str.length();
504 }
505
506 void NextChar( int aAdvance = 1 )
507 {
508 m_pos += aAdvance;
509 }
510
511 size_t GetPos() const
512 {
513 return m_pos;
514 }
515
516 wxString GetString();
517
518 wxString GetChars( const std::function<bool( wxUniChar )>& cond ) const;
519
520 bool MatchAhead( const wxString& match,
521 const std::function<bool( wxUniChar )>& stopCond ) const;
522
523private:
524 wxString m_str;
525 size_t m_pos = 0;
526};
527
528
530{
531public:
532 COMPILER();
533 virtual ~COMPILER();
534
535 // We own at least one list of raw pointers. Don't let the compiler fill in copy c'tors that
536 // will only land us in trouble.
537 COMPILER( const COMPILER& ) = delete;
538 COMPILER& operator=( const COMPILER& ) = delete;
539
540 /*
541 * clear() should be invoked by the client if a new input string is to be processed. It
542 * will reset the parser. User defined variables are retained.
543 */
544 void Clear();
545
546 /* Used by the lemon parser */
547 void parseError( const char* s );
548 void parseOk();
549
550 int GetSourcePos() const { return m_sourcePos; }
551
552 void setRoot( LIBEVAL::TREE_NODE *root );
553 void freeTree( LIBEVAL::TREE_NODE *tree );
554
555 bool Compile( const wxString& aString, UCODE* aCode, CONTEXT* aPreflightContext );
556
557 void SetErrorCallback( std::function<void( const wxString& aMessage, int aOffset )> aCallback )
558 {
559 m_errorCallback = std::move( aCallback );
560 }
561
562 bool IsErrorPending() const { return m_errorStatus.pendingError; }
563 const ERROR_STATUS& GetError() const { return m_errorStatus; }
564
565 void GcItem( TREE_NODE* aItem ) { m_gcItems.push_back( aItem ); }
566 void GcItem( wxString* aItem ) { m_gcStrings.push_back( aItem ); }
567
568protected:
570 {
573 };
574
576
577 bool generateUCode( UCODE* aCode, CONTEXT* aPreflightContext );
578
579 void reportError( COMPILATION_STAGE stage, const wxString& aErrorMsg, int aPos = -1 );
580
581 /* Begin processing of a new input string */
582 void newString( const wxString& aString );
583
584 /* Tokenizer: Next token/value taken from input string. */
586 bool lexDefault( T_TOKEN& aToken );
587 bool lexString( T_TOKEN& aToken );
588
589 int resolveUnits();
590
591protected:
592 /* Token state for input string. */
593 void* m_parser; // the current lemon parser state machine
596
597 std::unique_ptr<UNIT_RESOLVER> m_unitResolver;
598
602
603 std::function<void( const wxString& aMessage, int aOffset )> m_errorCallback;
604
606
607 std::vector<TREE_NODE*> m_gcItems;
608 std::vector<wxString*> m_gcStrings;
609};
610
611
612} // namespace LIBEVAL
613
const char * name
void SetErrorCallback(std::function< void(const wxString &aMessage, int aOffset)> aCallback)
bool IsErrorPending() const
std::unique_ptr< UNIT_RESOLVER > m_unitResolver
void newString(const wxString &aString)
void GcItem(wxString *aItem)
bool lexString(T_TOKEN &aToken)
void GcItem(TREE_NODE *aItem)
COMPILER(const COMPILER &)=delete
bool generateUCode(UCODE *aCode, CONTEXT *aPreflightContext)
std::function< void(const wxString &aMessage, int aOffset)> m_errorCallback
bool lexDefault(T_TOKEN &aToken)
std::vector< TREE_NODE * > m_gcItems
void reportError(COMPILATION_STAGE stage, const wxString &aErrorMsg, int aPos=-1)
const ERROR_STATUS & GetError() const
COMPILER & operator=(const COMPILER &)=delete
std::vector< wxString * > m_gcStrings
ERROR_STATUS m_errorStatus
void parseError(const char *s)
std::vector< VALUE * > m_ownedValues
VALUE * StoreValue(VALUE *aValue)
void ReportError(const wxString &aErrorMsg)
std::function< void(const wxString &aMessage, int aOffset)> m_errorCallback
CONTEXT(const CONTEXT &)=delete
void SetErrorCallback(std::function< void(const wxString &aMessage, int aOffset)> aCallback)
CONTEXT & operator=(const CONTEXT &)=delete
void Push(VALUE *v)
void NextChar(int aAdvance=1)
void Restart(const wxString &aStr)
size_t GetPos() const
void SetUop(int aOp, double aValue, EDA_UNITS aUnits)
virtual std::unique_ptr< VAR_REF > CreateVarRef(const wxString &var, const wxString &field)
void AddOp(UOP *uop)
UCODE(const UCODE &)=delete
std::vector< UOP * > m_ucode
virtual FUNC_CALL_REF CreateFuncCall(const wxString &name)
UCODE & operator=(const UCODE &)=delete
virtual wxString GetSupportedUnitsMessage() const
virtual const std::vector< EDA_UNITS > & GetSupportedUnitsTypes() const
virtual double Convert(const wxString &aString, int unitType) const
virtual const std::vector< wxString > & GetSupportedUnits() const
virtual ~UOP()=default
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)
void Exec(CONTEXT *ctx)
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 SetUnits(const EDA_UNITS aUnits)
void SetDeferredEval(std::function< wxString()> aLambda)
bool StringIsWildcard() const
virtual ~VALUE()=default
void Set(const wxString &aValue)
static VALUE * MakeNullValue()
std::function< double()> m_lambdaDbl
virtual double AsDouble() const
EDA_UNITS GetUnits() 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
virtual ~VAR_REF()=default
#define _(s)
EDA_UNITS
Definition eda_units.h:48
#define KICOMMON_API
Definition kicommon.h:27
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".