KiCad PCB EDA Suite
numeric_evaluator.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, mgeselbracht3@gmail.com
5 
6  This program is free software: you can redistribute it and/or modify
7  it under the terms of the GNU General Public License as published by
8  the Free Software Foundation, either version 3 of the License, or
9  (at your option) any later version.
10 
11  This program is distributed in the hope that it will be useful,
12  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  GNU General Public License for more details.
15 
16  You should have received a copy of the GNU General Public License
17  along with this program. If not, see <https://www.gnu.org/licenses/>.
18 */
19 
20 
22 
23 /* The (generated) lemon parser is written in C.
24  * In order to keep its symbol from the global namespace include the parser code with
25  * a C++ namespace.
26  */
27 namespace numEval
28 {
29 
30 #ifdef __GNUC__
31 #pragma GCC diagnostic push
32 #pragma GCC diagnostic ignored "-Wunused-variable"
33 #pragma GCC diagnostic ignored "-Wsign-compare"
34 #endif
35 
36 #include "grammar.c"
37 #include "grammar.h"
38 
39 #ifdef __GNUC__
40 #pragma GCC diagnostic pop
41 #endif
42 
43 } /* namespace numEval */
44 
45 
47 {
48  struct lconv* lc = localeconv();
49  m_localeDecimalSeparator = *lc->decimal_point;
50 
51  m_parseError = false;
52  m_parseFinished = false;
53 
55 
56  switch( aUnits )
57  {
59  if( aUseMils )
61  else
63  break;
66  break;
68  break;
69  }
70 }
71 
72 
74 {
76 
77  // Allow explicit call to destructor
78  m_parser = nullptr;
79 
80  Clear();
81 }
82 
83 
85 {
86  free( m_token.token );
87  m_token.token = nullptr;
88  m_token.input = nullptr;
89  m_parseError = true;
90  m_originalText = wxEmptyString;
91 }
92 
93 
94 void NUMERIC_EVALUATOR::parseError( const char* s )
95 {
96  m_parseError = true;
97 }
98 
99 
101 {
103 }
105 
107 {
108  if( std::isnan( val ) )
109  {
110  // Naively printing this with %g produces "nan" on some platforms
111  // and "-nan(ind)" on others (e.g. MSVC). So force a "standard" string.
112  snprintf( m_token.token, m_token.OutLen, "%s", "NaN" );
113  }
114  else
115  {
116  // Can be printed as a floating point
117  snprintf( m_token.token, m_token.OutLen, "%.10g", val );
118  }
119 }
123 {
125 }
128 bool NUMERIC_EVALUATOR::Process( const wxString& aString )
129 {
130  // Feed parser token after token until end of input.
131 
132  newString( aString );
133  m_parseError = false;
135  Token tok;
136 
137  if( aString.IsEmpty() )
138  {
140  return true;
141  }
143  do
144  {
145  tok = getToken();
146  numEval::Parse( m_parser, tok.token, tok.value, this );
148  if( m_parseFinished || tok.token == ENDS )
149  {
150  // Reset parser by passing zero as token ID, value is ignored.
151  numEval::Parse( m_parser, 0, tok.value, this );
152  break;
153  }
154  } while( tok.token );
156  return !m_parseError;
157 }
158 
160 void NUMERIC_EVALUATOR::newString( const wxString& aString )
161 {
162  Clear();
164  m_originalText = aString;
166  m_token.token = reinterpret_cast<decltype( m_token.token )>( malloc( TokenStat::OutLen + 1 ) );
167  strcpy( m_token.token, "0" );
168  m_token.inputLen = aString.length();
169  m_token.pos = 0;
170  m_token.input = aString.mb_str();
173 }
177 {
178  Token retval;
179  size_t idx;
181  retval.token = ENDS;
182  retval.value.dValue = 0;
184  if( m_token.token == nullptr )
185  return retval;
186 
187  if( m_token.input == nullptr )
188  return retval;
189 
190  if( m_token.pos >= m_token.inputLen )
191  return retval;
192 
193  auto isDecimalSeparator = [ & ]( char ch ) -> bool {
194  return ( ch == m_localeDecimalSeparator || ch == '.' || ch == ',' );
195  };
196 
197  // Lambda: get value as string, store into clToken.token and update current index.
198  auto extractNumber = [ & ]() {
199  bool haveSeparator = false;
200  idx = 0;
201  auto ch = m_token.input[ m_token.pos ];
202 
203  do
204  {
205  if( isDecimalSeparator( ch ) && haveSeparator )
206  break;
208  m_token.token[ idx++ ] = ch;
209 
210  if( isDecimalSeparator( ch ))
211  haveSeparator = true;
214  } while( isdigit( ch ) || isDecimalSeparator( ch ));
216  m_token.token[ idx ] = 0;
217 
218  // Ensure that the systems decimal separator is used
219  for( int i = strlen( m_token.token ); i; i-- )
220  if( isDecimalSeparator( m_token.token[ i - 1 ] ))
222  };
224  // Lamda: Get unit for current token.
225  // Valid units are ", in, mm, mil and thou. Returns Unit::Invalid otherwise.
226  auto checkUnit = [ this ]() -> Unit {
227  char ch = m_token.input[ m_token.pos ];
229  if( ch == '"' )
230  {
231  m_token.pos++;
232  return Unit::Inch;
233  }
235  // Do not use strcasecmp() as it is not available on all platforms
236  const char* cptr = &m_token.input[ m_token.pos ];
237  const auto sizeLeft = m_token.inputLen - m_token.pos;
238 
239  if( sizeLeft >= 2 && ch == 'm' && cptr[ 1 ] == 'm' && !isalnum( cptr[ 2 ] ))
240  {
241  m_token.pos += 2;
242  return Unit::Metric;
243  }
244 
245  if( sizeLeft >= 2 && ch == 'i' && cptr[ 1 ] == 'n' && !isalnum( cptr[ 2 ] ))
246  {
247  m_token.pos += 2;
248  return Unit::Inch;
249  }
251  if( sizeLeft >= 3 && ch == 'm' && cptr[ 1 ] == 'i' && cptr[ 2 ] == 'l' && !isalnum( cptr[ 3 ] ))
252  {
253  m_token.pos += 3;
254  return Unit::Mil;
255  }
256 
257  if( sizeLeft >= 4 && ch == 't' && cptr[ 1 ] == 'h' && cptr[ 2 ] == 'o' && cptr[ 3 ] == 'u' && !isalnum( cptr[ 4 ] ))
258  {
259  m_token.pos += 4;
260  return Unit::Mil;
261  }
263  return Unit::Invalid;
264  };
265 
266  char ch;
267 
268  // Start processing of first/next token: Remove whitespace
269  for( ;; )
270  {
273  if( ch == ' ' )
274  m_token.pos++;
275  else
276  break;
277  }
279  Unit convertFrom;
280 
281  if( ch == 0 )
282  {
283  /* End of input */
284  }
285  else if( isdigit( ch ) || isDecimalSeparator( ch ))
286  {
287  // VALUE
288  extractNumber();
289  retval.token = VALUE;
290  retval.value.dValue = atof( m_token.token );
291  }
292  else if(( convertFrom = checkUnit()) != Unit::Invalid )
293  {
294  // UNIT
295  // Units are appended to a VALUE.
296  // Determine factor to default unit if unit for value is given.
297  // Example: Default is mm, unit is inch: factor is 25.4
298  // The factor is assigned to the terminal UNIT. The actual
299  // conversion is done within a parser action.
300  retval.token = UNIT;
302  {
303  switch( convertFrom )
304  {
305  case Unit::Inch :retval.value.dValue = 25.4; break;
306  case Unit::Mil :retval.value.dValue = 25.4 / 1000.0; break;
307  case Unit::Metric :retval.value.dValue = 1.0; break;
308  case Unit::Invalid :break;
309  }
310  }
311  else if( m_defaultUnits == Unit::Inch )
312  {
313  switch( convertFrom )
314  {
315  case Unit::Inch :retval.value.dValue = 1.0; break;
316  case Unit::Mil :retval.value.dValue = 1.0 / 1000.0; break;
317  case Unit::Metric :retval.value.dValue = 1.0 / 25.4; break;
318  case Unit::Invalid :break;
319  }
320  }
321  else if( m_defaultUnits == Unit::Mil )
322  {
323  switch( convertFrom )
324  {
325  case Unit::Inch :retval.value.dValue = 1.0 * 1000.0; break;
326  case Unit::Mil :retval.value.dValue = 1.0; break;
327  case Unit::Metric :retval.value.dValue = 1000.0 / 25.4; break;
328  case Unit::Invalid :break;
329  }
330  }
331  }
332  else if( isalpha( ch ))
333  {
334  // VAR
335  const char* cptr = &m_token.input[ m_token.pos ];
336  cptr++;
338  while( isalnum( *cptr ))
339  cptr++;
340 
341  retval.token = VAR;
342  size_t bytesToCopy = cptr - &m_token.input[ m_token.pos ];
343 
344  if( bytesToCopy >= sizeof( retval.value.text ))
345  bytesToCopy = sizeof( retval.value.text ) - 1;
346 
347  strncpy( retval.value.text, &m_token.input[ m_token.pos ], bytesToCopy );
348  retval.value.text[ bytesToCopy ] = 0;
349  m_token.pos += cptr - &m_token.input[ m_token.pos ];
350  }
351  else
352  {
353  // Single char tokens
354  switch( ch )
355  {
356  case '+' :retval.token = PLUS; break;
357  case '-' :retval.token = MINUS; break;
358  case '*' :retval.token = MULT; break;
359  case '/' :retval.token = DIVIDE; break;
360  case '(' :retval.token = PARENL; break;
361  case ')' :retval.token = PARENR; break;
362  case '=' :retval.token = ASSIGN; break;
363  case ';' :retval.token = SEMCOL; break;
364  default :m_parseError = true; break; /* invalid character */
365  }
366  m_token.pos++;
367  }
369  return retval;
370 }
371 
372 void NUMERIC_EVALUATOR::SetVar( const wxString& aString, double aValue )
373 {
374  m_varMap[ aString ] = aValue;
375 }
377 double NUMERIC_EVALUATOR::GetVar( const wxString& aString )
378 {
379  if( m_varMap[ aString ] )
380  return m_varMap[ aString ];
381  else
382  return 0.0;
383 }
std::map< wxString, double > m_varMap
#define ASSIGN
void SetVar(const wxString &aString, double aValue)
void Parse(void *yyp, int yymajor, ParseTOKENTYPE yyminor ParseARG_PDECL)
#define PARENR
struct NUMERIC_EVALUATOR::TokenStat m_token
#define MINUS
wxString OriginalText() const
#define SEMCOL
#define ENDS
#define PARENL
#define MULT
#define DIVIDE
void ParseFree(void *p, void(*freeProc)(void *))
#define UNIT
bool Process(const wxString &aString)
void parseSetResult(double)
void newString(const wxString &aString)
#define PLUS
NUMERIC_EVALUATOR(EDA_UNITS aUnits, bool aUseMils=false)
void * ParseAlloc(void *(*mallocProc)(size_t))
double GetVar(const wxString &aString)
#define VAR
#define VALUE
void parseError(const char *s)