KiCad PCB EDA Suite
Loading...
Searching...
No Matches
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, [email protected]
5 * Copyright (C) 2021-2022 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 <string_utils.h>
23
24/* The (generated) lemon parser is written in C.
25 * In order to keep its symbol from the global namespace include the parser code with
26 * a C++ namespace.
27 */
28namespace numEval
29{
30
31#ifdef __GNUC__
32#pragma GCC diagnostic push
33#pragma GCC diagnostic ignored "-Wunused-variable"
34#pragma GCC diagnostic ignored "-Wsign-compare"
35#endif
36
37#include <libeval/grammar.c>
38#include <libeval/grammar.h>
39
40#ifdef __GNUC__
41#pragma GCC diagnostic pop
42#endif
43
44} /* namespace numEval */
45
46
48{
50
51 m_parseError = false;
52 m_parseFinished = false;
53
54 m_parser = numEval::ParseAlloc( malloc );
55
56 SetDefaultUnits( aUnits );
57}
58
59
61{
62 numEval::ParseFree( m_parser, free );
63
64 // Allow explicit call to destructor
65 m_parser = nullptr;
66
67 Clear();
68}
69
70
72{
73 delete[] m_token.token;
74 m_token.token = nullptr;
75 m_token.input = nullptr;
76 m_parseError = true;
77 m_originalText = wxEmptyString;
78}
79
80
82{
83 switch( aUnits )
84 {
85 case EDA_UNITS::MILLIMETRES: m_defaultUnits = Unit::MM; break;
86 case EDA_UNITS::MILS: m_defaultUnits = Unit::Mil; break;
87 case EDA_UNITS::INCHES: m_defaultUnits = Unit::Inch; break;
88 case EDA_UNITS::DEGREES: m_defaultUnits = Unit::Degrees; break;
89 case EDA_UNITS::UNSCALED: m_defaultUnits = Unit::SI; break;
90 default: m_defaultUnits = Unit::MM; break;
91 }
92}
93
94
96{
97 struct lconv* lc = localeconv();
98 m_localeDecimalSeparator = *lc->decimal_point;
99}
100
101
102// NOT UNUSED. Called by LEMON grammar.
103void NUMERIC_EVALUATOR::parseError( const char* s )
104{
105 m_parseError = true;
106}
107
108
109// NOT UNUSED. Called by LEMON grammar.
111{
112 m_parseFinished = true;
113}
114
115
116// NOT UNUSED. Called by LEMON grammar.
118{
119 if( std::isnan( val ) )
120 {
121 // Naively printing this with %g produces "nan" on some platforms
122 // and "-nan(ind)" on others (e.g. MSVC). So force a "standard" string.
123 snprintf( m_token.token, m_token.outputLen, "%s", "NaN" );
124 }
125 else
126 {
127 // Can be printed as a floating point
128 // Warning: DO NOT use a format like %f or %g, because they can create issues.
129 // especially %g can generate an exponent, incompatible with UNIT_BINDER
130 // Use the optimized UIDouble2Str
131 snprintf( m_token.token, m_token.outputLen, "%s", UIDouble2Str( val ).c_str() );
132 }
133}
134
135
137{
138 return m_originalText;
139}
140
141
142bool NUMERIC_EVALUATOR::Process( const wxString& aString )
143{
144 // Feed parser token after token until end of input.
145
146 newString( aString );
147 m_parseError = false;
148 m_parseFinished = false;
149 Token tok;
150
151 if( aString.IsEmpty() )
152 {
153 m_parseFinished = true;
154 return true;
155 }
156
157 do
158 {
159 tok = getToken();
160 numEval::Parse( m_parser, tok.token, tok.value, this );
161
162 if( m_parseFinished || tok.token == ENDS )
163 {
164 // Reset parser by passing zero as token ID, value is ignored.
165 numEval::Parse( m_parser, 0, tok.value, this );
166 break;
167 }
168 } while( tok.token );
169
170 return !m_parseError;
171}
172
173
174void NUMERIC_EVALUATOR::newString( const wxString& aString )
175{
176 Clear();
177
178 m_originalText = aString;
179 m_token.input = aString.mb_str();
180 m_token.inputLen = strlen( m_token.input );
181 m_token.outputLen = std::max<std::size_t>( 64, m_token.inputLen + 1 );
182 m_token.pos = 0;
183 m_token.token = new char[m_token.outputLen]();
184 m_token.token[0] = '0';
185
186 m_parseFinished = false;
187}
188
189
191{
192 Token retval;
193 size_t idx;
194
195 retval.token = ENDS;
196 retval.value.dValue = 0;
197 retval.value.valid = false;
198 retval.value.text[0] = 0;
199
200 if( m_token.token == nullptr )
201 return retval;
202
203 if( m_token.input == nullptr )
204 return retval;
205
206 if( m_token.pos >= m_token.inputLen )
207 return retval;
208
209 // Support for old school decimal separators (ie: "2K2")
210 auto isOldSchoolDecimalSeparator =
211 []( char ch, double* siScaler ) -> bool
212 {
213 switch( ch )
214 {
215 case 'a': *siScaler = 1.0e-18; return true;
216 case 'f': *siScaler = 1.0e-15; return true;
217 case 'p': *siScaler = 1.0e-12; return true;
218 case 'n': *siScaler = 1.0e-9; return true;
219 case 'u': *siScaler = 1.0e-6; return true;
220 case 'm': *siScaler = 1.0e-3; return true;
221 case 'k':
222 case 'K': *siScaler = 1.0e3; return true;
223 case 'M': *siScaler = 1.0e6; return true;
224 case 'G': *siScaler = 1.0e9; return true;
225 case 'T': *siScaler = 1.0e12; return true;
226 case 'P': *siScaler = 1.0e15; return true;
227 case 'E': *siScaler = 1.0e18; return true;
228 default: return false;
229 }
230 };
231
232 auto isDecimalSeparator =
233 [&]( char ch ) -> bool
234 {
235 double dummy;
236
237 if( ch == m_localeDecimalSeparator || ch == '.' || ch == ',' )
238 return true;
239
240 if( m_defaultUnits == Unit::SI && isOldSchoolDecimalSeparator( ch, &dummy ) )
241 return true;
242
243 return false;
244 };
245
246 // Lambda: get value as string, store into clToken.token and update current index.
247 auto extractNumber =
248 [&]( double* aScaler )
249 {
250 bool haveSeparator = false;
251 double siScaler = 1.0;
252 char ch = m_token.input[ m_token.pos ];
253
254 idx = 0;
255
256 do
257 {
258 if( isDecimalSeparator( ch ) )
259 {
260 if( haveSeparator )
261 break;
262 else
263 haveSeparator = true;
264
265 if( isOldSchoolDecimalSeparator( ch, &siScaler ) )
266 *aScaler = siScaler;
267
269 }
270 else
271 {
272 m_token.token[ idx++ ] = ch;
273 }
274
275 ch = m_token.input[ ++m_token.pos ];
276 } while( isdigit( ch ) || isDecimalSeparator( ch ) );
277
278 m_token.token[ idx ] = 0;
279 };
280
281 // Lamda: Get unit for current token.
282 // Valid units are ", in, um, cm, mm, mil and thou. Returns Unit::Invalid otherwise.
283 auto checkUnit =
284 [&]( double* siScaler ) -> Unit
285 {
286 char ch = m_token.input[ m_token.pos ];
287
288 if( ch == '"' )
289 {
290 m_token.pos++;
291 return Unit::Inch;
292 }
293
294 // Do not use strcasecmp() as it is not available on all platforms
295 const char* cptr = &m_token.input[ m_token.pos ];
296 const auto sizeLeft = m_token.inputLen - m_token.pos;
297
298 // We should really give this unicode support
299 if( sizeLeft >= 2 && ch == '\xC2' && cptr[1] == '\xB0' )
300 {
301 m_token.pos += 2;
302 return Unit::Degrees;
303 }
304
305 // Ideally we should also handle the unicode characters that can be used for micro,
306 // but unicode handling in this tokenizer doesn't work.
307 // (e.g. add support for μm (µ is MICRO SIGN), µm (µ is GREEK SMALL LETTER MU) later)
308 if( sizeLeft >= 2 && ch == 'u' && cptr[ 1 ] == 'm' && !isalnum( cptr[ 2 ] ) )
309 {
310 m_token.pos += 2;
311 return Unit::UM;
312 }
313
314 if( sizeLeft >= 2 && ch == 'm' && cptr[ 1 ] == 'm' && !isalnum( cptr[ 2 ] ) )
315 {
316 m_token.pos += 2;
317 return Unit::MM;
318 }
319
320 if( sizeLeft >= 2 && ch == 'c' && cptr[ 1 ] == 'm' && !isalnum( cptr[ 2 ] ) )
321 {
322 m_token.pos += 2;
323 return Unit::CM;
324 }
325
326 if( sizeLeft >= 2 && ch == 'i' && cptr[ 1 ] == 'n' && !isalnum( cptr[ 2 ] ) )
327 {
328 m_token.pos += 2;
329 return Unit::Inch;
330 }
331
332 if( sizeLeft >= 3 && ch == 'm' && cptr[ 1 ] == 'i' && cptr[ 2 ] == 'l'
333 && !isalnum( cptr[ 3 ] ) )
334 {
335 m_token.pos += 3;
336 return Unit::Mil;
337 }
338
339 if( sizeLeft >= 4 && ch == 't' && cptr[ 1 ] == 'h' && cptr[ 2 ] == 'o'
340 && cptr[ 3 ] == 'u' && !isalnum( cptr[ 4 ] ) )
341 {
342 m_token.pos += 4;
343 return Unit::Mil;
344 }
345
346 if( m_defaultUnits == Unit::SI && sizeLeft >= 1
347 && isOldSchoolDecimalSeparator( ch, siScaler ) )
348 {
349 m_token.pos++;
350 return Unit::SI;
351 }
352
353 return Unit::Invalid;
354 };
355
356 char ch;
357
358 // Start processing of first/next token: Remove whitespace
359 for( ;; )
360 {
361 ch = m_token.input[ m_token.pos ];
362
363 if( ch == ' ' )
364 m_token.pos++;
365 else
366 break;
367 }
368
369 double siScaler = 1.0;
370 Unit convertFrom = Unit::Invalid;
371
372 if( ch == 0 )
373 {
374 /* End of input */
375 }
376 else if( isdigit( ch ) || isDecimalSeparator( ch ) )
377 {
378 // VALUE
379 extractNumber( &siScaler );
380 retval.token = VALUE;
381 retval.value.dValue = atof( m_token.token ) * siScaler;
382 }
383 else if( ( convertFrom = checkUnit( &siScaler ) ) != Unit::Invalid )
384 {
385 // UNIT
386 // Units are appended to a VALUE.
387 // Determine factor to default unit if unit for value is given.
388 // Example: Default is mm, unit is inch: factor is 25.4
389 // The factor is assigned to the terminal UNIT. The actual
390 // conversion is done within a parser action.
391 retval.token = UNIT;
392
393 if( m_defaultUnits == Unit::MM )
394 {
395 switch( convertFrom )
396 {
397 case Unit::Inch: retval.value.dValue = 25.4; break;
398 case Unit::Mil: retval.value.dValue = 25.4 / 1000.0; break;
399 case Unit::UM: retval.value.dValue = 1 / 1000.0; break;
400 case Unit::MM: retval.value.dValue = 1.0; break;
401 case Unit::CM: retval.value.dValue = 10.0; break;
402 default:
403 case Unit::Invalid: break;
404 }
405 }
406 else if( m_defaultUnits == Unit::Inch )
407 {
408 switch( convertFrom )
409 {
410 case Unit::Inch: retval.value.dValue = 1.0; break;
411 case Unit::Mil: retval.value.dValue = 1.0 / 1000.0; break;
412 case Unit::UM: retval.value.dValue = 1.0 / 25400.0; break;
413 case Unit::MM: retval.value.dValue = 1.0 / 25.4; break;
414 case Unit::CM: retval.value.dValue = 1.0 / 2.54; break;
415 default:
416 case Unit::Invalid: break;
417 }
418 }
419 else if( m_defaultUnits == Unit::Mil )
420 {
421 switch( convertFrom )
422 {
423 case Unit::Inch: retval.value.dValue = 1.0 * 1000.0; break;
424 case Unit::Mil: retval.value.dValue = 1.0; break;
425 case Unit::UM: retval.value.dValue = 1.0 / 25.4; break;
426 case Unit::MM: retval.value.dValue = 1000.0 / 25.4; break;
427 case Unit::CM: retval.value.dValue = 1000.0 / 2.54; break;
428 default:
429 case Unit::Invalid: break;
430 }
431 }
432 else if( m_defaultUnits == Unit::Degrees && convertFrom == Unit::Degrees )
433 {
434 retval.value.dValue = 1.0;
435 }
436 else if( m_defaultUnits == Unit::SI )
437 {
438 retval.value.dValue = siScaler;
439 }
440 }
441 else if( isalpha( ch ) )
442 {
443 // VAR
444 const char* cptr = &m_token.input[ m_token.pos ];
445 cptr++;
446
447 while( isalnum( *cptr ) )
448 cptr++;
449
450 retval.token = VAR;
451 size_t bytesToCopy = cptr - &m_token.input[ m_token.pos ];
452
453 if( bytesToCopy >= sizeof( retval.value.text ) )
454 bytesToCopy = sizeof( retval.value.text ) - 1;
455
456 strncpy( retval.value.text, &m_token.input[ m_token.pos ], bytesToCopy );
457 retval.value.text[ bytesToCopy ] = 0;
458 m_token.pos += cptr - &m_token.input[ m_token.pos ];
459 }
460 else
461 {
462 // Single char tokens
463 switch( ch )
464 {
465 case '+': retval.token = PLUS; break;
466 case '-': retval.token = MINUS; break;
467 case '*': retval.token = MULT; break;
468 case '/': retval.token = DIVIDE; break;
469 case '(': retval.token = PARENL; break;
470 case ')': retval.token = PARENR; break;
471 case '=': retval.token = ASSIGN; break;
472 case ';': retval.token = SEMCOL; break;
473 default: m_parseError = true; break; /* invalid character */
474 }
475
476 m_token.pos++;
477 }
478
479 if( !m_parseError )
480 retval.value.valid = true;
481
482 return retval;
483}
484
485void NUMERIC_EVALUATOR::SetVar( const wxString& aString, double aValue )
486{
487 m_varMap[ aString ] = aValue;
488}
489
490double NUMERIC_EVALUATOR::GetVar( const wxString& aString )
491{
492 auto it = m_varMap.find( aString );
493
494 if( it != m_varMap.end() )
495 {
496 return it->second;
497 }
498 else
499 {
500 m_parseError = true;
501 return 0.0;
502 }
503}
void parseSetResult(double)
wxString OriginalText() const
struct NUMERIC_EVALUATOR::TokenStat m_token
void newString(const wxString &aString)
void parseError(const char *s)
double GetVar(const wxString &aString)
NUMERIC_EVALUATOR(EDA_UNITS aUnits)
void SetDefaultUnits(EDA_UNITS aUnits)
void SetVar(const wxString &aString, double aValue)
bool Process(const wxString &aString)
std::map< wxString, double > m_varMap
EDA_UNITS
Definition: eda_units.h:46
std::vector< FAB_LAYER_COLOR > dummy
std::string UIDouble2Str(double aValue)
Print a float number without using scientific notation and no trailing 0 We want to avoid scientific ...
numEval::TokenType value