KiCad PCB EDA Suite
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-2021 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().CmpNoCase( b->AsString() );
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 }
254
255 // Allow explicit call to destructor
256 m_parser = nullptr;
257
258 Clear();
259}
260
261
263{
264 //free( current.token );
266
267 if( m_tree )
268 {
269 freeTree( m_tree );
270 m_tree = nullptr;
271 }
272
273 m_tree = nullptr;
274
275 for( auto tok : m_gcItems )
276 delete tok;
277
278 for( auto tok: m_gcStrings )
279 delete tok;
280
281 m_gcItems.clear();
282 m_gcStrings.clear();
283}
284
285
286void COMPILER::parseError( const char* s )
287{
289}
290
291
293{
294 m_parseFinished = true;
295}
296
297
298bool COMPILER::Compile( const wxString& aString, UCODE* aCode, CONTEXT* aPreflightContext )
299{
300 // Feed parser token after token until end of input.
301
302 newString( aString );
303
304 if( m_tree )
305 {
306 freeTree( m_tree );
307 m_tree = nullptr;
308 }
309
310 m_tree = nullptr;
311 m_parseFinished = false;
312 T_TOKEN tok( defaultToken );
313
314 libeval_dbg(0, "str: '%s' empty: %d\n", aString.c_str(), !!aString.empty() );
315
316 if( aString.empty() )
317 {
318 m_parseFinished = true;
319 return generateUCode( aCode, aPreflightContext );
320 }
321
322 do
323 {
325
326 tok = getToken();
327
328 if( tok.value.str )
329 GcItem( tok.value.str );
330
331 libeval_dbg(10, "parse: tok %d valstr %p\n", tok.token, tok.value.str );
332 Parse( m_parser, tok.token, tok, this );
333
335 return false;
336
337 if( m_parseFinished || tok.token == G_ENDS )
338 {
339 // Reset parser by passing zero as token ID, value is ignored.
340 Parse( m_parser, 0, tok, this );
341 break;
342 }
343 } while( tok.token );
344
345 return generateUCode( aCode, aPreflightContext );
346}
347
348
349void COMPILER::newString( const wxString& aString )
350{
351 Clear();
352
354 m_tokenizer.Restart( aString );
355 m_parseFinished = false;
356}
357
359{
360 T_TOKEN rv;
361 rv.value.str = nullptr;
362
363 bool done = false;
364
365 do
366 {
367 switch( m_lexerState )
368 {
369 case LS_DEFAULT:
370 done = lexDefault( rv );
371 break;
372 case LS_STRING:
373 done = lexString( rv );
374 break;
375 }
376 } while( !done );
377
378 return rv;
379}
380
381
383{
384 wxString str = m_tokenizer.GetChars( []( int c ) -> bool { return c != '\''; } );
385
386 aToken.token = G_STRING;
387 aToken.value.str = new wxString( str );
388
389 m_tokenizer.NextChar( str.length() + 1 );
391 return true;
392}
393
394
396{
397 int unitId = 0;
398
399 for( const wxString& unitName : m_unitResolver->GetSupportedUnits() )
400 {
401 if( m_tokenizer.MatchAhead( unitName, []( int c ) -> bool { return !isalnum( c ); } ) )
402 {
403 libeval_dbg(10, "Match unit '%s'\n", unitName.c_str() );
404 m_tokenizer.NextChar( unitName.length() );
405 return unitId;
406 }
407
408 unitId++;
409 }
410
411 return -1;
412}
413
414
416{
417 T_TOKEN retval;
418 wxString current;
419 int convertFrom;
420 wxString msg;
421
422 retval.value.str = nullptr;
423 retval.value.num = 0.0;
424 retval.value.idx = -1;
425 retval.token = G_ENDS;
426
427 if( m_tokenizer.Done() )
428 {
429 aToken = retval;
430 return true;
431 }
432
433 auto isDecimalSeparator =
434 [&]( wxUniChar ch ) -> bool
435 {
436 return ( ch == m_localeDecimalSeparator || ch == '.' || ch == ',' );
437 };
438
439 // Lambda: get value as string, store into clToken.token and update current index.
440 auto extractNumber =
441 [&]()
442 {
443 bool haveSeparator = false;
444 wxUniChar ch = m_tokenizer.GetChar();
445
446 do
447 {
448 if( isDecimalSeparator( ch ) && haveSeparator )
449 break;
450
451 current.append( 1, ch );
452
453 if( isDecimalSeparator( ch ) )
454 haveSeparator = true;
455
457 ch = m_tokenizer.GetChar();
458 } while( isdigit( ch ) || isDecimalSeparator( ch ) );
459
460 // Ensure that the systems decimal separator is used
461 for( int i = current.length(); i; i-- )
462 {
463 if( isDecimalSeparator( current[i - 1] ) )
464 current[i - 1] = m_localeDecimalSeparator;
465 }
466 };
467
468
469 int ch;
470
471 // Start processing of first/next token: Remove whitespace
472 for( ;; )
473 {
474 ch = m_tokenizer.GetChar();
475
476 if( ch == ' ' )
478 else
479 break;
480 }
481
482 libeval_dbg(10, "LEX ch '%c' pos %lu\n", ch, (unsigned long)m_tokenizer.GetPos() );
483
484 if( ch == 0 )
485 {
486 /* End of input */
487 }
488 else if( isdigit( ch ) )
489 {
490 // VALUE
491 extractNumber();
492 retval.token = G_VALUE;
493 retval.value.str = new wxString( current );
494 }
495 else if( ( convertFrom = resolveUnits() ) >= 0 )
496 {
497 // UNIT
498 // Units are appended to a VALUE.
499 // Determine factor to default unit if unit for value is given.
500 // Example: Default is mm, unit is inch: factor is 25.4
501 // The factor is assigned to the terminal UNIT. The actual
502 // conversion is done within a parser action.
503 retval.token = G_UNIT;
504 retval.value.idx = convertFrom;
505 }
506 else if( ch == '\'' ) // string literal
507 {
510 return false;
511 }
512 else if( isalpha( ch ) || ch == '_' )
513 {
514 current = m_tokenizer.GetChars( []( int c ) -> bool { return isalnum( c ) || c == '_'; } );
515 retval.token = G_IDENTIFIER;
516 retval.value.str = new wxString( current );
517 m_tokenizer.NextChar( current.length() );
518 }
519 else if( m_tokenizer.MatchAhead( "==", []( int c ) -> bool { return c != '='; } ) )
520 {
521 retval.token = G_EQUAL;
523 }
524 else if( m_tokenizer.MatchAhead( "!=", []( int c ) -> bool { return c != '='; } ) )
525 {
526 retval.token = G_NOT_EQUAL;
528 }
529 else if( m_tokenizer.MatchAhead( "<=", []( int c ) -> bool { return c != '='; } ) )
530 {
531 retval.token = G_LESS_EQUAL_THAN;
533 }
534 else if( m_tokenizer.MatchAhead( ">=", []( int c ) -> bool { return c != '='; } ) )
535 {
536 retval.token = G_GREATER_EQUAL_THAN;
538 }
539 else if( m_tokenizer.MatchAhead( "&&", []( int c ) -> bool { return c != '&'; } ) )
540 {
541 retval.token = G_BOOL_AND;
543 }
544 else if( m_tokenizer.MatchAhead( "||", []( int c ) -> bool { return c != '|'; } ) )
545 {
546 retval.token = G_BOOL_OR;
548 }
549 else
550 {
551 // Single char tokens
552 switch( ch )
553 {
554 case '+': retval.token = G_PLUS; break;
555 case '!': retval.token = G_BOOL_NOT; break;
556 case '-': retval.token = G_MINUS; break;
557 case '*': retval.token = G_MULT; break;
558 case '/': retval.token = G_DIVIDE; break;
559 case '<': retval.token = G_LESS_THAN; break;
560 case '>': retval.token = G_GREATER_THAN; break;
561 case '(': retval.token = G_PARENL; break;
562 case ')': retval.token = G_PARENR; break;
563 case ';': retval.token = G_SEMCOL; break;
564 case '.': retval.token = G_STRUCT_REF; break;
565 case ',': retval.token = G_COMMA; break;
566
567 default:
568 reportError( CST_PARSE, wxString::Format( _( "Unrecognized character '%c'" ),
569 (char) ch ) );
570 break;
571 }
572
574 }
575
576 aToken = retval;
577 return true;
578}
579
580
581const wxString formatNode( TREE_NODE* node )
582{
583 return node->value.str ? *(node->value.str) : "";
584}
585
586
587void dumpNode( wxString& buf, TREE_NODE* tok, int depth = 0 )
588{
589 wxString str;
590
591 if( !tok )
592 return;
593
594 str.Printf( "\n[%p L0:%-20p L1:%-20p] ", tok, tok->leaf[0], tok->leaf[1] );
595 buf += str;
596
597 for( int i = 0; i < 2 * depth; i++ )
598 buf += " ";
599
600 if( tok->op & TR_OP_BINARY_MASK )
601 {
602 buf += formatOpName( tok->op );
603 dumpNode( buf, tok->leaf[0], depth + 1 );
604 dumpNode( buf, tok->leaf[1], depth + 1 );
605 }
606
607 switch( tok->op )
608 {
609 case TR_NUMBER:
610 buf += "NUMERIC: ";
611 buf += formatNode( tok );
612
613 if( tok->leaf[0] )
614 dumpNode( buf, tok->leaf[0], depth + 1 );
615
616 break;
617
618 case TR_ARG_LIST:
619 buf += "ARG_LIST: ";
620 buf += formatNode( tok );
621
622 if( tok->leaf[0] )
623 dumpNode( buf, tok->leaf[0], depth + 1 );
624 if( tok->leaf[1] )
625 dumpNode( buf, tok->leaf[1], depth + 1 );
626
627 break;
628
629 case TR_STRING:
630 buf += "STRING: ";
631 buf += formatNode( tok );
632 break;
633
634 case TR_IDENTIFIER:
635 buf += "ID: ";
636 buf += formatNode( tok );
637 break;
638
639 case TR_STRUCT_REF:
640 buf += "SREF: ";
641 dumpNode( buf, tok->leaf[0], depth + 1 );
642 dumpNode( buf, tok->leaf[1], depth + 1 );
643 break;
644
645 case TR_OP_FUNC_CALL:
646 buf += "CALL '";
647 buf += *tok->leaf[0]->value.str;
648 buf += "': ";
649 dumpNode( buf, tok->leaf[1], depth + 1 );
650 break;
651
652 case TR_UNIT:
653 str.Printf( "UNIT: %d ", tok->value.idx );
654 buf += str;
655 break;
656 }
657}
658
659
660void CONTEXT::ReportError( const wxString& aErrorMsg )
661{
662 if( m_errorCallback )
663 m_errorCallback( aErrorMsg, -1 );
664}
665
666
667void COMPILER::reportError( COMPILATION_STAGE stage, const wxString& aErrorMsg, int aPos )
668{
669 if( aPos == -1 )
670 aPos = m_sourcePos;
671
673 m_errorStatus.stage = stage;
674 m_errorStatus.message = aErrorMsg;
675 m_errorStatus.srcPos = aPos;
676
677 if( m_errorCallback )
678 m_errorCallback( aErrorMsg, aPos );
679}
680
681
683{
684 m_tree = root;
685}
686
687
689{
690 if ( tree->leaf[0] )
691 freeTree( tree->leaf[0] );
692
693 if ( tree->leaf[1] )
694 freeTree( tree->leaf[1] );
695
696 delete tree->uop;
697}
698
699
700void TREE_NODE::SetUop( int aOp, double aValue )
701{
702 delete uop;
703
704 std::unique_ptr<VALUE> val = std::make_unique<VALUE>( aValue );
705 uop = new UOP( aOp, std::move( val ) );
706}
707
708
709void TREE_NODE::SetUop( int aOp, const wxString& aValue, bool aStringIsWildcard )
710{
711 delete uop;
712
713 std::unique_ptr<VALUE> val = std::make_unique<VALUE>( aValue, aStringIsWildcard );
714 uop = new UOP( aOp, std::move( val ) );
715}
716
717
718void TREE_NODE::SetUop( int aOp, std::unique_ptr<VAR_REF> aRef )
719{
720 delete uop;
721
722 uop = new UOP( aOp, std::move( aRef ) );
723}
724
725
726void TREE_NODE::SetUop( int aOp, FUNC_CALL_REF aFunc, std::unique_ptr<VAR_REF> aRef )
727{
728 delete uop;
729
730 uop = new UOP( aOp, std::move( aFunc ), std::move( aRef ) );
731}
732
733
734static void prepareTree( LIBEVAL::TREE_NODE *node )
735{
736 node->isVisited = false;
737
738 // fixme: for reasons I don't understand the lemon parser isn't initializing the
739 // leaf node pointers of function name nodes. -JY
740 if( node->op == TR_OP_FUNC_CALL && node->leaf[0] )
741 {
742 node->leaf[0]->leaf[0] = nullptr;
743 node->leaf[0]->leaf[1] = nullptr;
744 }
745
746 if ( node->leaf[0] )
747 prepareTree( node->leaf[0] );
748
749 if ( node->leaf[1] )
750 prepareTree( node->leaf[1] );
751}
752
753static std::vector<TREE_NODE*> squashParamList( TREE_NODE* root )
754{
755 std::vector<TREE_NODE*> args;
756
757 if( !root )
758 {
759 return args;
760 }
761
762 if( root->op != TR_ARG_LIST && root->op != TR_NULL )
763 {
764 args.push_back( root );
765 }
766 else
767 {
768 TREE_NODE *n = root;
769 do
770 {
771 if( n->leaf[1] )
772 args.push_back(n->leaf[1]);
773
774 n = n->leaf[0];
775 } while ( n && n->op == TR_ARG_LIST );
776
777 if( n )
778 {
779 args.push_back( n );
780 }
781 }
782
783 std::reverse( args.begin(), args.end() );
784
785 for( size_t i = 0; i < args.size(); i++ )
786 libeval_dbg( 10, "squash arg%d: %s\n", int( i ), *args[i]->value.str );
787
788 return args;
789}
790
791
792bool COMPILER::generateUCode( UCODE* aCode, CONTEXT* aPreflightContext )
793{
794 std::vector<TREE_NODE*> stack;
795 wxString msg;
796
797 if( !m_tree )
798 {
799 std::unique_ptr<VALUE> val = std::make_unique<VALUE>( 1.0 );
800 // Empty expression returns true
801 aCode->AddOp( new UOP( TR_UOP_PUSH_VALUE, std::move(val) ) );
802 return true;
803 }
804
806
807 stack.push_back( m_tree );
808
809 wxString dump;
810
811 dumpNode( dump, m_tree, 0 );
812 libeval_dbg( 3, "Tree dump:\n%s\n\n", (const char*) dump.c_str() );
813
814 while( !stack.empty() )
815 {
816 TREE_NODE* node = stack.back();
817
818 libeval_dbg( 4, "process node %p [op %d] [stack %lu]\n",
819 node, node->op, (unsigned long)stack.size() );
820
821 // process terminal nodes first
822 switch( node->op )
823 {
824 case TR_OP_FUNC_CALL:
825 // Function call's uop was generated inside TR_STRUCT_REF
826 if( !node->uop )
827 {
828 reportError( CST_CODEGEN, _( "Unknown parent of function parameters" ),
829 node->srcPos );
830 }
831
832 node->isTerminal = true;
833 break;
834
835 case TR_STRUCT_REF:
836 {
837 // leaf[0]: object
838 // leaf[1]: field (TR_IDENTIFIER) or TR_OP_FUNC_CALL
839
840 if( node->leaf[0]->op != TR_IDENTIFIER )
841 {
842 int pos = node->leaf[0]->srcPos;
843
844 if( node->leaf[0]->value.str )
845 pos -= static_cast<int>( node->leaf[0]->value.str->length() );
846
847 reportError( CST_CODEGEN, _( "Unknown parent of property" ), pos );
848
849 node->leaf[0]->isVisited = true;
850 node->leaf[1]->isVisited = true;
851
852 node->SetUop( TR_UOP_PUSH_VALUE, 0.0 );
853 node->isTerminal = true;
854 break;
855 }
856
857 switch( node->leaf[1]->op )
858 {
859 case TR_IDENTIFIER:
860 {
861 // leaf[0]: object
862 // leaf[1]: field
863
864 wxString itemName = *node->leaf[0]->value.str;
865 wxString propName = *node->leaf[1]->value.str;
866 std::unique_ptr<VAR_REF> vref = aCode->CreateVarRef( itemName, propName );
867
868 if( !vref )
869 {
870 msg.Printf( _( "Unrecognized item '%s'" ), itemName );
872 node->leaf[0]->srcPos - (int) itemName.length() );
873 }
874 else if( vref->GetType() == VT_PARSE_ERROR )
875 {
876 msg.Printf( _( "Unrecognized property '%s'" ), propName );
878 node->leaf[1]->srcPos - (int) propName.length() );
879 }
880
881 node->leaf[0]->isVisited = true;
882 node->leaf[1]->isVisited = true;
883
884 node->SetUop( TR_UOP_PUSH_VAR, std::move( vref ) );
885 node->isTerminal = true;
886 break;
887 }
888 case TR_OP_FUNC_CALL:
889 {
890 // leaf[0]: object
891 // leaf[1]: TR_OP_FUNC_CALL
892 // leaf[0]: function name
893 // leaf[1]: parameter
894
895 wxString itemName = *node->leaf[0]->value.str;
896 std::unique_ptr<VAR_REF> vref = aCode->CreateVarRef( itemName, "" );
897
898 if( !vref )
899 {
900 msg.Printf( _( "Unrecognized item '%s'" ), itemName );
902 node->leaf[0]->srcPos - (int) itemName.length() );
903 }
904
905 wxString functionName = *node->leaf[1]->leaf[0]->value.str;
906 auto func = aCode->CreateFuncCall( functionName );
907 std::vector<TREE_NODE*> params = squashParamList( node->leaf[1]->leaf[1] );
908
909 libeval_dbg( 10, "emit func call: %s\n", functionName );
910
911 if( !func )
912 {
913 msg.Printf( _( "Unrecognized function '%s'" ), functionName );
914 reportError( CST_CODEGEN, msg, node->leaf[0]->srcPos + 1 );
915 }
916
917 if( func )
918 {
919 // Preflight the function call
920
921 for( TREE_NODE* pnode : params )
922 {
923 VALUE* param = aPreflightContext->AllocValue();
924 param->Set( *pnode->value.str );
925 aPreflightContext->Push( param );
926 }
927
928 aPreflightContext->SetErrorCallback(
929 [&]( const wxString& aMessage, int aOffset )
930 {
931 size_t loc = node->leaf[1]->leaf[1]->srcPos;
932 reportError( CST_CODEGEN, aMessage, (int) loc - 1 );
933 } );
934
935 try
936 {
937 func( aPreflightContext, vref.get() );
938 aPreflightContext->Pop(); // return value
939 }
940 catch( ... )
941 {
942 }
943 }
944
945 node->leaf[0]->isVisited = true;
946 node->leaf[1]->isVisited = true;
947 node->leaf[1]->leaf[0]->isVisited = true;
948 node->leaf[1]->leaf[1]->isVisited = true;
949
950 // Our non-terminal-node stacking algorithm can't handle doubly-nested
951 // structures so we need to pop a level by replacing the TR_STRUCT_REF with
952 // a TR_OP_FUNC_CALL and its function parameter
953 stack.pop_back();
954 stack.push_back( node->leaf[1] );
955
956 for( TREE_NODE* pnode : params )
957 stack.push_back( pnode );
958
959 node->leaf[1]->SetUop( TR_OP_METHOD_CALL, func, std::move( vref ) );
960 node->isTerminal = false;
961 break;
962 }
963
964 default:
965 // leaf[0]: object
966 // leaf[1]: malformed syntax
967
968 wxString itemName = *node->leaf[0]->value.str;
969 wxString propName = *node->leaf[1]->value.str;
970 std::unique_ptr<VAR_REF> vref = aCode->CreateVarRef( itemName, propName );
971
972 if( !vref )
973 {
974 msg.Printf( _( "Unrecognized item '%s'" ), itemName );
976 node->leaf[0]->srcPos - (int) itemName.length() );
977 }
978
979 msg.Printf( _( "Unrecognized property '%s'" ), propName );
980 reportError( CST_CODEGEN, msg, node->leaf[0]->srcPos + 1 );
981
982 node->leaf[0]->isVisited = true;
983 node->leaf[1]->isVisited = true;
984
985 node->SetUop( TR_UOP_PUSH_VALUE, 0.0 );
986 node->isTerminal = true;
987 break;
988 }
989
990 break;
991 }
992
993 case TR_NUMBER:
994 {
995 TREE_NODE* son = node->leaf[0];
996 double value;
997
998 if( !node->value.str )
999 {
1000 value = 0.0;
1001 }
1002 else if( son && son->op == TR_UNIT )
1003 {
1004 int units = son->value.idx;
1005 value = m_unitResolver->Convert( *node->value.str, units );
1006 son->isVisited = true;
1007 }
1008 else
1009 {
1010 msg.Printf( _( "Missing units for '%s'| (%s)" ),
1011 *node->value.str,
1012 m_unitResolver->GetSupportedUnitsMessage() );
1013 reportError( CST_CODEGEN, msg, node->srcPos );
1014
1016 }
1017
1018 node->SetUop( TR_UOP_PUSH_VALUE, value );
1019 node->isTerminal = true;
1020 break;
1021 }
1022
1023 case TR_STRING:
1024 {
1025 wxString str = *node->value.str;
1026 bool isWildcard = str.Contains("?") || str.Contains("*");
1027 node->SetUop( TR_UOP_PUSH_VALUE, str, isWildcard );
1028 node->isTerminal = true;
1029 break;
1030 }
1031
1032 case TR_IDENTIFIER:
1033 {
1034 std::unique_ptr<VAR_REF> vref = aCode->CreateVarRef( *node->value.str, "" );
1035
1036 if( !vref )
1037 {
1038 msg.Printf( _( "Unrecognized item '%s'" ), *node->value.str );
1039 reportError( CST_CODEGEN, msg, node->srcPos - (int) node->value.str->length() );
1040 }
1041
1042 node->SetUop( TR_UOP_PUSH_VAR, std::move( vref ) );
1043 node->isTerminal = true;
1044 break;
1045 }
1046
1047 default:
1048 node->SetUop( node->op );
1049 node->isTerminal = ( !node->leaf[0] || node->leaf[0]->isVisited )
1050 && ( !node->leaf[1] || node->leaf[1]->isVisited );
1051 break;
1052 }
1053
1054 if( !node->isTerminal )
1055 {
1056 if( node->leaf[0] && !node->leaf[0]->isVisited )
1057 {
1058 stack.push_back( node->leaf[0] );
1059 node->leaf[0]->isVisited = true;
1060 continue;
1061 }
1062 else if( node->leaf[1] && !node->leaf[1]->isVisited )
1063 {
1064 stack.push_back( node->leaf[1] );
1065 node->leaf[1]->isVisited = true;
1066 }
1067
1068 continue;
1069 }
1070
1071 node->isVisited = true;
1072
1073 if( node->uop )
1074 {
1075 aCode->AddOp( node->uop );
1076 node->uop = nullptr;
1077 }
1078
1079 stack.pop_back();
1080 }
1081
1082 libeval_dbg(2,"dump: \n%s\n", aCode->Dump().c_str() );
1083
1084 return true;
1085}
1086
1087
1088void UOP::Exec( CONTEXT* ctx )
1089{
1090 switch( m_op )
1091 {
1092 case TR_UOP_PUSH_VAR:
1093 {
1094 VALUE* value = nullptr;
1095
1096 if( m_ref )
1097 value = ctx->StoreValue( m_ref->GetValue( ctx ) );
1098 else
1099 value = ctx->AllocValue();
1100
1101 ctx->Push( value );
1102 }
1103 break;
1104
1105 case TR_UOP_PUSH_VALUE:
1106 ctx->Push( m_value.get() );
1107 return;
1108
1109 case TR_OP_METHOD_CALL:
1110 m_func( ctx, m_ref.get() );
1111 return;
1112
1113 default:
1114 break;
1115 }
1116
1117 if( m_op & TR_OP_BINARY_MASK )
1118 {
1119 LIBEVAL::VALUE* arg2 = ctx->Pop();
1120 LIBEVAL::VALUE* arg1 = ctx->Pop();
1121 double arg2Value = arg2 ? arg2->AsDouble() : 0.0;
1122 double arg1Value = arg1 ? arg1->AsDouble() : 0.0;
1123 double result;
1124
1125 if( ctx->HasErrorCallback() )
1126 {
1127 if( arg1 && arg1->GetType() == VT_STRING && arg2 && arg2->GetType() == VT_NUMERIC )
1128 {
1129 ctx->ReportError( wxString::Format( _( "Type mismatch between '%s' and %lf" ),
1130 arg1->AsString(),
1131 arg2->AsDouble() ) );
1132 }
1133 else if( arg1 && arg1->GetType() == VT_NUMERIC && arg2 && arg2->GetType() == VT_STRING )
1134 {
1135 ctx->ReportError( wxString::Format( _( "Type mismatch between %lf and '%s'" ),
1136 arg1->AsDouble(),
1137 arg2->AsString() ) );
1138 }
1139 }
1140
1141 switch( m_op )
1142 {
1143 case TR_OP_ADD:
1144 result = arg1Value + arg2Value;
1145 break;
1146 case TR_OP_SUB:
1147 result = arg1Value - arg2Value;
1148 break;
1149 case TR_OP_MUL:
1150 result = arg1Value * arg2Value;
1151 break;
1152 case TR_OP_DIV:
1153 result = arg1Value / arg2Value;
1154 break;
1155 case TR_OP_LESS_EQUAL:
1156 result = arg1Value <= arg2Value ? 1 : 0;
1157 break;
1159 result = arg1Value >= arg2Value ? 1 : 0;
1160 break;
1161 case TR_OP_LESS:
1162 result = arg1Value < arg2Value ? 1 : 0;
1163 break;
1164 case TR_OP_GREATER:
1165 result = arg1Value > arg2Value ? 1 : 0;
1166 break;
1167 case TR_OP_EQUAL:
1168 if( !arg1 || !arg2 )
1169 result = arg1 == arg2 ? 1 : 0;
1170 else if( arg2->GetType() == VT_UNDEFINED )
1171 result = arg2->EqualTo( ctx, arg1 ) ? 1 : 0;
1172 else
1173 result = arg1->EqualTo( ctx, arg2 ) ? 1 : 0;
1174 break;
1175 case TR_OP_NOT_EQUAL:
1176 if( !arg1 || !arg2 )
1177 result = arg1 != arg2 ? 1 : 0;
1178 else if( arg2->GetType() == VT_UNDEFINED )
1179 result = arg2->NotEqualTo( ctx, arg1 ) ? 1 : 0;
1180 else
1181 result = arg1->NotEqualTo( ctx, arg2 ) ? 1 : 0;
1182 break;
1183 case TR_OP_BOOL_AND:
1184 result = arg1Value != 0.0 && arg2Value != 0.0 ? 1 : 0;
1185 break;
1186 case TR_OP_BOOL_OR:
1187 result = arg1Value != 0.0 || arg2Value != 0.0 ? 1 : 0;
1188 break;
1189 default:
1190 result = 0.0;
1191 break;
1192 }
1193
1194 auto rp = ctx->AllocValue();
1195 rp->Set( result );
1196 ctx->Push( rp );
1197 return;
1198 }
1199 else if( m_op & TR_OP_UNARY_MASK )
1200 {
1201 LIBEVAL::VALUE* arg1 = ctx->Pop();
1202 double arg1Value = arg1 ? arg1->AsDouble() : 0.0;
1203 double result;
1204
1205 switch( m_op )
1206 {
1207 case TR_OP_BOOL_NOT:
1208 result = arg1Value != 0.0 ? 0 : 1;
1209 break;
1210 default:
1211 result = 0.0;
1212 break;
1213 }
1214
1215 auto rp = ctx->AllocValue();
1216 rp->Set( result );
1217 ctx->Push( rp );
1218 return;
1219 }
1220}
1221
1222
1224{
1225 static VALUE g_false( 0 );
1226
1227 try
1228 {
1229 for( UOP* op : m_ucode )
1230 op->Exec( ctx );
1231 }
1232 catch(...)
1233 {
1234 // rules which fail outright should not be fired
1235 return &g_false;
1236 }
1237
1238 if( ctx->SP() == 1 )
1239 {
1240 return ctx->Pop();
1241 }
1242 else
1243 {
1244 // If stack is corrupted after execution it suggests a problem with the compiler, not
1245 // the rule....
1246
1247 // do not use "assert"; it crashes outright on OSX
1248 wxASSERT( ctx->SP() == 1 );
1249
1250 // non-well-formed rules should not be fired on a release build
1251 return &g_false;
1252 }
1253}
1254
1255
1256} // 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:451
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)
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)
PARSE_RESULT Parse(const std::string &aString, NOTATION aNotation=NOTATION::SI, SIM_VALUE::TYPE aValueType=SIM_VALUE::TYPE_FLOAT)
Definition: sim_value.cpp:189
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
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.