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 (C) 2019-2023 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
35
36/* The (generated) lemon parser is written in C.
37 * In order to keep its symbol from the global namespace include the parser code with
38 * a C++ namespace.
39 */
40namespace LIBEVAL
41{
42
43#ifdef __GNUC__
44#pragma GCC diagnostic push
45#pragma GCC diagnostic ignored "-Wunused-variable"
46#pragma GCC diagnostic ignored "-Wsign-compare"
47#endif
48
49#include <libeval_compiler/grammar.c>
50#include <libeval_compiler/grammar.h>
51
52#ifdef __GNUC__
53#pragma GCC diagnostic pop
54#endif
55
56
57#define libeval_dbg(level, fmt, ...) \
58 wxLogTrace( "libeval_compiler", fmt, __VA_ARGS__ );
59
60
61TREE_NODE* newNode( LIBEVAL::COMPILER* compiler, int op, const T_TOKEN_VALUE& value )
62{
63 auto t2 = new TREE_NODE();
64
65 t2->valid = true;
66 t2->value.str = value.str ? new wxString( *value.str ) : nullptr;
67 t2->value.num = value.num;
68 t2->value.idx = value.idx;
69 t2->op = op;
70 t2->leaf[0] = nullptr;
71 t2->leaf[1] = nullptr;
72 t2->isTerminal = false;
73 t2->srcPos = compiler->GetSourcePos();
74 t2->uop = nullptr;
75
76 libeval_dbg(10, " ostr %p nstr %p nnode %p op %d", value.str, t2->value.str, t2, t2->op );
77
78 if(t2->value.str)
79 compiler->GcItem( t2->value.str );
80
81 compiler->GcItem( t2 );
82
83 return t2;
84}
85
86
87static const wxString formatOpName( int op )
88{
89 static const struct
90 {
91 int op;
92 wxString mnemonic;
93 }
94 simpleOps[] =
95 {
96 { TR_OP_MUL, "MUL" }, { TR_OP_DIV, "DIV" }, { TR_OP_ADD, "ADD" },
97 { TR_OP_SUB, "SUB" }, { TR_OP_LESS, "LESS" }, { TR_OP_GREATER, "GREATER" },
98 { TR_OP_LESS_EQUAL, "LESS_EQUAL" }, { TR_OP_GREATER_EQUAL, "GREATER_EQUAL" },
99 { TR_OP_EQUAL, "EQUAL" }, { TR_OP_NOT_EQUAL, "NEQUAL" }, { TR_OP_BOOL_AND, "AND" },
100 { TR_OP_BOOL_OR, "OR" }, { TR_OP_BOOL_NOT, "NOT" }, { -1, "" }
101 };
102
103 for( int i = 0; simpleOps[i].op >= 0; i++ )
104 {
105 if( simpleOps[i].op == op )
106 return simpleOps[i].mnemonic;
107 }
108
109 return "???";
110}
111
112
113bool VALUE::EqualTo( CONTEXT* aCtx, const VALUE* b ) const
114{
115 if( m_type == VT_UNDEFINED || b->m_type == VT_UNDEFINED )
116 return false;
117
118 if( m_type == VT_NUMERIC && b->m_type == VT_NUMERIC )
119 {
120 return AsDouble() == b->AsDouble();
121 }
122 else if( m_type == VT_STRING && b->m_type == VT_STRING )
123 {
124 if( b->m_stringIsWildcard )
125 return WildCompareString( b->AsString(), AsString(), false );
126 else
127 return AsString().IsSameAs( b->AsString(), false );
128 }
129
130 return false;
131}
132
133
134bool VALUE::NotEqualTo( CONTEXT* aCtx, const VALUE* b ) const
135{
136 if( m_type == VT_UNDEFINED || b->m_type == VT_UNDEFINED )
137 return false;
138
139 return !EqualTo( aCtx, b );
140}
141
142
143wxString UOP::Format() const
144{
145 wxString str;
146
147 switch( m_op )
148 {
149 case TR_UOP_PUSH_VAR:
150 str = wxString::Format( "PUSH VAR [%p]", m_ref.get() );
151 break;
152
154 {
155 if( !m_value )
156 str = wxString::Format( "PUSH nullptr" );
157 else if( m_value->GetType() == VT_NUMERIC )
158 str = wxString::Format( "PUSH NUM [%.10f]", m_value->AsDouble() );
159 else
160 str = wxString::Format( "PUSH STR [%ls]", m_value->AsString() );
161 }
162 break;
163
165 str = wxString::Format( "MCALL" );
166 break;
167
168 case TR_OP_FUNC_CALL:
169 str = wxString::Format( "FCALL" );
170 break;
171
172 default:
173 str = wxString::Format( "%s %d", formatOpName( m_op ).c_str(), m_op );
174 break;
175 }
176
177 return str;
178}
179
180
182{
183 for ( auto op : m_ucode )
184 {
185 delete op;
186 }
187}
188
189
190wxString UCODE::Dump() const
191{
192 wxString rv;
193
194 for( auto op : m_ucode )
195 {
196 rv += op->Format();
197 rv += "\n";
198 }
199
200 return rv;
201};
202
203
204wxString TOKENIZER::GetChars( const std::function<bool( wxUniChar )>& cond ) const
205{
206 wxString rv;
207 size_t p = m_pos;
208
209 while( p < m_str.length() && cond( m_str[p] ) )
210 {
211 rv.append( 1, m_str[p] );
212 p++;
213 }
214
215 return rv;
216}
217
218bool TOKENIZER::MatchAhead( const wxString& match,
219 const std::function<bool( wxUniChar )>& stopCond ) const
220{
221 int remaining = (int) m_str.Length() - m_pos;
222
223 if( remaining < (int) match.length() )
224 return false;
225
226 if( m_str.substr( m_pos, match.length() ) == match )
227 return ( remaining == (int) match.length() || stopCond( m_str[m_pos + match.length()] ) );
228
229 return false;
230}
231
232
234 m_lexerState( COMPILER::LS_DEFAULT )
235{
237 m_sourcePos = 0;
238 m_parseFinished = false;
239 m_unitResolver = std::make_unique<UNIT_RESOLVER>();
240 m_parser = LIBEVAL::ParseAlloc( malloc );
241 m_tree = nullptr;
243}
244
245
247{
248 LIBEVAL::ParseFree( m_parser, free );
249
250 if( m_tree )
251 {
252 freeTree( m_tree );
253 m_tree = nullptr;
254 }
255
256 // Allow explicit call to destructor
257 m_parser = nullptr;
258
259 Clear();
260}
261
262
264{
265 //free( current.token );
267
268 if( m_tree )
269 {
270 freeTree( m_tree );
271 m_tree = nullptr;
272 }
273
274 m_tree = nullptr;
275
276 for( auto tok : m_gcItems )
277 delete tok;
278
279 for( auto tok: m_gcStrings )
280 delete tok;
281
282 m_gcItems.clear();
283 m_gcStrings.clear();
284}
285
286
287void COMPILER::parseError( const char* s )
288{
290}
291
292
294{
295 m_parseFinished = true;
296}
297
298
299bool COMPILER::Compile( const wxString& aString, UCODE* aCode, CONTEXT* aPreflightContext )
300{
301 // Feed parser token after token until end of input.
302
303 newString( aString );
304
305 if( m_tree )
306 {
307 freeTree( m_tree );
308 m_tree = nullptr;
309 }
310
311 m_tree = nullptr;
312 m_parseFinished = false;
313 T_TOKEN tok( defaultToken );
314
315 libeval_dbg(0, "str: '%s' empty: %d\n", aString.c_str(), !!aString.empty() );
316
317 if( aString.empty() )
318 {
319 m_parseFinished = true;
320 return generateUCode( aCode, aPreflightContext );
321 }
322
323 do
324 {
326
327 tok = getToken();
328
329 if( tok.value.str )
330 GcItem( tok.value.str );
331
332 libeval_dbg(10, "parse: tok %d valstr %p\n", tok.token, tok.value.str );
333 Parse( m_parser, tok.token, tok, this );
334
336 return false;
337
338 if( m_parseFinished || tok.token == G_ENDS )
339 {
340 // Reset parser by passing zero as token ID, value is ignored.
341 Parse( m_parser, 0, tok, this );
342 break;
343 }
344 } while( tok.token );
345
346 return generateUCode( aCode, aPreflightContext );
347}
348
349
350void COMPILER::newString( const wxString& aString )
351{
352 Clear();
353
355 m_tokenizer.Restart( aString );
356 m_parseFinished = false;
357}
358
359
361{
362 T_TOKEN rv;
364
365 bool done = false;
366
367 do
368 {
369 switch( m_lexerState )
370 {
371 case LS_DEFAULT:
372 done = lexDefault( rv );
373 break;
374 case LS_STRING:
375 done = lexString( rv );
376 break;
377 }
378 } while( !done );
379
380 return rv;
381}
382
383
385{
386 wxString str = m_tokenizer.GetChars( []( int c ) -> bool { return c != '\''; } );
387
388 aToken.token = G_STRING;
389 aToken.value.str = new wxString( str );
390
391 m_tokenizer.NextChar( str.length() + 1 );
393 return true;
394}
395
396
398{
399 int unitId = 0;
400
401 for( const wxString& unitName : m_unitResolver->GetSupportedUnits() )
402 {
403 if( m_tokenizer.MatchAhead( unitName, []( int c ) -> bool { return !isalnum( c ); } ) )
404 {
405 libeval_dbg(10, "Match unit '%s'\n", unitName.c_str() );
406 m_tokenizer.NextChar( unitName.length() );
407 return unitId;
408 }
409
410 unitId++;
411 }
412
413 return -1;
414}
415
416
418{
419 T_TOKEN retval;
420 wxString current;
421 int convertFrom;
422 wxString msg;
423
424 retval.value.str = nullptr;
425 retval.value.num = 0.0;
426 retval.value.idx = -1;
427 retval.token = G_ENDS;
428
429 if( m_tokenizer.Done() )
430 {
431 aToken = retval;
432 return true;
433 }
434
435 auto isDecimalSeparator =
436 [&]( wxUniChar ch ) -> bool
437 {
438 return ( ch == m_localeDecimalSeparator || ch == '.' || ch == ',' );
439 };
440
441 // Lambda: get value as string, store into clToken.token and update current index.
442 auto extractNumber =
443 [&]()
444 {
445 bool haveSeparator = false;
446 wxUniChar ch = m_tokenizer.GetChar();
447
448 do
449 {
450 if( isDecimalSeparator( ch ) && haveSeparator )
451 break;
452
453 current.append( 1, ch );
454
455 if( isDecimalSeparator( ch ) )
456 haveSeparator = true;
457
459 ch = m_tokenizer.GetChar();
460 } while( isdigit( ch ) || isDecimalSeparator( ch ) );
461
462 // Ensure that the systems decimal separator is used
463 for( int i = current.length(); i; i-- )
464 {
465 if( isDecimalSeparator( current[i - 1] ) )
466 current[i - 1] = m_localeDecimalSeparator;
467 }
468 };
469
470
471 int ch;
472
473 // Start processing of first/next token: Remove whitespace
474 for( ;; )
475 {
476 ch = m_tokenizer.GetChar();
477
478 if( ch == ' ' )
480 else
481 break;
482 }
483
484 libeval_dbg(10, "LEX ch '%c' pos %lu\n", ch, (unsigned long)m_tokenizer.GetPos() );
485
486 if( ch == 0 )
487 {
488 /* End of input */
489 }
490 else if( isdigit( ch ) )
491 {
492 // VALUE
493 extractNumber();
494 retval.token = G_VALUE;
495 retval.value.str = new wxString( current );
496 }
497 else if( ( convertFrom = resolveUnits() ) >= 0 )
498 {
499 // UNIT
500 // Units are appended to a VALUE.
501 // Determine factor to default unit if unit for value is given.
502 // Example: Default is mm, unit is inch: factor is 25.4
503 // The factor is assigned to the terminal UNIT. The actual
504 // conversion is done within a parser action.
505 retval.token = G_UNIT;
506 retval.value.idx = convertFrom;
507 }
508 else if( ch == '\'' ) // string literal
509 {
512 return false;
513 }
514 else if( isalpha( ch ) || ch == '_' )
515 {
516 current = m_tokenizer.GetChars( []( int c ) -> bool { return isalnum( c ) || c == '_'; } );
517 retval.token = G_IDENTIFIER;
518 retval.value.str = new wxString( current );
519 m_tokenizer.NextChar( current.length() );
520 }
521 else if( m_tokenizer.MatchAhead( "==", []( int c ) -> bool { return c != '='; } ) )
522 {
523 retval.token = G_EQUAL;
525 }
526 else if( m_tokenizer.MatchAhead( "!=", []( int c ) -> bool { return c != '='; } ) )
527 {
528 retval.token = G_NOT_EQUAL;
530 }
531 else if( m_tokenizer.MatchAhead( "<=", []( int c ) -> bool { return c != '='; } ) )
532 {
533 retval.token = G_LESS_EQUAL_THAN;
535 }
536 else if( m_tokenizer.MatchAhead( ">=", []( int c ) -> bool { return c != '='; } ) )
537 {
538 retval.token = G_GREATER_EQUAL_THAN;
540 }
541 else if( m_tokenizer.MatchAhead( "&&", []( int c ) -> bool { return c != '&'; } ) )
542 {
543 retval.token = G_BOOL_AND;
545 }
546 else if( m_tokenizer.MatchAhead( "||", []( int c ) -> bool { return c != '|'; } ) )
547 {
548 retval.token = G_BOOL_OR;
550 }
551 else
552 {
553 // Single char tokens
554 switch( ch )
555 {
556 case '+': retval.token = G_PLUS; break;
557 case '!': retval.token = G_BOOL_NOT; break;
558 case '-': retval.token = G_MINUS; break;
559 case '*': retval.token = G_MULT; break;
560 case '/': retval.token = G_DIVIDE; break;
561 case '<': retval.token = G_LESS_THAN; break;
562 case '>': retval.token = G_GREATER_THAN; break;
563 case '(': retval.token = G_PARENL; break;
564 case ')': retval.token = G_PARENR; break;
565 case ';': retval.token = G_SEMCOL; break;
566 case '.': retval.token = G_STRUCT_REF; break;
567 case ',': retval.token = G_COMMA; break;
568
569 default:
570 reportError( CST_PARSE, wxString::Format( _( "Unrecognized character '%c'" ),
571 (char) ch ) );
572 break;
573 }
574
576 }
577
578 aToken = retval;
579 return true;
580}
581
582
583const wxString formatNode( TREE_NODE* node )
584{
585 return node->value.str ? *(node->value.str) : wxString( wxEmptyString );
586}
587
588
589void dumpNode( wxString& buf, TREE_NODE* tok, int depth = 0 )
590{
591 wxString str;
592
593 if( !tok )
594 return;
595
596 str.Printf( "\n[%p L0:%-20p L1:%-20p] ", tok, tok->leaf[0], tok->leaf[1] );
597 buf += str;
598
599 for( int i = 0; i < 2 * depth; i++ )
600 buf += " ";
601
602 if( tok->op & TR_OP_BINARY_MASK )
603 {
604 buf += formatOpName( tok->op );
605 dumpNode( buf, tok->leaf[0], depth + 1 );
606 dumpNode( buf, tok->leaf[1], depth + 1 );
607 }
608
609 switch( tok->op )
610 {
611 case TR_NUMBER:
612 buf += "NUMERIC: ";
613 buf += formatNode( tok );
614
615 if( tok->leaf[0] )
616 dumpNode( buf, tok->leaf[0], depth + 1 );
617
618 break;
619
620 case TR_ARG_LIST:
621 buf += "ARG_LIST: ";
622 buf += formatNode( tok );
623
624 if( tok->leaf[0] )
625 dumpNode( buf, tok->leaf[0], depth + 1 );
626 if( tok->leaf[1] )
627 dumpNode( buf, tok->leaf[1], depth + 1 );
628
629 break;
630
631 case TR_STRING:
632 buf += "STRING: ";
633 buf += formatNode( tok );
634 break;
635
636 case TR_IDENTIFIER:
637 buf += "ID: ";
638 buf += formatNode( tok );
639 break;
640
641 case TR_STRUCT_REF:
642 buf += "SREF: ";
643 dumpNode( buf, tok->leaf[0], depth + 1 );
644 dumpNode( buf, tok->leaf[1], depth + 1 );
645 break;
646
647 case TR_OP_FUNC_CALL:
648 buf += "CALL '";
649 buf += *tok->leaf[0]->value.str;
650 buf += "': ";
651 dumpNode( buf, tok->leaf[1], depth + 1 );
652 break;
653
654 case TR_UNIT:
655 str.Printf( "UNIT: %d ", tok->value.idx );
656 buf += str;
657 break;
658 }
659}
660
661
662void CONTEXT::ReportError( const wxString& aErrorMsg )
663{
664 if( m_errorCallback )
665 m_errorCallback( aErrorMsg, -1 );
666}
667
668
669void COMPILER::reportError( COMPILATION_STAGE stage, const wxString& aErrorMsg, int aPos )
670{
671 if( aPos == -1 )
672 aPos = m_sourcePos;
673
675 m_errorStatus.stage = stage;
676 m_errorStatus.message = aErrorMsg;
677 m_errorStatus.srcPos = aPos;
678
679 if( m_errorCallback )
680 m_errorCallback( aErrorMsg, aPos );
681}
682
683
685{
686 m_tree = root;
687}
688
689
691{
692 if ( tree->leaf[0] )
693 freeTree( tree->leaf[0] );
694
695 if ( tree->leaf[1] )
696 freeTree( tree->leaf[1] );
697
698 delete tree->uop;
699 tree->uop = nullptr;
700}
701
702
703void TREE_NODE::SetUop( int aOp, double aValue )
704{
705 delete uop;
706
707 std::unique_ptr<VALUE> val = std::make_unique<VALUE>( aValue );
708 uop = new UOP( aOp, std::move( val ) );
709}
710
711
712void TREE_NODE::SetUop( int aOp, const wxString& aValue, bool aStringIsWildcard )
713{
714 delete uop;
715
716 std::unique_ptr<VALUE> val = std::make_unique<VALUE>( aValue, aStringIsWildcard );
717 uop = new UOP( aOp, std::move( val ) );
718}
719
720
721void TREE_NODE::SetUop( int aOp, std::unique_ptr<VAR_REF> aRef )
722{
723 delete uop;
724
725 uop = new UOP( aOp, std::move( aRef ) );
726}
727
728
729void TREE_NODE::SetUop( int aOp, FUNC_CALL_REF aFunc, std::unique_ptr<VAR_REF> aRef )
730{
731 delete uop;
732
733 uop = new UOP( aOp, std::move( aFunc ), std::move( aRef ) );
734}
735
736
737static void prepareTree( LIBEVAL::TREE_NODE *node )
738{
739 node->isVisited = false;
740
741 // fixme: for reasons I don't understand the lemon parser isn't initializing the
742 // leaf node pointers of function name nodes. -JY
743 if( node->op == TR_OP_FUNC_CALL && node->leaf[0] )
744 {
745 node->leaf[0]->leaf[0] = nullptr;
746 node->leaf[0]->leaf[1] = nullptr;
747 }
748
749 if ( node->leaf[0] )
750 prepareTree( node->leaf[0] );
751
752 if ( node->leaf[1] )
753 prepareTree( node->leaf[1] );
754}
755
756static std::vector<TREE_NODE*> squashParamList( TREE_NODE* root )
757{
758 std::vector<TREE_NODE*> args;
759
760 if( !root )
761 {
762 return args;
763 }
764
765 if( root->op != TR_ARG_LIST && root->op != TR_NULL )
766 {
767 args.push_back( root );
768 }
769 else
770 {
771 TREE_NODE *n = root;
772 do
773 {
774 if( n->leaf[1] )
775 args.push_back(n->leaf[1]);
776
777 n = n->leaf[0];
778 } while ( n && n->op == TR_ARG_LIST );
779
780 if( n )
781 {
782 args.push_back( n );
783 }
784 }
785
786 std::reverse( args.begin(), args.end() );
787
788 for( size_t i = 0; i < args.size(); i++ )
789 libeval_dbg( 10, "squash arg%d: %s\n", int( i ), *args[i]->value.str );
790
791 return args;
792}
793
794
795bool COMPILER::generateUCode( UCODE* aCode, CONTEXT* aPreflightContext )
796{
797 std::vector<TREE_NODE*> stack;
798 wxString msg;
799
800 if( !m_tree )
801 {
802 std::unique_ptr<VALUE> val = std::make_unique<VALUE>( 1.0 );
803 // Empty expression returns true
804 aCode->AddOp( new UOP( TR_UOP_PUSH_VALUE, std::move(val) ) );
805 return true;
806 }
807
809
810 stack.push_back( m_tree );
811
812 wxString dump;
813
814 dumpNode( dump, m_tree, 0 );
815 libeval_dbg( 3, "Tree dump:\n%s\n\n", (const char*) dump.c_str() );
816
817 while( !stack.empty() )
818 {
819 TREE_NODE* node = stack.back();
820
821 libeval_dbg( 4, "process node %p [op %d] [stack %lu]\n",
822 node, node->op, (unsigned long)stack.size() );
823
824 // process terminal nodes first
825 switch( node->op )
826 {
827 case TR_OP_FUNC_CALL:
828 // Function call's uop was generated inside TR_STRUCT_REF
829 if( !node->uop )
830 {
831 reportError( CST_CODEGEN, _( "Unknown parent of function parameters" ),
832 node->srcPos );
833 }
834
835 node->isTerminal = true;
836 break;
837
838 case TR_STRUCT_REF:
839 {
840 // leaf[0]: object
841 // leaf[1]: field (TR_IDENTIFIER) or TR_OP_FUNC_CALL
842
843 if( node->leaf[0]->op != TR_IDENTIFIER )
844 {
845 int pos = node->leaf[0]->srcPos;
846
847 if( node->leaf[0]->value.str )
848 pos -= static_cast<int>( node->leaf[0]->value.str->length() );
849
850 reportError( CST_CODEGEN, _( "Unknown parent of property" ), pos );
851
852 node->leaf[0]->isVisited = true;
853 node->leaf[1]->isVisited = true;
854
855 node->SetUop( TR_UOP_PUSH_VALUE, 0.0 );
856 node->isTerminal = true;
857 break;
858 }
859
860 switch( node->leaf[1]->op )
861 {
862 case TR_IDENTIFIER:
863 {
864 // leaf[0]: object
865 // leaf[1]: field
866
867 wxString itemName = *node->leaf[0]->value.str;
868 wxString propName = *node->leaf[1]->value.str;
869 std::unique_ptr<VAR_REF> vref = aCode->CreateVarRef( itemName, propName );
870
871 if( !vref )
872 {
873 msg.Printf( _( "Unrecognized item '%s'" ), itemName );
875 node->leaf[0]->srcPos - (int) itemName.length() );
876 }
877 else if( vref->GetType() == VT_PARSE_ERROR )
878 {
879 msg.Printf( _( "Unrecognized property '%s'" ), propName );
881 node->leaf[1]->srcPos - (int) propName.length() );
882 }
883
884 node->leaf[0]->isVisited = true;
885 node->leaf[1]->isVisited = true;
886
887 node->SetUop( TR_UOP_PUSH_VAR, std::move( vref ) );
888 node->isTerminal = true;
889 break;
890 }
891 case TR_OP_FUNC_CALL:
892 {
893 // leaf[0]: object
894 // leaf[1]: TR_OP_FUNC_CALL
895 // leaf[0]: function name
896 // leaf[1]: parameter
897
898 wxString itemName = *node->leaf[0]->value.str;
899 std::unique_ptr<VAR_REF> vref = aCode->CreateVarRef( itemName, "" );
900
901 if( !vref )
902 {
903 msg.Printf( _( "Unrecognized item '%s'" ), itemName );
905 node->leaf[0]->srcPos - (int) itemName.length() );
906 }
907
908 wxString functionName = *node->leaf[1]->leaf[0]->value.str;
909 auto func = aCode->CreateFuncCall( functionName );
910 std::vector<TREE_NODE*> params = squashParamList( node->leaf[1]->leaf[1] );
911
912 libeval_dbg( 10, "emit func call: %s\n", functionName );
913
914 if( !func )
915 {
916 msg.Printf( _( "Unrecognized function '%s'" ), functionName );
917 reportError( CST_CODEGEN, msg, node->leaf[0]->srcPos + 1 );
918 }
919
920 if( func )
921 {
922 // Preflight the function call
923
924 for( TREE_NODE* pnode : params )
925 {
926 VALUE* param = aPreflightContext->AllocValue();
927 param->Set( *pnode->value.str );
928 aPreflightContext->Push( param );
929 }
930
931 aPreflightContext->SetErrorCallback(
932 [&]( const wxString& aMessage, int aOffset )
933 {
934 size_t loc = node->leaf[1]->leaf[1]->srcPos;
935 reportError( CST_CODEGEN, aMessage, (int) loc - 1 );
936 } );
937
938 try
939 {
940 func( aPreflightContext, vref.get() );
941 aPreflightContext->Pop(); // return value
942 }
943 catch( ... )
944 {
945 }
946 }
947
948 node->leaf[0]->isVisited = true;
949 node->leaf[1]->isVisited = true;
950 node->leaf[1]->leaf[0]->isVisited = true;
951 node->leaf[1]->leaf[1]->isVisited = true;
952
953 // Our non-terminal-node stacking algorithm can't handle doubly-nested
954 // structures so we need to pop a level by replacing the TR_STRUCT_REF with
955 // a TR_OP_FUNC_CALL and its function parameter
956 stack.pop_back();
957 stack.push_back( node->leaf[1] );
958
959 for( TREE_NODE* pnode : params )
960 stack.push_back( pnode );
961
962 node->leaf[1]->SetUop( TR_OP_METHOD_CALL, func, std::move( vref ) );
963 node->isTerminal = false;
964 break;
965 }
966
967 default:
968 // leaf[0]: object
969 // leaf[1]: malformed syntax
970
971 wxString itemName = *node->leaf[0]->value.str;
972 wxString propName = *node->leaf[1]->value.str;
973 std::unique_ptr<VAR_REF> vref = aCode->CreateVarRef( itemName, propName );
974
975 if( !vref )
976 {
977 msg.Printf( _( "Unrecognized item '%s'" ), itemName );
979 node->leaf[0]->srcPos - (int) itemName.length() );
980 }
981
982 msg.Printf( _( "Unrecognized property '%s'" ), propName );
983 reportError( CST_CODEGEN, msg, node->leaf[0]->srcPos + 1 );
984
985 node->leaf[0]->isVisited = true;
986 node->leaf[1]->isVisited = true;
987
988 node->SetUop( TR_UOP_PUSH_VALUE, 0.0 );
989 node->isTerminal = true;
990 break;
991 }
992
993 break;
994 }
995
996 case TR_NUMBER:
997 {
998 TREE_NODE* son = node->leaf[0];
999 double value;
1000
1001 if( !node->value.str )
1002 {
1003 value = 0.0;
1004 }
1005 else if( son && son->op == TR_UNIT )
1006 {
1007 if( m_unitResolver->GetSupportedUnits().empty() )
1008 {
1009 msg.Printf( _( "Unexpected units for '%s'" ), *node->value.str );
1010 reportError( CST_CODEGEN, msg, node->srcPos );
1011 }
1012
1013 int units = son->value.idx;
1014 value = m_unitResolver->Convert( *node->value.str, units );
1015 son->isVisited = true;
1016 }
1017 else
1018 {
1019 if( !m_unitResolver->GetSupportedUnitsMessage().empty() )
1020 {
1021 msg.Printf( _( "Missing units for '%s'| (%s)" ),
1022 *node->value.str,
1023 m_unitResolver->GetSupportedUnitsMessage() );
1024 reportError( CST_CODEGEN, msg, node->srcPos );
1025 }
1026
1028 }
1029
1030 node->SetUop( TR_UOP_PUSH_VALUE, value );
1031 node->isTerminal = true;
1032 break;
1033 }
1034
1035 case TR_STRING:
1036 {
1037 wxString str = *node->value.str;
1038 bool isWildcard = str.Contains("?") || str.Contains("*");
1039 node->SetUop( TR_UOP_PUSH_VALUE, str, isWildcard );
1040 node->isTerminal = true;
1041 break;
1042 }
1043
1044 case TR_IDENTIFIER:
1045 {
1046 std::unique_ptr<VAR_REF> vref = aCode->CreateVarRef( *node->value.str, "" );
1047
1048 if( !vref )
1049 {
1050 msg.Printf( _( "Unrecognized item '%s'" ), *node->value.str );
1051 reportError( CST_CODEGEN, msg, node->srcPos - (int) node->value.str->length() );
1052 }
1053
1054 node->SetUop( TR_UOP_PUSH_VAR, std::move( vref ) );
1055 node->isTerminal = true;
1056 break;
1057 }
1058
1059 default:
1060 node->SetUop( node->op );
1061 node->isTerminal = ( !node->leaf[0] || node->leaf[0]->isVisited )
1062 && ( !node->leaf[1] || node->leaf[1]->isVisited );
1063 break;
1064 }
1065
1066 if( !node->isTerminal )
1067 {
1068 if( node->leaf[0] && !node->leaf[0]->isVisited )
1069 {
1070 stack.push_back( node->leaf[0] );
1071 node->leaf[0]->isVisited = true;
1072 continue;
1073 }
1074 else if( node->leaf[1] && !node->leaf[1]->isVisited )
1075 {
1076 stack.push_back( node->leaf[1] );
1077 node->leaf[1]->isVisited = true;
1078 }
1079
1080 continue;
1081 }
1082
1083 node->isVisited = true;
1084
1085 if( node->uop )
1086 {
1087 aCode->AddOp( node->uop );
1088 node->uop = nullptr;
1089 }
1090
1091 stack.pop_back();
1092 }
1093
1094 libeval_dbg(2,"dump: \n%s\n", aCode->Dump().c_str() );
1095
1096 return true;
1097}
1098
1099
1100void UOP::Exec( CONTEXT* ctx )
1101{
1102 switch( m_op )
1103 {
1104 case TR_UOP_PUSH_VAR:
1105 {
1106 VALUE* value = nullptr;
1107
1108 if( m_ref )
1109 value = ctx->StoreValue( m_ref->GetValue( ctx ) );
1110 else
1111 value = ctx->AllocValue();
1112
1113 ctx->Push( value );
1114 }
1115 break;
1116
1117 case TR_UOP_PUSH_VALUE:
1118 ctx->Push( m_value.get() );
1119 return;
1120
1121 case TR_OP_METHOD_CALL:
1122 m_func( ctx, m_ref.get() );
1123 return;
1124
1125 default:
1126 break;
1127 }
1128
1129 if( m_op & TR_OP_BINARY_MASK )
1130 {
1131 LIBEVAL::VALUE* arg2 = ctx->Pop();
1132 LIBEVAL::VALUE* arg1 = ctx->Pop();
1133 double arg2Value = arg2 ? arg2->AsDouble() : 0.0;
1134 double arg1Value = arg1 ? arg1->AsDouble() : 0.0;
1135 double result;
1136
1137 if( ctx->HasErrorCallback() )
1138 {
1139 if( arg1 && arg1->GetType() == VT_STRING && arg2 && arg2->GetType() == VT_NUMERIC )
1140 {
1141 ctx->ReportError( wxString::Format( _( "Type mismatch between '%s' and %lf" ),
1142 arg1->AsString(),
1143 arg2->AsDouble() ) );
1144 }
1145 else if( arg1 && arg1->GetType() == VT_NUMERIC && arg2 && arg2->GetType() == VT_STRING )
1146 {
1147 ctx->ReportError( wxString::Format( _( "Type mismatch between %lf and '%s'" ),
1148 arg1->AsDouble(),
1149 arg2->AsString() ) );
1150 }
1151 }
1152
1153 switch( m_op )
1154 {
1155 case TR_OP_ADD:
1156 result = arg1Value + arg2Value;
1157 break;
1158 case TR_OP_SUB:
1159 result = arg1Value - arg2Value;
1160 break;
1161 case TR_OP_MUL:
1162 result = arg1Value * arg2Value;
1163 break;
1164 case TR_OP_DIV:
1165 result = arg1Value / arg2Value;
1166 break;
1167 case TR_OP_LESS_EQUAL:
1168 result = arg1Value <= arg2Value ? 1 : 0;
1169 break;
1171 result = arg1Value >= arg2Value ? 1 : 0;
1172 break;
1173 case TR_OP_LESS:
1174 result = arg1Value < arg2Value ? 1 : 0;
1175 break;
1176 case TR_OP_GREATER:
1177 result = arg1Value > arg2Value ? 1 : 0;
1178 break;
1179 case TR_OP_EQUAL:
1180 if( !arg1 || !arg2 )
1181 result = arg1 == arg2 ? 1 : 0;
1182 else if( arg2->GetType() == VT_UNDEFINED )
1183 result = arg2->EqualTo( ctx, arg1 ) ? 1 : 0;
1184 else
1185 result = arg1->EqualTo( ctx, arg2 ) ? 1 : 0;
1186 break;
1187 case TR_OP_NOT_EQUAL:
1188 if( !arg1 || !arg2 )
1189 result = arg1 != arg2 ? 1 : 0;
1190 else if( arg2->GetType() == VT_UNDEFINED )
1191 result = arg2->NotEqualTo( ctx, arg1 ) ? 1 : 0;
1192 else
1193 result = arg1->NotEqualTo( ctx, arg2 ) ? 1 : 0;
1194 break;
1195 case TR_OP_BOOL_AND:
1196 result = arg1Value != 0.0 && arg2Value != 0.0 ? 1 : 0;
1197 break;
1198 case TR_OP_BOOL_OR:
1199 result = arg1Value != 0.0 || arg2Value != 0.0 ? 1 : 0;
1200 break;
1201 default:
1202 result = 0.0;
1203 break;
1204 }
1205
1206 auto rp = ctx->AllocValue();
1207 rp->Set( result );
1208 ctx->Push( rp );
1209 return;
1210 }
1211 else if( m_op & TR_OP_UNARY_MASK )
1212 {
1213 LIBEVAL::VALUE* arg1 = ctx->Pop();
1214 double arg1Value = arg1 ? arg1->AsDouble() : 0.0;
1215 double result;
1216
1217 switch( m_op )
1218 {
1219 case TR_OP_BOOL_NOT:
1220 result = arg1Value != 0.0 ? 0 : 1;
1221 break;
1222 default:
1223 result = arg1Value != 0.0 ? 1 : 0;
1224 break;
1225 }
1226
1227 auto rp = ctx->AllocValue();
1228 rp->Set( result );
1229 ctx->Push( rp );
1230 return;
1231 }
1232}
1233
1234
1236{
1237 static VALUE g_false( 0 );
1238
1239 try
1240 {
1241 for( UOP* op : m_ucode )
1242 op->Exec( ctx );
1243 }
1244 catch(...)
1245 {
1246 // rules which fail outright should not be fired
1247 return &g_false;
1248 }
1249
1250 if( ctx->SP() == 1 )
1251 {
1252 return ctx->Pop();
1253 }
1254 else
1255 {
1256 // If stack is corrupted after execution it suggests a problem with the compiler, not
1257 // the rule....
1258
1259 // do not use "assert"; it crashes outright on OSX
1260 wxASSERT( ctx->SP() == 1 );
1261
1262 // non-well-formed rules should not be fired on a release build
1263 return &g_false;
1264 }
1265}
1266
1267
1268} // 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)
LEXER_STATE m_lexerState
bool generateUCode(UCODE *aCode, CONTEXT *aPreflightContext)
std::function< void(const wxString &aMessage, int aOffset)> m_errorCallback
bool lexDefault(T_TOKEN &aToken)
int GetSourcePos() const
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)
VALUE * StoreValue(VALUE *aValue)
void ReportError(const wxString &aErrorMsg)
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)
wxString GetChars(const std::function< bool(wxUniChar)> &cond) const
size_t GetPos() const
bool MatchAhead(const wxString &match, const std::function< bool(wxUniChar)> &stopCond) const
TREE_NODE * leaf[2]
void SetUop(int aOp, double aValue)
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
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
void Exec(CONTEXT *ctx)
std::unique_ptr< VALUE > m_value
void Set(double aValue)
virtual const wxString & AsString() const
virtual bool NotEqualTo(CONTEXT *aCtx, const VALUE *b) const
virtual double AsDouble() const
VAR_TYPE_T GetType() const
virtual bool EqualTo(CONTEXT *aCtx, const VALUE *b) const
#define _(s)
#define libeval_dbg(level, fmt,...)
#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_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_NOT_EQUAL
#define TR_OP_BOOL_NOT
double DoubleValueFromString(const EDA_IU_SCALE &aIuScale, EDA_UNITS aUnits, const wxString &aTextValue, EDA_DATA_TYPE aType=EDA_DATA_TYPE::DISTANCE)
Function DoubleValueFromString converts aTextValue to a double.
Definition: eda_units.cpp:445
TREE_NODE * newNode(LIBEVAL::COMPILER *compiler, int op, const T_TOKEN_VALUE &value)
static std::vector< TREE_NODE * > squashParamList(TREE_NODE *root)
constexpr T_TOKEN defaultToken
void dumpNode(wxString &buf, TREE_NODE *tok, int depth=0)
constexpr T_TOKEN_VALUE defaultTokenValue
std::function< void(CONTEXT *, void *)> FUNC_CALL_REF
static const wxString formatOpName(int op)
const wxString formatNode(TREE_NODE *node)
static void prepareTree(LIBEVAL::TREE_NODE *node)
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.
COMPILATION_STAGE stage
T_TOKEN_VALUE value
wxString dump(const wxArrayString &aArray)
Debug helper for printing wxArrayString contents.