45#pragma GCC diagnostic push
46#pragma GCC diagnostic ignored "-Wunused-variable"
47#pragma GCC diagnostic ignored "-Wsign-compare"
50#include <libeval_compiler/grammar.c>
51#include <libeval_compiler/grammar.h>
54#pragma GCC diagnostic pop
58#define libeval_dbg(level, fmt, ...) \
59 wxLogTrace( "libeval_compiler", fmt, __VA_ARGS__ );
71 t2->
leaf[0] =
nullptr;
72 t2->
leaf[1] =
nullptr;
113 for(
int i = 0; simpleOps[i].op >= 0; i++ )
115 if( simpleOps[i].op == op )
116 return simpleOps[i].mnemonic;
163 str = wxString::Format(
"PUSH VAR [%p]",
m_ref.get() );
168 str = wxString::Format(
"PUSH nullptr" );
170 str = wxString::Format(
"PUSH NUM [%.10f]",
m_value->AsDouble() );
172 str = wxString::Format(
"PUSH STR [%ls]",
m_value->AsString() );
176 str = wxString::Format(
"MCALL" );
180 str = wxString::Format(
"FCALL" );
244 while( p <
m_str.length() && cond(
m_str[p] ) )
246 rv.append( 1,
m_str[p] );
255 const std::function<
bool( wxUniChar )>& stopCond )
const
259 if( remaining < (
int) match.length() )
262 if(
m_str.substr(
m_pos, match.length() ) == match )
263 return ( remaining == (
int) match.length() || stopCond(
m_str[
m_pos + match.length()] ) );
276 m_parser = LIBEVAL::ParseAlloc( malloc );
284 LIBEVAL::ParseFree(
m_parser, free );
351 libeval_dbg(0,
"str: '%s' empty: %d\n", aString.c_str(), !!aString.empty() );
353 if( aString.empty() )
380 }
while( tok.
token );
423 aToken.
token = G_STRING;
435 for(
const wxString& unitName :
m_unitResolver->GetSupportedUnits() )
440 return !isalnum( c );
443 libeval_dbg(10,
"Match unit '%s'\n", unitName.c_str() );
464 retval.
token = G_ENDS;
476 bool haveSeparator =
false;
477 bool haveDigit =
false;
480 auto isDecimalSeparator =
481 [&]( wxUniChar c ) ->
bool
489 return haveDigit && wxIsdigit(
m_tokenizer.GetChar( 1 ) )
495 if( isDecimalSeparator( ch ) && haveSeparator )
498 current.append( 1, ch );
500 if( isDecimalSeparator( ch ) )
501 haveSeparator =
true;
507 }
while( isdigit( ch ) || isDecimalSeparator( ch ) );
511 for(
int i = current.length(); i; i-- )
513 if( current[i - 1] ==
'.' || current[i - 1] ==
',' )
537 else if( isdigit( ch ) )
541 retval.
token = G_VALUE;
542 retval.
value.
str =
new wxString( current );
552 retval.
token = G_UNIT;
555 else if( ch ==
'\'' )
561 else if( isalpha( ch ) || ch ==
'_' )
563 current =
m_tokenizer.GetChars( [](
int c ) ->
bool {
return isalnum( c ) || c ==
'_'; } );
564 retval.
token = G_IDENTIFIER;
565 retval.
value.
str =
new wxString( current );
568 else if(
m_tokenizer.MatchAhead(
"==", [](
int c ) ->
bool { return c !=
'='; } ) )
570 retval.
token = G_EQUAL;
573 else if(
m_tokenizer.MatchAhead(
"!=", [](
int c ) ->
bool { return c !=
'='; } ) )
575 retval.
token = G_NOT_EQUAL;
578 else if(
m_tokenizer.MatchAhead(
"<=", [](
int c ) ->
bool { return c !=
'='; } ) )
580 retval.
token = G_LESS_EQUAL_THAN;
583 else if(
m_tokenizer.MatchAhead(
">=", [](
int c ) ->
bool { return c !=
'='; } ) )
585 retval.
token = G_GREATER_EQUAL_THAN;
588 else if(
m_tokenizer.MatchAhead(
"&&", [](
int c ) ->
bool { return c !=
'&'; } ) )
590 retval.
token = G_BOOL_AND;
593 else if(
m_tokenizer.MatchAhead(
"||", [](
int c ) ->
bool { return c !=
'|'; } ) )
595 retval.
token = G_BOOL_OR;
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;
617 if(
m_tokenizer.MatchAhead(
"${", [](
int c ) ->
bool { return c !=
'{'; } ) )
645 str.Printf(
"\n[%p L0:%-20p L1:%-20p] ", tok, tok->
leaf[0], tok->
leaf[1] );
648 for(
int i = 0; i < 2 * depth; i++ )
704 str.Printf(
"UNIT: %d ", tok->
value.
idx );
720 ReportError(
_(
"Expression evaluation stack overflow" ) );
724#if defined( __MINGW64__ )
767 std::unique_ptr<VALUE> val = std::make_unique<VALUE>( aValue );
768 val->SetUnits( aUnits );
769 uop =
new UOP( aOp, std::move( val ) );
777 std::unique_ptr<VALUE> val = std::make_unique<VALUE>( aValue, aStringIsWildcard );
778 uop =
new UOP( aOp, std::move( val ) );
786 uop =
new UOP( aOp, std::move( aRef ) );
794 uop =
new UOP( aOp, std::move( aFunc ), std::move( aRef ) );
820 std::vector<TREE_NODE*> args;
827 args.push_back( root );
835 args.push_back(n->
leaf[1]);
844 std::reverse( args.begin(), args.end() );
846 for(
size_t i = 0; i < args.size(); i++ )
886 std::vector<TREE_NODE*> stack;
888 int numericValueCount = 0;
889 wxString missingUnitsMsg;
890 int missingUnitsSrcPos = 0;
894 std::map<TREE_NODE*, UOP*> scJumps;
898 std::unique_ptr<VALUE> val = std::make_unique<VALUE>( 1.0 );
906 stack.push_back(
m_tree );
913 while( !stack.empty() )
917 libeval_dbg( 4,
"process node %p [op %d] [stack %lu]\n", node, node->
op, (
unsigned long)stack.size() );
959 switch( node->
leaf[1]->
op )
967 std::unique_ptr<VAR_REF> vref = aCode->
CreateVarRef( itemName, propName );
971 msg.Printf(
_(
"Unrecognized item '%s'" ), itemName );
976 msg.Printf(
_(
"Unrecognized property '%s'" ), propName );
993 std::unique_ptr<VAR_REF> vref = aCode->
CreateVarRef( itemName,
"" );
997 msg.Printf(
_(
"Unrecognized item '%s'" ), itemName );
1005 libeval_dbg( 10,
"emit func call: %s\n", functionName );
1009 msg.Printf(
_(
"Unrecognized function '%s'" ), functionName );
1015 const bool literalArgs = std::all_of( params.begin(), params.end(),
1018 return param->op == TR_STRING || param->op == TR_NUMBER;
1021 if( func && literalArgs )
1023 bool overflow =
false;
1026 [&](
const wxString& aMessage,
int aOffset )
1038 aPreflightContext->
Push( param );
1041 func( aPreflightContext, vref.get() );
1042 aPreflightContext->
Pop();
1070 stack.push_back( node->
leaf[1] );
1073 stack.push_back( pnode );
1085 std::unique_ptr<VAR_REF> vref = aCode->
CreateVarRef( itemName, propName );
1089 msg.Printf(
_(
"Unrecognized item '%s'" ), itemName );
1093 msg.Printf(
_(
"Unrecognized property '%s'" ), propName );
1121 msg.Printf(
_(
"Unexpected units for '%s'" ),
formatNode( node ) );
1134 missingUnitsMsg.Printf(
_(
"Missing units for '%s'| (%s)" ),
1137 missingUnitsSrcPos = node->
srcPos;
1145 numericValueCount++;
1152 bool isWildcard = str.Contains(
"?") || str.Contains(
"*");
1164 msg.Printf(
_(
"Unrecognized item '%s'" ),
formatNode( node ) );
1184 stack.push_back( node->
leaf[0] );
1195 aCode->
AddOp( jump );
1197 scJumps[node] = jump;
1200 stack.push_back( node->
leaf[1] );
1212 node->
uop =
nullptr;
1215 auto jumpIt = scJumps.find( node );
1217 if( jumpIt != scJumps.end() )
1218 jumpIt->second->SetJumpTarget( aCode->
GetSize() );
1232 if( !missingUnitsMsg.IsEmpty() && numericValueCount == 1 )
1277 VALUE* value =
nullptr;
1315#define AS_DOUBLE( arg ) ( arg ? arg->AsDouble() : 0.0 )
1331 arg1 = &autoConverted;
1335 ctx->
ReportError( wxString::Format(
_(
"Type mismatch between '%s' and %lf" ),
1347 arg2 = &autoConverted;
1351 ctx->
ReportError( wxString::Format(
_(
"Type mismatch between %lf and '%s'" ),
1361 auto getOpResultUnits =
1368 return aVal2->GetUnits();
1373 return aVal2->GetUnits();
1382 resultUnits = getOpResultUnits( arg1, arg2 );
1387 resultUnits = getOpResultUnits( arg1, arg2 );
1392 resultUnits = getOpResultUnits( arg1, arg2 );
1397 resultUnits = getOpResultUnits( arg1, arg2 );
1416 if( !arg1 || !arg2 )
1417 result = arg1 == arg2 ? 1 : 0;
1425 if( !arg1 || !arg2 )
1426 result = arg1 != arg2 ? 1 : 0;
1455 double ARG1VALUE = arg1 ? arg1->
AsDouble() : 0.0;
1462 result = ARG1VALUE != 0.0 ? 0 : 1;
1465 result = ARG1VALUE != 0.0 ? 1 : 0;
1486 for( std::size_t ip = 0; ip <
m_ucode.size(); )
1492 wxASSERT(
next < 0 ||
static_cast<std::size_t
>(
next ) > ip );
1510 if( ctx->
SP() == 1 )
1524 if( aText.EndsWith( wxS(
"\\" ) ) )
1525 return std::nullopt;
1527 wxString escaped = aText;
1528 escaped.Replace( wxS(
"'" ), wxS(
"\\'" ) );
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)
char m_localeDecimalSeparator
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)
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)
std::vector< UOP * > m_ucode
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
int Exec(CONTEXT *ctx)
Execute the op.
std::unique_ptr< VALUE > m_value
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 libeval_dbg(level, fmt,...)
#define TR_OP_GREATER_EQUAL
#define TR_UOP_PUSH_VALUE
#define TR_OP_METHOD_CALL
#define TR_OP_BINARY_MASK
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)
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)
@ 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.