KiCad PCB EDA Suite
Loading...
Searching...
No Matches
libeval_compiler.cpp
Go to the documentation of this file.
1/*
2 * This file is part of libeval, a simple math expression evaluator
3 *
4 * Copyright (C) 2017 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#include <memory>
22#include <set>
23#include <vector>
24#include <algorithm>
25
26#include <eda_units.h>
27#include <string_utils.h>
28#include <wx/log.h>
29
30#ifdef DEBUG
31#include <cstdarg>
32#endif
33
36
37/* The (generated) lemon parser is written in C.
38 * In order to keep its symbol from the global namespace include the parser code with
39 * a C++ namespace.
40 */
41namespace LIBEVAL
42{
43
44#ifdef __GNUC__
45#pragma GCC diagnostic push
46#pragma GCC diagnostic ignored "-Wunused-variable"
47#pragma GCC diagnostic ignored "-Wsign-compare"
48#endif
49
50#include <libeval_compiler/grammar.c>
51#include <libeval_compiler/grammar.h>
52
53#ifdef __GNUC__
54#pragma GCC diagnostic pop
55#endif
56
57
58#define libeval_dbg(level, fmt, ...) \
59 wxLogTrace( "libeval_compiler", fmt, __VA_ARGS__ );
60
61
62TREE_NODE* newNode( LIBEVAL::COMPILER* compiler, int op, const T_TOKEN_VALUE& value )
63{
64 TREE_NODE* t2 = new TREE_NODE();
65
66 t2->valid = true;
67 t2->value.str = value.str ? new wxString( *value.str ) : nullptr;
68 t2->value.num = value.num;
69 t2->value.idx = value.idx;
70 t2->op = op;
71 t2->leaf[0] = nullptr;
72 t2->leaf[1] = nullptr;
73 t2->isTerminal = false;
74 t2->srcPos = compiler->GetSourcePos();
75 t2->uop = nullptr;
76
77 libeval_dbg(10, " ostr %p nstr %p nnode %p op %d", value.str, t2->value.str, t2, t2->op );
78
79 if(t2->value.str)
80 compiler->GcItem( t2->value.str );
81
82 compiler->GcItem( t2 );
83
84 return t2;
85}
86
87
88static const wxString formatOpName( int op )
89{
90 static const struct
91 {
92 int op;
93 wxString mnemonic;
94 }
95 simpleOps[] =
96 {
97 { TR_OP_MUL, "MUL" },
98 { TR_OP_DIV, "DIV" },
99 { TR_OP_ADD, "ADD" },
100 { TR_OP_SUB, "SUB" },
101 { TR_OP_LESS, "LESS" },
102 { TR_OP_GREATER, "GREATER" },
103 { TR_OP_LESS_EQUAL, "LESS_EQUAL" },
104 { TR_OP_GREATER_EQUAL, "GREATER_EQUAL" },
105 { TR_OP_EQUAL, "EQUAL" },
106 { TR_OP_NOT_EQUAL, "NEQUAL" },
107 { TR_OP_BOOL_AND, "AND" },
108 { TR_OP_BOOL_OR, "OR" },
109 { TR_OP_BOOL_NOT, "NOT" },
110 { -1, "" }
111 };
112
113 for( int i = 0; simpleOps[i].op >= 0; i++ )
114 {
115 if( simpleOps[i].op == op )
116 return simpleOps[i].mnemonic;
117 }
118
119 return "???";
120}
121
122
123bool VALUE::EqualTo( CONTEXT* aCtx, const VALUE* b ) const
124{
125 if( m_type == VT_UNDEFINED || b->m_type == VT_UNDEFINED )
126 return false;
127
128 if( m_type == VT_NULL && b->m_type == VT_NULL )
129 return true;
130
131 if( m_type == VT_NUMERIC && b->m_type == VT_NUMERIC )
132 {
133 return AsDouble() == b->AsDouble();
134 }
135 else if( m_type == VT_STRING && b->m_type == VT_STRING )
136 {
137 if( b->m_stringIsWildcard )
138 return WildCompareString( b->AsString(), AsString(), false );
139 else
140 return AsString().IsSameAs( b->AsString(), false );
141 }
142
143 return false;
144}
145
146
147bool VALUE::NotEqualTo( CONTEXT* aCtx, const VALUE* b ) const
148{
149 if( m_type == VT_UNDEFINED || b->m_type == VT_UNDEFINED )
150 return false;
151
152 return !EqualTo( aCtx, b );
153}
154
155
156wxString UOP::Format() const
157{
158 wxString str;
159
160 switch( m_op )
161 {
162 case TR_UOP_PUSH_VAR:
163 str = wxString::Format( "PUSH VAR [%p]", m_ref.get() );
164 break;
165
167 if( !m_value )
168 str = wxString::Format( "PUSH nullptr" );
169 else if( m_value->GetType() == VT_NUMERIC )
170 str = wxString::Format( "PUSH NUM [%.10f]", m_value->AsDouble() );
171 else
172 str = wxString::Format( "PUSH STR [%ls]", m_value->AsString() );
173 break;
174
176 str = wxString::Format( "MCALL" );
177 break;
178
179 case TR_OP_FUNC_CALL:
180 str = wxString::Format( "FCALL" );
181 break;
182
183 case TR_OP_JZ:
184 str = wxString::Format( "JZ -> %d", m_jumpTarget );
185 break;
186
187 case TR_OP_JNZ:
188 str = wxString::Format( "JNZ -> %d", m_jumpTarget );
189 break;
190
191 default:
192 str = wxString::Format( "%s %d", formatOpName( m_op ).c_str(), m_op );
193 break;
194 }
195
196 return str;
197}
198
199
201{
202 for( UOP* op : m_ucode )
203 delete op;
204}
205
206
207wxString UCODE::Dump() const
208{
209 wxString rv;
210
211 for( UOP* op : m_ucode )
212 {
213 rv += op->Format();
214 rv += "\n";
215 }
216
217 return rv;
218};
219
220
222{
223 wxString rv;
224
225 while( m_pos < m_str.length() && m_str[ m_pos ] != '\'' )
226 {
227 if( m_str[ m_pos ] == '\\' && m_pos + 1 < m_str.length() && m_str[ m_pos + 1 ] == '\'' )
228 m_pos++;
229
230 rv.append( 1, m_str[ m_pos++ ] );
231 }
232
233 m_pos++;
234
235 return rv;
236}
237
238
239wxString TOKENIZER::GetChars( const std::function<bool( wxUniChar )>& cond ) const
240{
241 wxString rv;
242 size_t p = m_pos;
243
244 while( p < m_str.length() && cond( m_str[p] ) )
245 {
246 rv.append( 1, m_str[p] );
247 p++;
248 }
249
250 return rv;
251}
252
253
254bool TOKENIZER::MatchAhead( const wxString& match,
255 const std::function<bool( wxUniChar )>& stopCond ) const
256{
257 int remaining = (int) m_str.Length() - m_pos;
258
259 if( remaining < (int) match.length() )
260 return false;
261
262 if( m_str.substr( m_pos, match.length() ) == match )
263 return ( remaining == (int) match.length() || stopCond( m_str[m_pos + match.length()] ) );
264
265 return false;
266}
267
268
271{
273 m_sourcePos = 0;
274 m_parseFinished = false;
275 m_unitResolver = std::make_unique<UNIT_RESOLVER>();
276 m_parser = LIBEVAL::ParseAlloc( malloc );
277 m_tree = nullptr;
278 m_errorStatus.pendingError = false;
279}
280
281
283{
284 LIBEVAL::ParseFree( m_parser, free );
285
286 if( m_tree )
287 {
288 freeTree( m_tree );
289 m_tree = nullptr;
290 }
291
292 // Allow explicit call to destructor
293 m_parser = nullptr;
294
295 Clear();
296}
297
298
300{
301 //free( current.token );
302 m_tokenizer.Clear();
303
304 if( m_tree )
305 {
306 freeTree( m_tree );
307 m_tree = nullptr;
308 }
309
310 m_tree = nullptr;
311
312 for( TREE_NODE* tok : m_gcItems )
313 delete tok;
314
315 for( wxString* tok: m_gcStrings )
316 delete tok;
317
318 m_gcItems.clear();
319 m_gcStrings.clear();
320}
321
322
323void COMPILER::parseError( const char* s )
324{
326}
327
328
330{
331 m_parseFinished = true;
332}
333
334
335bool COMPILER::Compile( const wxString& aString, UCODE* aCode, CONTEXT* aPreflightContext )
336{
337 // Feed parser token after token until end of input.
338
339 newString( aString );
340
341 if( m_tree )
342 {
343 freeTree( m_tree );
344 m_tree = nullptr;
345 }
346
347 m_tree = nullptr;
348 m_parseFinished = false;
349 T_TOKEN tok( defaultToken );
350
351 libeval_dbg(0, "str: '%s' empty: %d\n", aString.c_str(), !!aString.empty() );
352
353 if( aString.empty() )
354 {
355 m_parseFinished = true;
356 return generateUCode( aCode, aPreflightContext );
357 }
358
359 do
360 {
361 m_sourcePos = m_tokenizer.GetPos();
362
363 tok = getToken();
364
365 if( tok.value.str )
366 GcItem( tok.value.str );
367
368 libeval_dbg(10, "parse: tok %d valstr %p\n", tok.token, tok.value.str );
369 Parse( m_parser, tok.token, tok, this );
370
371 if ( m_errorStatus.pendingError )
372 return false;
373
374 if( m_parseFinished || tok.token == G_ENDS )
375 {
376 // Reset parser by passing zero as token ID, value is ignored.
377 Parse( m_parser, 0, tok, this );
378 break;
379 }
380 } while( tok.token );
381
382 return generateUCode( aCode, aPreflightContext );
383}
384
385
386void COMPILER::newString( const wxString& aString )
387{
388 Clear();
389
391 m_tokenizer.Restart( aString );
392 m_parseFinished = false;
393}
394
395
397{
398 T_TOKEN rv;
400
401 bool done = false;
402
403 do
404 {
405 switch( m_lexerState )
406 {
407 case LS_DEFAULT:
408 done = lexDefault( rv );
409 break;
410
411 case LS_STRING:
412 done = lexString( rv );
413 break;
414 }
415 } while( !done );
416
417 return rv;
418}
419
420
422{
423 aToken.token = G_STRING;
424 aToken.value.str = new wxString( m_tokenizer.GetString() );
425
427 return true;
428}
429
430
432{
433 int unitId = 0;
434
435 for( const wxString& unitName : m_unitResolver->GetSupportedUnits() )
436 {
437 if( m_tokenizer.MatchAhead( unitName,
438 []( int c ) -> bool
439 {
440 return !isalnum( c );
441 } ) )
442 {
443 libeval_dbg(10, "Match unit '%s'\n", unitName.c_str() );
444 m_tokenizer.NextChar( unitName.length() );
445 return unitId;
446 }
447
448 unitId++;
449 }
450
451 return -1;
452}
453
454
456{
457 T_TOKEN retval;
458 wxString current;
459 int convertFrom;
460
461 retval.value.str = nullptr;
462 retval.value.num = 0.0;
463 retval.value.idx = -1;
464 retval.token = G_ENDS;
465
466 if( m_tokenizer.Done() )
467 {
468 aToken = retval;
469 return true;
470 }
471
472 // Lambda: get value as string, store into clToken.token and update current index.
473 auto extractNumber =
474 [&]()
475 {
476 bool haveSeparator = false;
477 bool haveDigit = false;
478 wxUniChar ch = m_tokenizer.GetChar();
479
480 auto isDecimalSeparator =
481 [&]( wxUniChar c ) -> bool
482 {
483 double dummy;
484
485 if( c == m_localeDecimalSeparator || c == '.' || c == ',' )
486 return true;
487
488 // Infix only between digits so 4k7 scales while 5mm and 100ps keep their units
489 return haveDigit && wxIsdigit( m_tokenizer.GetChar( 1 ) )
491 };
492
493 do
494 {
495 if( isDecimalSeparator( ch ) && haveSeparator )
496 break;
497
498 current.append( 1, ch );
499
500 if( isDecimalSeparator( ch ) )
501 haveSeparator = true;
502 else
503 haveDigit = true;
504
505 m_tokenizer.NextChar();
506 ch = m_tokenizer.GetChar();
507 } while( isdigit( ch ) || isDecimalSeparator( ch ) );
508
509 // Ensure that the systems decimal separator is used. Keep infix for now, as we'll need it later
510 // to scale the number.
511 for( int i = current.length(); i; i-- )
512 {
513 if( current[i - 1] == '.' || current[i - 1] == ',' )
514 current[i - 1] = m_localeDecimalSeparator;
515 }
516 };
517
518 int ch;
519
520 // Start processing of first/next token: Remove whitespace
521 for( ;; )
522 {
523 ch = m_tokenizer.GetChar();
524
525 if( ch == ' ' )
526 m_tokenizer.NextChar();
527 else
528 break;
529 }
530
531 libeval_dbg(10, "LEX ch '%c' pos %lu\n", ch, (unsigned long)m_tokenizer.GetPos() );
532
533 if( ch == 0 )
534 {
535 /* End of input */
536 }
537 else if( isdigit( ch ) )
538 {
539 // VALUE
540 extractNumber();
541 retval.token = G_VALUE;
542 retval.value.str = new wxString( current );
543 }
544 else if( ( convertFrom = resolveUnits() ) >= 0 )
545 {
546 // UNIT
547 // Units are appended to a VALUE.
548 // Determine factor to default unit if unit for value is given.
549 // Example: Default is mm, unit is inch: factor is 25.4
550 // The factor is assigned to the terminal UNIT. The actual
551 // conversion is done within a parser action.
552 retval.token = G_UNIT;
553 retval.value.idx = convertFrom;
554 }
555 else if( ch == '\'' ) // string literal
556 {
558 m_tokenizer.NextChar();
559 return false;
560 }
561 else if( isalpha( ch ) || ch == '_' )
562 {
563 current = m_tokenizer.GetChars( []( int c ) -> bool { return isalnum( c ) || c == '_'; } );
564 retval.token = G_IDENTIFIER;
565 retval.value.str = new wxString( current );
566 m_tokenizer.NextChar( current.length() );
567 }
568 else if( m_tokenizer.MatchAhead( "==", []( int c ) -> bool { return c != '='; } ) )
569 {
570 retval.token = G_EQUAL;
571 m_tokenizer.NextChar( 2 );
572 }
573 else if( m_tokenizer.MatchAhead( "!=", []( int c ) -> bool { return c != '='; } ) )
574 {
575 retval.token = G_NOT_EQUAL;
576 m_tokenizer.NextChar( 2 );
577 }
578 else if( m_tokenizer.MatchAhead( "<=", []( int c ) -> bool { return c != '='; } ) )
579 {
580 retval.token = G_LESS_EQUAL_THAN;
581 m_tokenizer.NextChar( 2 );
582 }
583 else if( m_tokenizer.MatchAhead( ">=", []( int c ) -> bool { return c != '='; } ) )
584 {
585 retval.token = G_GREATER_EQUAL_THAN;
586 m_tokenizer.NextChar( 2 );
587 }
588 else if( m_tokenizer.MatchAhead( "&&", []( int c ) -> bool { return c != '&'; } ) )
589 {
590 retval.token = G_BOOL_AND;
591 m_tokenizer.NextChar( 2 );
592 }
593 else if( m_tokenizer.MatchAhead( "||", []( int c ) -> bool { return c != '|'; } ) )
594 {
595 retval.token = G_BOOL_OR;
596 m_tokenizer.NextChar( 2 );
597 }
598 else
599 {
600 // Single char tokens
601 switch( ch )
602 {
603 case '+': retval.token = G_PLUS; break;
604 case '!': retval.token = G_BOOL_NOT; break;
605 case '-': retval.token = G_MINUS; break;
606 case '*': retval.token = G_MULT; break;
607 case '/': retval.token = G_DIVIDE; break;
608 case '<': retval.token = G_LESS_THAN; break;
609 case '>': retval.token = G_GREATER_THAN; break;
610 case '(': retval.token = G_PARENL; break;
611 case ')': retval.token = G_PARENR; break;
612 case ';': retval.token = G_SEMCOL; break;
613 case '.': retval.token = G_STRUCT_REF; break;
614 case ',': retval.token = G_COMMA; break;
615
616 default:
617 if( m_tokenizer.MatchAhead( "${", []( int c ) -> bool { return c != '{'; } ) )
618 reportError( CST_PARSE, _( "Unresolved text variable reference" ), m_sourcePos + 2 );
619 else
620 reportError( CST_PARSE, wxString::Format( _( "Unrecognized character '%c'" ), (char) ch ) );
621 break;
622 }
623
624 m_tokenizer.NextChar();
625 }
626
627 aToken = retval;
628 return true;
629}
630
631
632const wxString formatNode( TREE_NODE* node )
633{
634 return node->value.str ? *(node->value.str) : wxString( wxEmptyString );
635}
636
637
638void dumpNode( wxString& buf, TREE_NODE* tok, int depth = 0 )
639{
640 wxString str;
641
642 if( !tok )
643 return;
644
645 str.Printf( "\n[%p L0:%-20p L1:%-20p] ", tok, tok->leaf[0], tok->leaf[1] );
646 buf += str;
647
648 for( int i = 0; i < 2 * depth; i++ )
649 buf += " ";
650
651 if( tok->op & TR_OP_BINARY_MASK )
652 {
653 buf += formatOpName( tok->op );
654 dumpNode( buf, tok->leaf[0], depth + 1 );
655 dumpNode( buf, tok->leaf[1], depth + 1 );
656 }
657
658 switch( tok->op )
659 {
660 case TR_NUMBER:
661 buf += "NUMERIC: ";
662 buf += formatNode( tok );
663
664 if( tok->leaf[0] )
665 dumpNode( buf, tok->leaf[0], depth + 1 );
666
667 break;
668
669 case TR_ARG_LIST:
670 buf += "ARG_LIST: ";
671 buf += formatNode( tok );
672
673 if( tok->leaf[0] )
674 dumpNode( buf, tok->leaf[0], depth + 1 );
675 if( tok->leaf[1] )
676 dumpNode( buf, tok->leaf[1], depth + 1 );
677
678 break;
679
680 case TR_STRING:
681 buf += "STRING: ";
682 buf += formatNode( tok );
683 break;
684
685 case TR_IDENTIFIER:
686 buf += "ID: ";
687 buf += formatNode( tok );
688 break;
689
690 case TR_STRUCT_REF:
691 buf += "SREF: ";
692 dumpNode( buf, tok->leaf[0], depth + 1 );
693 dumpNode( buf, tok->leaf[1], depth + 1 );
694 break;
695
696 case TR_OP_FUNC_CALL:
697 buf += "CALL '";
698 buf += formatNode( tok->leaf[0] );
699 buf += "': ";
700 dumpNode( buf, tok->leaf[1], depth + 1 );
701 break;
702
703 case TR_UNIT:
704 str.Printf( "UNIT: %d ", tok->value.idx );
705 buf += str;
706 break;
707 }
708}
709
710
711void CONTEXT::ReportError( const wxString& aErrorMsg )
712{
713 if( m_errorCallback )
714 m_errorCallback( aErrorMsg, -1 );
715}
716
717
719{
720 ReportError( _( "Expression evaluation stack overflow" ) );
721 throw STACK_OVERFLOW{};
722}
723
724#if defined( __MINGW64__ ) // needed on MINGW to avoid a link issue
725constexpr int CONTEXT::STACK_CAPACITY;
726#endif
727
728
729void COMPILER::reportError( COMPILATION_STAGE stage, const wxString& aErrorMsg, int aPos )
730{
731 if( aPos == -1 )
732 aPos = m_sourcePos;
733
734 m_errorStatus.pendingError = true;
735 m_errorStatus.stage = stage;
736 m_errorStatus.message = aErrorMsg;
737 m_errorStatus.srcPos = aPos;
738
739 if( m_errorCallback )
740 m_errorCallback( aErrorMsg, aPos );
741}
742
743
745{
746 m_tree = root;
747}
748
749
751{
752 if ( tree->leaf[0] )
753 freeTree( tree->leaf[0] );
754
755 if ( tree->leaf[1] )
756 freeTree( tree->leaf[1] );
757
758 delete tree->uop;
759 tree->uop = nullptr;
760}
761
762
763void TREE_NODE::SetUop( int aOp, double aValue, EDA_UNITS aUnits )
764{
765 delete uop;
766
767 std::unique_ptr<VALUE> val = std::make_unique<VALUE>( aValue );
768 val->SetUnits( aUnits );
769 uop = new UOP( aOp, std::move( val ) );
770}
771
772
773void TREE_NODE::SetUop( int aOp, const wxString& aValue, bool aStringIsWildcard )
774{
775 delete uop;
776
777 std::unique_ptr<VALUE> val = std::make_unique<VALUE>( aValue, aStringIsWildcard );
778 uop = new UOP( aOp, std::move( val ) );
779}
780
781
782void TREE_NODE::SetUop( int aOp, std::unique_ptr<VAR_REF> aRef )
783{
784 delete uop;
785
786 uop = new UOP( aOp, std::move( aRef ) );
787}
788
789
790void TREE_NODE::SetUop( int aOp, FUNC_CALL_REF aFunc, std::unique_ptr<VAR_REF> aRef )
791{
792 delete uop;
793
794 uop = new UOP( aOp, std::move( aFunc ), std::move( aRef ) );
795}
796
797
798static void prepareTree( LIBEVAL::TREE_NODE *node )
799{
800 node->isVisited = false;
801
802 // fixme: for reasons I don't understand the lemon parser isn't initializing the
803 // leaf node pointers of function name nodes. -JY
804 if( node->op == TR_OP_FUNC_CALL && node->leaf[0] )
805 {
806 node->leaf[0]->leaf[0] = nullptr;
807 node->leaf[0]->leaf[1] = nullptr;
808 }
809
810 if ( node->leaf[0] )
811 prepareTree( node->leaf[0] );
812
813 if ( node->leaf[1] )
814 prepareTree( node->leaf[1] );
815}
816
817
818static std::vector<TREE_NODE*> squashParamList( TREE_NODE* root )
819{
820 std::vector<TREE_NODE*> args;
821
822 if( !root )
823 return args;
824
825 if( root->op != TR_ARG_LIST && root->op != TR_NULL )
826 {
827 args.push_back( root );
828 }
829 else
830 {
831 TREE_NODE *n = root;
832 do
833 {
834 if( n->leaf[1] )
835 args.push_back(n->leaf[1]);
836
837 n = n->leaf[0];
838 } while ( n && n->op == TR_ARG_LIST );
839
840 if( n )
841 args.push_back( n );
842 }
843
844 std::reverse( args.begin(), args.end() );
845
846 for( size_t i = 0; i < args.size(); i++ )
847 libeval_dbg( 10, "squash arg%d: %s\n", int( i ), formatNode( args[i] ) );
848
849 return args;
850}
851
852
853// Flatten a pure identifier chain (e.g. "A" or "A.Parent") that forms the receiver of a
854// property or method access into a dotted variable name. Returns false when the receiver
855// is anything else (for example the result of another method call), which is unsupported.
856// Every node consumed is marked visited so the code generator does not re-process it.
857static bool flattenVarChain( TREE_NODE* aNode, wxString& aResult )
858{
859 if( aNode->op == TR_IDENTIFIER )
860 {
861 aResult = formatNode( aNode );
862 aNode->isVisited = true;
863 return true;
864 }
865
866 if( aNode->op == TR_STRUCT_REF && aNode->leaf[0] && aNode->leaf[1]
867 && aNode->leaf[1]->op == TR_IDENTIFIER )
868 {
869 wxString base;
870
871 if( !flattenVarChain( aNode->leaf[0], base ) )
872 return false;
873
874 aResult = base + wxT( "." ) + formatNode( aNode->leaf[1] );
875 aNode->leaf[1]->isVisited = true;
876 aNode->isVisited = true;
877 return true;
878 }
879
880 return false;
881}
882
883
884bool COMPILER::generateUCode( UCODE* aCode, CONTEXT* aPreflightContext )
885{
886 std::vector<TREE_NODE*> stack;
887 wxString msg;
888 int numericValueCount = 0;
889 wxString missingUnitsMsg;
890 int missingUnitsSrcPos = 0;
891
892 // Short-circuit jumps for && / || awaiting their target backpatched once the right-hand
893 // operand's microcode has been emitted.
894 std::map<TREE_NODE*, UOP*> scJumps;
895
896 if( !m_tree )
897 {
898 std::unique_ptr<VALUE> val = std::make_unique<VALUE>( 1.0 );
899 // Empty expression returns true
900 aCode->AddOp( new UOP( TR_UOP_PUSH_VALUE, std::move(val) ) );
901 return true;
902 }
903
905
906 stack.push_back( m_tree );
907
908 wxString dump;
909
910 dumpNode( dump, m_tree, 0 );
911 libeval_dbg( 3, "Tree dump:\n%s\n\n", (const char*) dump.c_str() );
912
913 while( !stack.empty() )
914 {
915 TREE_NODE* node = stack.back();
916
917 libeval_dbg( 4, "process node %p [op %d] [stack %lu]\n", node, node->op, (unsigned long)stack.size() );
918
919 // process terminal nodes first
920 switch( node->op )
921 {
922 case TR_OP_FUNC_CALL:
923 // Function call's uop was generated inside TR_STRUCT_REF
924 if( !node->uop )
925 {
926 // This function call is bare so we don't know who to apply it to
927 // Set a safe default value to exit gracefully with an error
928 reportError( CST_CODEGEN, _( "Unknown parent of function parameters" ), node->srcPos );
930 }
931
932 node->isTerminal = true;
933 break;
934
935 case TR_STRUCT_REF:
936 {
937 // leaf[0]: object (a variable name, or a "." chain such as "A.Parent")
938 // leaf[1]: field (TR_IDENTIFIER) or TR_OP_FUNC_CALL
939
940 wxString itemName;
941
942 if( !flattenVarChain( node->leaf[0], itemName ) )
943 {
944 int pos = node->leaf[0]->srcPos;
945
946 if( node->leaf[0]->value.str )
947 pos -= static_cast<int>( formatNode( node->leaf[0] ).length() );
948
949 reportError( CST_CODEGEN, _( "Unknown parent of property" ), pos );
950
951 node->leaf[0]->isVisited = true;
952 node->leaf[1]->isVisited = true;
953
955 node->isTerminal = true;
956 break;
957 }
958
959 switch( node->leaf[1]->op )
960 {
961 case TR_IDENTIFIER:
962 {
963 // leaf[0]: object
964 // leaf[1]: field
965
966 wxString propName = formatNode( node->leaf[1] );
967 std::unique_ptr<VAR_REF> vref = aCode->CreateVarRef( itemName, propName );
968
969 if( !vref )
970 {
971 msg.Printf( _( "Unrecognized item '%s'" ), itemName );
972 reportError( CST_CODEGEN, msg, node->leaf[0]->srcPos - (int) itemName.length() );
973 }
974 else if( vref->GetType() == VT_PARSE_ERROR )
975 {
976 msg.Printf( _( "Unrecognized property '%s'" ), propName );
977 reportError( CST_CODEGEN, msg, node->leaf[1]->srcPos - (int) propName.length() );
978 }
979
980 node->leaf[1]->isVisited = true;
981
982 node->SetUop( TR_UOP_PUSH_VAR, std::move( vref ) );
983 node->isTerminal = true;
984 break;
985 }
986 case TR_OP_FUNC_CALL:
987 {
988 // leaf[0]: object
989 // leaf[1]: TR_OP_FUNC_CALL
990 // leaf[0]: function name
991 // leaf[1]: parameter
992
993 std::unique_ptr<VAR_REF> vref = aCode->CreateVarRef( itemName, "" );
994
995 if( !vref )
996 {
997 msg.Printf( _( "Unrecognized item '%s'" ), itemName );
998 reportError( CST_CODEGEN, msg, node->leaf[0]->srcPos - (int) itemName.length() );
999 }
1000
1001 wxString functionName = formatNode( node->leaf[1]->leaf[0] );
1002 auto func = aCode->CreateFuncCall( functionName );
1003 std::vector<TREE_NODE*> params = squashParamList( node->leaf[1]->leaf[1] );
1004
1005 libeval_dbg( 10, "emit func call: %s\n", functionName );
1006
1007 if( !func )
1008 {
1009 msg.Printf( _( "Unrecognized function '%s'" ), functionName );
1010 reportError( CST_CODEGEN, msg, node->leaf[0]->srcPos + 1 );
1011 }
1012
1013 // Expressions have no value until runtime; formatNode() would turn
1014 // them into empty strings and falsely report missing arguments
1015 const bool literalArgs = std::all_of( params.begin(), params.end(),
1016 []( const TREE_NODE* param )
1017 {
1018 return param->op == TR_STRING || param->op == TR_NUMBER;
1019 } );
1020
1021 if( func && literalArgs )
1022 {
1023 bool overflow = false;
1024
1025 auto previousCallback = aPreflightContext->ExchangeErrorCallback(
1026 [&]( const wxString& aMessage, int aOffset )
1027 {
1028 size_t loc = node->leaf[1]->leaf[1]->srcPos;
1029 reportError( CST_CODEGEN, aMessage, (int) loc - 1 );
1030 } );
1031
1032 try
1033 {
1034 for( TREE_NODE* pnode : params )
1035 {
1036 VALUE* param = aPreflightContext->AllocValue();
1037 param->Set( formatNode( pnode ) );
1038 aPreflightContext->Push( param );
1039 }
1040
1041 func( aPreflightContext, vref.get() );
1042 aPreflightContext->Pop(); // return value
1043 }
1044 catch( const CONTEXT::STACK_OVERFLOW& )
1045 {
1046 overflow = true;
1047 }
1048 catch( ... )
1049 {
1050 }
1051
1052 // Each preflight checks one call.
1053 // Also reset the error callback, so we don't leak the local variables
1054 aPreflightContext->ClearStack();
1055 aPreflightContext->SetErrorCallback( std::move( previousCallback ) );
1056
1057 if( overflow )
1058 return false;
1059 }
1060
1061 node->leaf[0]->isVisited = true;
1062 node->leaf[1]->isVisited = true;
1063 node->leaf[1]->leaf[0]->isVisited = true;
1064 node->leaf[1]->leaf[1]->isVisited = true;
1065
1066 // Our non-terminal-node stacking algorithm can't handle doubly-nested
1067 // structures so we need to pop a level by replacing the TR_STRUCT_REF with
1068 // a TR_OP_FUNC_CALL and its function parameter
1069 stack.pop_back();
1070 stack.push_back( node->leaf[1] );
1071
1072 for( TREE_NODE* pnode : params )
1073 stack.push_back( pnode );
1074
1075 node->leaf[1]->SetUop( TR_OP_METHOD_CALL, std::move( func ), std::move( vref ) );
1076 node->isTerminal = false;
1077 break;
1078 }
1079
1080 default:
1081 // leaf[0]: object
1082 // leaf[1]: malformed syntax
1083
1084 wxString propName = formatNode( node->leaf[1] );
1085 std::unique_ptr<VAR_REF> vref = aCode->CreateVarRef( itemName, propName );
1086
1087 if( !vref )
1088 {
1089 msg.Printf( _( "Unrecognized item '%s'" ), itemName );
1090 reportError( CST_CODEGEN, msg, node->leaf[0]->srcPos - (int) itemName.length() );
1091 }
1092
1093 msg.Printf( _( "Unrecognized property '%s'" ), propName );
1094 reportError( CST_CODEGEN, msg, node->leaf[0]->srcPos + 1 );
1095
1096 node->leaf[0]->isVisited = true;
1097 node->leaf[1]->isVisited = true;
1098
1100 node->isTerminal = true;
1101 break;
1102 }
1103
1104 break;
1105 }
1106
1107 case TR_NUMBER:
1108 {
1109 TREE_NODE* son = node->leaf[0];
1110 double value;
1112
1113 if( !node->value.str )
1114 {
1115 value = 0.0;
1116 }
1117 else if( son && son->op == TR_UNIT )
1118 {
1119 if( m_unitResolver->GetSupportedUnits().empty() )
1120 {
1121 msg.Printf( _( "Unexpected units for '%s'" ), formatNode( node ) );
1122 reportError( CST_CODEGEN, msg, node->srcPos );
1123 }
1124
1125 int units = son->value.idx;
1126 unitsType = m_unitResolver->GetSupportedUnitsTypes().at( units );
1127 value = m_unitResolver->Convert( formatNode( node ), units );
1128 son->isVisited = true;
1129 }
1130 else
1131 {
1132 if( !m_unitResolver->GetSupportedUnitsMessage().empty() )
1133 {
1134 missingUnitsMsg.Printf( _( "Missing units for '%s'| (%s)" ),
1135 formatNode( node ),
1136 m_unitResolver->GetSupportedUnitsMessage() );
1137 missingUnitsSrcPos = node->srcPos;
1138 }
1139
1141 }
1142
1143 node->SetUop( TR_UOP_PUSH_VALUE, value, unitsType );
1144 node->isTerminal = true;
1145 numericValueCount++;
1146 break;
1147 }
1148
1149 case TR_STRING:
1150 {
1151 wxString str = formatNode( node );
1152 bool isWildcard = str.Contains("?") || str.Contains("*");
1153 node->SetUop( TR_UOP_PUSH_VALUE, str, isWildcard );
1154 node->isTerminal = true;
1155 break;
1156 }
1157
1158 case TR_IDENTIFIER:
1159 {
1160 std::unique_ptr<VAR_REF> vref = aCode->CreateVarRef( formatNode( node ), "" );
1161
1162 if( !vref )
1163 {
1164 msg.Printf( _( "Unrecognized item '%s'" ), formatNode( node ) );
1165 reportError( CST_CODEGEN, msg, node->srcPos - (int) formatNode( node ).length() );
1166 }
1167
1168 node->SetUop( TR_UOP_PUSH_VAR, std::move( vref ) );
1169 node->isTerminal = true;
1170 break;
1171 }
1172
1173 default:
1174 node->SetUop( node->op );
1175 node->isTerminal = ( !node->leaf[0] || node->leaf[0]->isVisited )
1176 && ( !node->leaf[1] || node->leaf[1]->isVisited );
1177 break;
1178 }
1179
1180 if( !node->isTerminal )
1181 {
1182 if( node->leaf[0] && !node->leaf[0]->isVisited )
1183 {
1184 stack.push_back( node->leaf[0] );
1185 node->leaf[0]->isVisited = true;
1186 }
1187 else if( node->leaf[1] && !node->leaf[1]->isVisited )
1188 {
1189 // The left operand's microcode is now fully emitted. For && / || insert the
1190 // short-circuit jump here, before the right operand, so the right side can be
1191 // skipped at run time when the left already decides the result.
1192 if( node->op == TR_OP_BOOL_AND || node->op == TR_OP_BOOL_OR )
1193 {
1194 UOP* jump = new UOP( node->op == TR_OP_BOOL_AND ? TR_OP_JZ : TR_OP_JNZ );
1195 aCode->AddOp( jump );
1196 aCode->MarkHasJumps();
1197 scJumps[node] = jump;
1198 }
1199
1200 stack.push_back( node->leaf[1] );
1201 node->leaf[1]->isVisited = true;
1202 }
1203
1204 continue;
1205 }
1206
1207 node->isVisited = true;
1208
1209 if( node->uop )
1210 {
1211 aCode->AddOp( node->uop );
1212 node->uop = nullptr;
1213
1214 // Backpatch the matching short-circuit jump to land just past this combine op.
1215 auto jumpIt = scJumps.find( node );
1216
1217 if( jumpIt != scJumps.end() )
1218 jumpIt->second->SetJumpTarget( aCode->GetSize() );
1219 }
1220
1221 stack.pop_back();
1222 }
1223
1224 // Report the common error condition of a single numeric value with no units (which will result in
1225 // nanometers, and rarely leads to anything useful).
1226 // Reporting missing units with multiple numeric values is far more complicated as we have to
1227 // separate comparison operators from multiplicative operators from additive operators. Consider:
1228 // 2 * 1.5mm
1229 // 2mm + 105um
1230 // 2mm > 20um
1231 // (2mm + 1.5mm) * 3
1232 if( !missingUnitsMsg.IsEmpty() && numericValueCount == 1 )
1233 reportError( CST_CODEGEN, missingUnitsMsg, missingUnitsSrcPos );
1234
1235 libeval_dbg(2,"dump: \n%s\n", aCode->Dump().c_str() );
1236
1237 return true;
1238}
1239
1240
1241// Normalized boolean results pushed when && / || short-circuits, so the skipped combine op's output
1242// contract (an UNSCALED numeric 1/0) is met for any enclosing operator without allocating a fresh
1243// value on the hot path. A numeric VALUE is immutable once set (only deferred values mutate on
1244// read), so DRC's worker threads can share these by reference, just as numeric literals are.
1245static const VALUE g_shortCircuitFalse( 0.0 );
1246static const VALUE g_shortCircuitTrue( 1.0 );
1247
1248
1250{
1251 switch( m_op )
1252 {
1253 case TR_OP_JZ:
1254 // Short-circuit && when the left side is false, then jump past the right-hand microcode.
1255 if( ctx->Top()->AsDouble() == 0.0 )
1256 {
1257 ctx->Pop();
1258 ctx->Push( const_cast<VALUE*>( &g_shortCircuitFalse ) );
1259 return m_jumpTarget;
1260 }
1261
1262 return -1;
1263
1264 case TR_OP_JNZ:
1265 // Short-circuit || when the left side is true, then jump past the right-hand microcode.
1266 if( ctx->Top()->AsDouble() != 0.0 )
1267 {
1268 ctx->Pop();
1269 ctx->Push( const_cast<VALUE*>( &g_shortCircuitTrue ) );
1270 return m_jumpTarget;
1271 }
1272
1273 return -1;
1274
1275 case TR_UOP_PUSH_VAR:
1276 {
1277 VALUE* value = nullptr;
1278
1279 if( m_ref )
1280 value = ctx->StoreValue( m_ref->GetValue( ctx ) );
1281 else
1282 value = ctx->AllocValue();
1283
1284 ctx->Push( value );
1285 break;
1286 }
1287
1288 case TR_UOP_PUSH_VALUE:
1289 // String literals contain a wxString whose internal mb_str cache is mutated by
1290 // ToUTF8/utf8_str. DRC evaluates compiled rules from many threads concurrently,
1291 // so push a per-thread copy to avoid racing on that cache.
1292 if( m_value && m_value->GetType() == VT_STRING )
1293 {
1294 VALUE* copy = ctx->AllocValue();
1295 copy->Set( *m_value );
1296 ctx->Push( copy );
1297 }
1298 else
1299 {
1300 ctx->Push( m_value.get() );
1301 }
1302
1303 return -1;
1304
1305 case TR_OP_METHOD_CALL:
1306 if( m_func )
1307 m_func( ctx, m_ref.get() );
1308
1309 return -1;
1310
1311 default:
1312 break;
1313 }
1314
1315#define AS_DOUBLE( arg ) ( arg ? arg->AsDouble() : 0.0 )
1316
1317 if( m_op & TR_OP_BINARY_MASK )
1318 {
1319 LIBEVAL::VALUE autoConverted;
1320 LIBEVAL::VALUE* arg2 = ctx->Pop();
1321 LIBEVAL::VALUE* arg1 = ctx->Pop();
1322 double result;
1323
1324 if( arg1 && arg1->GetType() == VT_STRING && arg2 && arg2->GetType() == VT_NUMERIC )
1325 {
1326 double doubleVal;
1327
1328 if( !arg1->StringIsLiteral() && QuacksLikeADuck( arg1->AsString(), &doubleVal ) )
1329 {
1330 autoConverted = LIBEVAL::VALUE( doubleVal );
1331 arg1 = &autoConverted;
1332 }
1333 else if( ctx->HasErrorCallback() )
1334 {
1335 ctx->ReportError( wxString::Format( _( "Type mismatch between '%s' and %lf" ),
1336 arg1->AsString(),
1337 arg2->AsDouble() ) );
1338 }
1339 }
1340 else if( arg1 && arg1->GetType() == VT_NUMERIC && arg2 && arg2->GetType() == VT_STRING )
1341 {
1342 double doubleVal;
1343
1344 if( !arg2->StringIsLiteral() && QuacksLikeADuck( arg2->AsString(), &doubleVal ) )
1345 {
1346 autoConverted = LIBEVAL::VALUE( doubleVal );
1347 arg2 = &autoConverted;
1348 }
1349 else if( ctx->HasErrorCallback() )
1350 {
1351 ctx->ReportError( wxString::Format( _( "Type mismatch between %lf and '%s'" ),
1352 arg1->AsDouble(),
1353 arg2->AsString() ) );
1354 }
1355 }
1356
1357 // TODO: This doesn't fully calculate units correctly yet. We really need to work out the dimensional analysis
1358 // TODO: (and do this independently of unit specifics - e.g. MM + INCH needs to return one of the dimension
1359 // TODO: types, but our units framework doesn't currently allow this. Therefore, use some heuristics to
1360 // TODO: determine the resulting operation unit type for now
1361 auto getOpResultUnits =
1362 []( const VALUE* aVal1, const VALUE* aVal2 )
1363 {
1364 wxCHECK( aVal1 && aVal2, EDA_UNITS::UNSCALED );
1365
1366 // This condition can occur in, e.g., a unary negation operation
1367 if( aVal1->GetUnits() == EDA_UNITS::UNSCALED && aVal2->GetUnits() != EDA_UNITS::UNSCALED )
1368 return aVal2->GetUnits();
1369
1370 if( aVal1->GetUnits() != EDA_UNITS::UNSCALED && aVal2->GetUnits() == EDA_UNITS::UNSCALED )
1371 return aVal1->GetUnits();
1372
1373 return aVal2->GetUnits();
1374 };
1375
1376 EDA_UNITS resultUnits = EDA_UNITS::UNSCALED;
1377
1378 switch( m_op )
1379 {
1380 case TR_OP_ADD:
1381 result = AS_DOUBLE( arg1 ) + AS_DOUBLE( arg2 );
1382 resultUnits = getOpResultUnits( arg1, arg2 );
1383 break;
1384
1385 case TR_OP_SUB:
1386 result = AS_DOUBLE( arg1 ) - AS_DOUBLE( arg2 );
1387 resultUnits = getOpResultUnits( arg1, arg2 );
1388 break;
1389
1390 case TR_OP_MUL:
1391 result = AS_DOUBLE( arg1 ) * AS_DOUBLE( arg2 );
1392 resultUnits = getOpResultUnits( arg1, arg2 );
1393 break;
1394
1395 case TR_OP_DIV:
1396 result = AS_DOUBLE( arg1 ) / AS_DOUBLE( arg2 );
1397 resultUnits = getOpResultUnits( arg1, arg2 );
1398 break;
1399
1400 case TR_OP_LESS_EQUAL:
1401 result = AS_DOUBLE( arg1 ) <= AS_DOUBLE( arg2 ) ? 1 : 0;
1402 break;
1403
1405 result = AS_DOUBLE( arg1 ) >= AS_DOUBLE( arg2 ) ? 1 : 0;
1406 break;
1407
1408 case TR_OP_LESS:
1409 result = AS_DOUBLE( arg1 ) < AS_DOUBLE( arg2 ) ? 1 : 0;
1410 break;
1411 case TR_OP_GREATER:
1412 result = AS_DOUBLE( arg1 ) > AS_DOUBLE( arg2 ) ? 1 : 0;
1413 break;
1414
1415 case TR_OP_EQUAL:
1416 if( !arg1 || !arg2 )
1417 result = arg1 == arg2 ? 1 : 0;
1418 else if( arg2->GetType() == VT_UNDEFINED )
1419 result = arg2->EqualTo( ctx, arg1 ) ? 1 : 0;
1420 else
1421 result = arg1->EqualTo( ctx, arg2 ) ? 1 : 0;
1422 break;
1423
1424 case TR_OP_NOT_EQUAL:
1425 if( !arg1 || !arg2 )
1426 result = arg1 != arg2 ? 1 : 0;
1427 else if( arg2->GetType() == VT_UNDEFINED )
1428 result = arg2->NotEqualTo( ctx, arg1 ) ? 1 : 0;
1429 else
1430 result = arg1->NotEqualTo( ctx, arg2 ) ? 1 : 0;
1431 break;
1432
1433 case TR_OP_BOOL_AND:
1434 result = AS_DOUBLE( arg1 ) != 0.0 && AS_DOUBLE( arg2 ) != 0.0 ? 1 : 0;
1435 break;
1436
1437 case TR_OP_BOOL_OR:
1438 result = AS_DOUBLE( arg1 ) != 0.0 || AS_DOUBLE( arg2 ) != 0.0 ? 1 : 0;
1439 break;
1440
1441 default:
1442 result = 0.0;
1443 break;
1444 }
1445
1446 VALUE* rp = ctx->AllocValue();
1447 rp->Set( result );
1448 rp->SetUnits( resultUnits );
1449 ctx->Push( rp );
1450 return -1;
1451 }
1452 else if( m_op & TR_OP_UNARY_MASK )
1453 {
1454 LIBEVAL::VALUE* arg1 = ctx->Pop();
1455 double ARG1VALUE = arg1 ? arg1->AsDouble() : 0.0;
1456 double result;
1457 EDA_UNITS resultUnits = arg1 ? arg1->GetUnits() : EDA_UNITS::UNSCALED;
1458
1459 switch( m_op )
1460 {
1461 case TR_OP_BOOL_NOT:
1462 result = ARG1VALUE != 0.0 ? 0 : 1;
1463 break;
1464 default:
1465 result = ARG1VALUE != 0.0 ? 1 : 0;
1466 break;
1467 }
1468
1469 VALUE* rp = ctx->AllocValue();
1470 rp->Set( result );
1471 rp->SetUnits( resultUnits );
1472 ctx->Push( rp );
1473 return -1;
1474 }
1475
1476 return -1;
1477}
1478
1479
1481{
1482 try
1483 {
1484 if( m_hasJumps )
1485 {
1486 for( std::size_t ip = 0; ip < m_ucode.size(); )
1487 {
1488 int next = m_ucode[ip]->Exec( ctx );
1489
1490 // Backpatched jump targets are always forward, past the combine op; a non-forward
1491 // or stale target would spin or read out of range, so reject it.
1492 wxASSERT( next < 0 || static_cast<std::size_t>( next ) > ip );
1493
1495 }
1496 }
1497 else
1498 {
1499 for( UOP* op : m_ucode )
1500 op->Exec( ctx );
1501 }
1502 }
1503 catch( ... )
1504 {
1505 ctx->ClearStack();
1506 // rules which fail outright should not be fired; return 0/false
1507 return ctx->StoreValue( new VALUE( 0 ) );
1508 }
1509
1510 if( ctx->SP() == 1 )
1511 {
1512 return ctx->Pop();
1513 }
1514
1515 // Extra function arguments can leave values on the stack even without an overflow.
1516 ctx->ClearStack();
1517 ctx->ReportError( _( "Malformed expression" ) );
1518 return ctx->StoreValue( new VALUE( 0 ) );
1519}
1520
1521
1522std::optional<wxString> EscapeStringLiteral( const wxString& aText )
1523{
1524 if( aText.EndsWith( wxS( "\\" ) ) )
1525 return std::nullopt;
1526
1527 wxString escaped = aText;
1528 escaped.Replace( wxS( "'" ), wxS( "\\'" ) );
1529 return escaped;
1530}
1531
1532
1533} // namespace LIBEVAL
std::unique_ptr< UNIT_RESOLVER > m_unitResolver
void newString(const wxString &aString)
void freeTree(LIBEVAL::TREE_NODE *tree)
bool lexString(T_TOKEN &aToken)
void GcItem(TREE_NODE *aItem)
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)
void setRoot(LIBEVAL::TREE_NODE *root)
std::vector< wxString * > m_gcStrings
bool Compile(const wxString &aString, UCODE *aCode, CONTEXT *aPreflightContext)
ERROR_STATUS m_errorStatus
void parseError(const char *s)
void Push(VALUE *aValue)
VALUE * StoreValue(VALUE *aValue)
void ReportError(const wxString &aErrorMsg)
ERROR_CALLBACK ExchangeErrorCallback(ERROR_CALLBACK aCallback)
Install a callback and return the previous one.
void SetErrorCallback(ERROR_CALLBACK aCallback)
ERROR_CALLBACK m_errorCallback
void ClearStack()
Discard operands while retaining allocated values and context settings.
VALUE * Top()
Peek the top of the stack without popping (used by the short-circuit jumps).
static constexpr int STACK_CAPACITY
wxString GetChars(const std::function< bool(wxUniChar)> &cond) const
bool MatchAhead(const wxString &match, const std::function< bool(wxUniChar)> &stopCond) 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)
std::vector< UOP * > m_ucode
wxString Dump() const
void MarkHasJumps()
Flag that this ucode contains short-circuit jumps, so Run() uses the jump-aware loop.
int GetSize() const
Index of the next op to be added (used to backpatch short-circuit jump targets).
VALUE * Run(CONTEXT *ctx)
virtual FUNC_CALL_REF CreateFuncCall(const wxString &name)
std::unique_ptr< VAR_REF > m_ref
FUNC_CALL_REF m_func
wxString Format() const
int Exec(CONTEXT *ctx)
Execute the op.
std::unique_ptr< VALUE > m_value
void Set(double aValue)
virtual const wxString & AsString() const
void SetUnits(const EDA_UNITS aUnits)
virtual bool NotEqualTo(CONTEXT *aCtx, const VALUE *b) const
virtual double AsDouble() const
EDA_UNITS GetUnits() const
VAR_TYPE_T GetType() const
bool StringIsLiteral() const
virtual bool EqualTo(CONTEXT *aCtx, const VALUE *b) const
static bool IsOldSchoolDecimalSeparator(wxUniChar ch, double *siScaler)
#define _(s)
EDA_UNITS
Definition eda_units.h:45
unitsType
#define libeval_dbg(level, fmt,...)
#define AS_DOUBLE(arg)
#define TR_OP_GREATER_EQUAL
#define TR_OP_BOOL_AND
#define TR_OP_MUL
#define TR_UOP_PUSH_VAR
#define TR_UOP_PUSH_VALUE
#define TR_OP_BOOL_OR
#define TR_OP_GREATER
#define TR_OP_EQUAL
#define TR_OP_JZ
#define TR_OP_ADD
#define TR_OP_FUNC_CALL
#define TR_OP_SUB
#define TR_OP_METHOD_CALL
#define TR_OP_UNARY_MASK
#define TR_OP_LESS_EQUAL
#define TR_OP_BINARY_MASK
#define TR_OP_LESS
#define TR_OP_DIV
#define TR_OP_JNZ
#define TR_OP_NOT_EQUAL
#define TR_OP_BOOL_NOT
KICOMMON_API double DoubleValueFromString(const EDA_IU_SCALE &aIuScale, EDA_UNITS aUnits, const wxString &aTextValue, EDA_DATA_TYPE aType=EDA_DATA_TYPE::DISTANCE)
Convert aTextValue to a double.
TREE_NODE * newNode(LIBEVAL::COMPILER *compiler, int op, const T_TOKEN_VALUE &value)
static bool flattenVarChain(TREE_NODE *aNode, wxString &aResult)
static std::vector< TREE_NODE * > squashParamList(TREE_NODE *root)
constexpr T_TOKEN defaultToken
void dumpNode(wxString &buf, TREE_NODE *tok, int depth=0)
static const VALUE g_shortCircuitFalse(0.0)
constexpr T_TOKEN_VALUE defaultTokenValue
std::function< void(CONTEXT *, void *)> FUNC_CALL_REF
static const wxString formatOpName(int op)
std::optional< wxString > EscapeStringLiteral(const wxString &aText)
Escape text for use between the quotes of an expression string.
static const VALUE g_shortCircuitTrue(1.0)
const wxString formatNode(TREE_NODE *node)
static void prepareTree(LIBEVAL::TREE_NODE *node)
CITER next(CITER it)
Definition ptree.cpp:120
std::vector< FAB_LAYER_COLOR > dummy
bool WildCompareString(const wxString &pattern, const wxString &string_to_tst, bool case_sensitive)
Compare a string against wild card (* and ?) pattern using the usual rules.
bool QuacksLikeADuck(const wxString &aStr, double *aValue)
T_TOKEN_VALUE value
@ VALUE
Field Value of part, i.e. "3.3K".
wxString result
Test unit parsing edge cases and error handling.
wxString dump(const wxArrayString &aArray)
Debug helper for printing wxArrayString contents.