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 
38 #ifdef __GNUC__
39 #pragma GCC diagnostic pop
40 #endif
41 
42 } /* namespace numEval */
43 
44 
45 #define VAR 1
46 #define ASSIGN 2
47 #define SEMCOL 3
48 #define PLUS 4
49 #define MINUS 5
50 #define UNIT 6
51 #define DIVIDE 7
52 #define MULT 8
53 #define ENDS 9
54 #define VALUE 10
55 #define PARENL 11
56 #define PARENR 12
57 
58 
60 {
61  struct lconv* lc = localeconv();
62  m_localeDecimalSeparator = *lc->decimal_point;
63 
64  m_parseError = false;
65  m_parseFinished = false;
66 
68 
69  switch( aUnits )
70  {
71  case INCHES:
72  if( aUseMils )
74  else
76  break;
78  break;
79  default:m_defaultUnits = Unit::Metric;
80  break;
81  }
82 }
83 
84 
86 {
88 
89  // Allow explicit call to destructor
90  m_parser = nullptr;
91 
92  Clear();
93 }
94 
95 
97 {
98  free( m_token.token );
99  m_token.token = nullptr;
100  m_token.input = nullptr;
101  m_parseError = true;
102  m_originalText = wxEmptyString;
103 }
106 void NUMERIC_EVALUATOR::parseError( const char* s )
107 {
108  m_parseError = true;
109 }
113 {
115 }
119 {
120  snprintf( m_token.token, m_token.OutLen, "%.10g", val );
121 }
122 
125 {
127 }
129 
130 bool NUMERIC_EVALUATOR::Process( const wxString& aString )
131 {
132  // Feed parser token after token until end of input.
134  newString( aString );
135  m_parseError = false;
137  Token tok;
139  if( aString.IsEmpty() )
140  {
141  m_parseFinished = true;
142  return true;
143  }
145  do
146  {
147  tok = getToken();
148  numEval::Parse( m_parser, tok.token, tok.value, this );
150  if( m_parseFinished || tok.token == ENDS )
151  {
152  // Reset parser by passing zero as token ID, value is ignored.
153  numEval::Parse( m_parser, 0, tok.value, this );
154  break;
155  }
156  } while( tok.token );
157 
158  return !m_parseError;
159 }
162 void NUMERIC_EVALUATOR::newString( const wxString& aString )
163 {
164  Clear();
166  m_originalText = aString;
168  m_token.token = reinterpret_cast<decltype( m_token.token )>( malloc( TokenStat::OutLen + 1 ) );
169  strcpy( m_token.token, "0" );
170  m_token.inputLen = aString.length();
171  m_token.pos = 0;
172  m_token.input = aString.mb_str();
175 }
177 
179 {
180  Token retval;
181  size_t idx;
183  retval.token = ENDS;
184  retval.value.dValue = 0;
186  if( m_token.token == nullptr )
187  return retval;
189  if( m_token.input == nullptr )
190  return retval;
192  if( m_token.pos >= m_token.inputLen )
193  return retval;
194 
195  auto isDecimalSeparator = [ & ]( char ch ) -> bool {
196  return ( ch == m_localeDecimalSeparator || ch == '.' || ch == ',' );
197  };
199  // Lambda: get value as string, store into clToken.token and update current index.
200  auto extractNumber = [ & ]() {
201  bool haveSeparator = false;
202  idx = 0;
203  auto ch = m_token.input[ m_token.pos ];
205  do
206  {
207  if( isDecimalSeparator( ch ) && haveSeparator )
208  break;
210  m_token.token[ idx++ ] = ch;
212  if( isDecimalSeparator( ch ))
213  haveSeparator = true;
216  } while( isdigit( ch ) || isDecimalSeparator( ch ));
218  m_token.token[ idx ] = 0;
219 
220  // Ensure that the systems decimal separator is used
221  for( int i = strlen( m_token.token ); i; i-- )
222  if( isDecimalSeparator( m_token.token[ i - 1 ] ))
224  };
225 
226  // Lamda: Get unit for current token.
227  // Valid units are ", in, mm, mil and thou. Returns Unit::Invalid otherwise.
228  auto checkUnit = [ this ]() -> Unit {
229  char ch = m_token.input[ m_token.pos ];
230 
231  if( ch == '"' )
232  {
234  return Unit::Inch;
235  }
236 
237  // Do not use strcasecmp() as it is not available on all platforms
238  const char* cptr = &m_token.input[ m_token.pos ];
239  const auto sizeLeft = m_token.inputLen - m_token.pos;
240 
241  if( sizeLeft >= 2 && ch == 'm' && cptr[ 1 ] == 'm' && !isalnum( cptr[ 2 ] ))
242  {
243  m_token.pos += 2;
244  return Unit::Metric;
245  }
246 
247  if( sizeLeft >= 2 && ch == 'i' && cptr[ 1 ] == 'n' && !isalnum( cptr[ 2 ] ))
248  {
249  m_token.pos += 2;
250  return Unit::Inch;
251  }
252 
253  if( sizeLeft >= 3 && ch == 'm' && cptr[ 1 ] == 'i' && cptr[ 2 ] == 'l' && !isalnum( cptr[ 3 ] ))
254  {
255  m_token.pos += 3;
256  return Unit::Mil;
257  }
259  if( sizeLeft >= 4 && ch == 't' && cptr[ 1 ] == 'h' && cptr[ 2 ] == 'o' && cptr[ 3 ] == 'u' && !isalnum( cptr[ 4 ] ))
260  {
261  m_token.pos += 4;
262  return Unit::Mil;
263  }
264 
265  return Unit::Invalid;
266  };
267 
268  char ch;
270  // Start processing of first/next token: Remove whitespace
271  for( ;; )
272  {
273  ch = m_token.input[ m_token.pos ];
274 
275  if( ch == ' ' )
277  else
278  break;
279  }
280 
281  Unit convertFrom;
282 
283  if( ch == 0 )
284  {
285  /* End of input */
286  }
287  else if( isdigit( ch ) || isDecimalSeparator( ch ))
288  {
289  // VALUE
290  extractNumber();
291  retval.token = VALUE;
292  retval.value.dValue = atof( m_token.token );
293  }
294  else if(( convertFrom = checkUnit()) != Unit::Invalid )
295  {
296  // UNIT
297  // Units are appended to a VALUE.
298  // Determine factor to default unit if unit for value is given.
299  // Example: Default is mm, unit is inch: factor is 25.4
300  // The factor is assigned to the terminal UNIT. The actual
301  // conversion is done within a parser action.
302  retval.token = UNIT;
304  {
305  switch( convertFrom )
306  {
307  case Unit::Inch :retval.value.dValue = 25.4; break;
308  case Unit::Mil :retval.value.dValue = 25.4 / 1000.0; break;
309  case Unit::Metric :retval.value.dValue = 1.0; break;
310  case Unit::Invalid :break;
311  }
312  }
314  {
315  switch( convertFrom )
316  {
317  case Unit::Inch :retval.value.dValue = 1.0; break;
318  case Unit::Mil :retval.value.dValue = 1.0 / 1000.0; break;
319  case Unit::Metric :retval.value.dValue = 1.0 / 25.4; break;
320  case Unit::Invalid :break;
321  }
322  }
323  else if( m_defaultUnits == Unit::Mil )
324  {
325  switch( convertFrom )
326  {
327  case Unit::Inch :retval.value.dValue = 1.0 * 1000.0; break;
328  case Unit::Mil :retval.value.dValue = 1.0; break;
329  case Unit::Metric :retval.value.dValue = 1000.0 / 25.4; break;
330  case Unit::Invalid :break;
331  }
332  }
333  }
334  else if( isalpha( ch ))
335  {
336  // VAR
337  const char* cptr = &m_token.input[ m_token.pos ];
338  cptr++;
339 
340  while( isalnum( *cptr ))
341  cptr++;
342 
343  retval.token = VAR;
344  size_t bytesToCopy = cptr - &m_token.input[ m_token.pos ];
345 
346  if( bytesToCopy >= sizeof( retval.value.text ))
347  bytesToCopy = sizeof( retval.value.text ) - 1;
348 
349  strncpy( retval.value.text, &m_token.input[ m_token.pos ], bytesToCopy );
350  retval.value.text[ bytesToCopy ] = 0;
351  m_token.pos += cptr - &m_token.input[ m_token.pos ];
352  }
353  else
354  {
355  // Single char tokens
356  switch( ch )
357  {
358  case '+' :retval.token = PLUS; break;
359  case '-' :retval.token = MINUS; break;
360  case '*' :retval.token = MULT; break;
361  case '/' :retval.token = DIVIDE; break;
362  case '(' :retval.token = PARENL; break;
363  case ')' :retval.token = PARENR; break;
364  case '=' :retval.token = ASSIGN; break;
365  case ';' :retval.token = SEMCOL; break;
366  default :m_parseError = true; break; /* invalid character */
367  }
369  }
371  return retval;
372 }
373 
374 void NUMERIC_EVALUATOR::SetVar( const wxString& aString, double aValue )
375 {
376  m_varMap[ aString ] = aValue;
377 }
378 
379 double NUMERIC_EVALUATOR::GetVar( const wxString& aString )
380 {
381  if( m_varMap[ aString ] )
382  return m_varMap[ aString ];
383  else
384  return 0.0;
385 }
NUMERIC_EVALUATOR(EDA_UNITS_T aUnits, bool aUseMils=false)
#define ASSIGN
void Parse(void *yyp, int yymajor, ParseTOKENTYPE yyminorParseARG_PDECL)
#define PARENR
#define MINUS
void newString(const wxString &aString)
#define SEMCOL
double GetVar(const wxString &aString)
void SetVar(const wxString &aString, double aValue)
#define ENDS
wxString OriginalText() const
#define PARENL
#define MULT
struct numEval::NUMERIC_EVALUATOR::TokenStat m_token
#define DIVIDE
void ParseFree(void *p, void(*freeProc)(void *))
bool Process(const wxString &aString)
#define UNIT
std::map< wxString, double > m_varMap
void parseError(const char *s)
#define PLUS
size_t i
Definition: json11.cpp:597
#define VAR
void * ParseAlloc(void *(*mallocProc)(YYMALLOCARGTYPE))
#define VALUE