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, [email protected]
5 * Copyright (C) 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 <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{
49 struct lconv* lc = localeconv();
50 m_localeDecimalSeparator = *lc->decimal_point;
51
52 m_parseError = false;
53 m_parseFinished = false;
54
55 m_parser = numEval::ParseAlloc( malloc );
56
57 switch( aUnits )
58 {
62 default: m_defaultUnits = Unit::MM; break;
63 }
64}
65
66
68{
69 numEval::ParseFree( m_parser, free );
70
71 // Allow explicit call to destructor
72 m_parser = nullptr;
73
74 Clear();
75}
76
77
79{
80 free( m_token.token );
81 m_token.token = nullptr;
82 m_token.input = nullptr;
83 m_parseError = true;
84 m_originalText = wxEmptyString;
85}
86
87
88void NUMERIC_EVALUATOR::parseError( const char* s )
89{
90 m_parseError = true;
91}
92
93
95{
96 m_parseFinished = true;
97}
98
99
101{
102 if( std::isnan( val ) )
103 {
104 // Naively printing this with %g produces "nan" on some platforms
105 // and "-nan(ind)" on others (e.g. MSVC). So force a "standard" string.
106 snprintf( m_token.token, m_token.OutLen, "%s", "NaN" );
107 }
108 else
109 {
110 // Can be printed as a floating point
111 // Warning: DO NOT use a format like %f or %g, because they can create issues.
112 // especially %g can generate an exponent, incompatible with UNIT_BINDER
113 // Use the optimized Double2Str
114 snprintf( m_token.token, m_token.OutLen, "%s", Double2Str( val ).c_str() );
115 }
116}
117
118
120{
121 return m_originalText;
122}
123
124
125bool NUMERIC_EVALUATOR::Process( const wxString& aString )
126{
127 // Feed parser token after token until end of input.
128
129 newString( aString );
130 m_parseError = false;
131 m_parseFinished = false;
132 Token tok;
133
134 if( aString.IsEmpty() )
135 {
136 m_parseFinished = true;
137 return true;
138 }
139
140 do
141 {
142 tok = getToken();
143 numEval::Parse( m_parser, tok.token, tok.value, this );
144
145 if( m_parseFinished || tok.token == ENDS )
146 {
147 // Reset parser by passing zero as token ID, value is ignored.
148 numEval::Parse( m_parser, 0, tok.value, this );
149 break;
150 }
151 } while( tok.token );
152
153 return !m_parseError;
154}
155
156
157void NUMERIC_EVALUATOR::newString( const wxString& aString )
158{
159 Clear();
160
161 m_originalText = aString;
162
163 m_token.token = reinterpret_cast<decltype( m_token.token )>( malloc( TokenStat::OutLen + 1 ) );
164 strcpy( m_token.token, "0" );
165 m_token.inputLen = aString.length();
166 m_token.pos = 0;
167 m_token.input = aString.mb_str();
168
169 m_parseFinished = false;
170}
171
172
174{
175 Token retval;
176 size_t idx;
177
178 retval.token = ENDS;
179 retval.value.dValue = 0;
180 retval.value.valid = false;
181 retval.value.text[0] = 0;
182
183 if( m_token.token == nullptr )
184 return retval;
185
186 if( m_token.input == nullptr )
187 return retval;
188
189 if( m_token.pos >= m_token.inputLen )
190 return retval;
191
192 auto isDecimalSeparator = [ & ]( char ch ) -> bool {
193 return ( ch == m_localeDecimalSeparator || ch == '.' || ch == ',' );
194 };
195
196 // Lambda: get value as string, store into clToken.token and update current index.
197 auto extractNumber = [ & ]() {
198 bool haveSeparator = false;
199 idx = 0;
200 auto ch = m_token.input[ m_token.pos ];
201
202 do
203 {
204 if( isDecimalSeparator( ch ) && haveSeparator )
205 break;
206
207 m_token.token[ idx++ ] = ch;
208
209 if( isDecimalSeparator( ch ) )
210 haveSeparator = true;
211
212 ch = m_token.input[ ++m_token.pos ];
213 } while( isdigit( ch ) || isDecimalSeparator( ch ) );
214
215 m_token.token[ idx ] = 0;
216
217 // Ensure that the systems decimal separator is used
218 for( int i = strlen( m_token.token ); i; i-- )
219 {
220 if( isDecimalSeparator( m_token.token[ i - 1 ] ) )
222 }
223 };
224
225 // Lamda: Get unit for current token.
226 // Valid units are ", in, mm, mil and thou. Returns Unit::Invalid otherwise.
227 auto checkUnit = [ this ]() -> Unit {
228 char ch = m_token.input[ m_token.pos ];
229
230 if( ch == '"' )
231 {
232 m_token.pos++;
233 return Unit::Inch;
234 }
235
236 // Do not use strcasecmp() as it is not available on all platforms
237 const char* cptr = &m_token.input[ m_token.pos ];
238 const auto sizeLeft = m_token.inputLen - m_token.pos;
239
240 if( sizeLeft >= 2 && ch == 'm' && cptr[ 1 ] == 'm' && !isalnum( cptr[ 2 ] ) )
241 {
242 m_token.pos += 2;
243 return Unit::MM;
244 }
245
246 if( sizeLeft >= 2 && ch == 'c' && cptr[ 1 ] == 'm' && !isalnum( cptr[ 2 ] ) )
247 {
248 m_token.pos += 2;
249 return Unit::CM;
250 }
251
252 if( sizeLeft >= 2 && ch == 'i' && cptr[ 1 ] == 'n' && !isalnum( cptr[ 2 ] ) )
253 {
254 m_token.pos += 2;
255 return Unit::Inch;
256 }
257
258 if( sizeLeft >= 3 && ch == 'm' && cptr[ 1 ] == 'i' && cptr[ 2 ] == 'l'
259 && !isalnum( cptr[ 3 ] ) )
260 {
261 m_token.pos += 3;
262 return Unit::Mil;
263 }
264
265 if( sizeLeft >= 4 && ch == 't' && cptr[ 1 ] == 'h' && cptr[ 2 ] == 'o'
266 && cptr[ 3 ] == 'u' && !isalnum( cptr[ 4 ] ) )
267 {
268 m_token.pos += 4;
269 return Unit::Mil;
270 }
271
272 return Unit::Invalid;
273 };
274
275 char ch;
276
277 // Start processing of first/next token: Remove whitespace
278 for( ;; )
279 {
280 ch = m_token.input[ m_token.pos ];
281
282 if( ch == ' ' )
283 m_token.pos++;
284 else
285 break;
286 }
287
288 Unit convertFrom;
289
290 if( ch == 0 )
291 {
292 /* End of input */
293 }
294 else if( isdigit( ch ) || isDecimalSeparator( ch ))
295 {
296 // VALUE
297 extractNumber();
298 retval.token = VALUE;
299 retval.value.dValue = atof( m_token.token );
300 }
301 else if(( convertFrom = checkUnit()) != Unit::Invalid )
302 {
303 // UNIT
304 // Units are appended to a VALUE.
305 // Determine factor to default unit if unit for value is given.
306 // Example: Default is mm, unit is inch: factor is 25.4
307 // The factor is assigned to the terminal UNIT. The actual
308 // conversion is done within a parser action.
309 retval.token = UNIT;
310
311 if( m_defaultUnits == Unit::MM )
312 {
313 switch( convertFrom )
314 {
315 case Unit::Inch: retval.value.dValue = 25.4; break;
316 case Unit::Mil: retval.value.dValue = 25.4 / 1000.0; break;
317 case Unit::MM: retval.value.dValue = 1.0; break;
318 case Unit::CM: retval.value.dValue = 10.0; break;
319 case Unit::Invalid: break;
320 }
321 }
322 else if( m_defaultUnits == Unit::Inch )
323 {
324 switch( convertFrom )
325 {
326 case Unit::Inch: retval.value.dValue = 1.0; break;
327 case Unit::Mil: retval.value.dValue = 1.0 / 1000.0; break;
328 case Unit::MM: retval.value.dValue = 1.0 / 25.4; break;
329 case Unit::CM: retval.value.dValue = 1.0 / 2.54; break;
330 case Unit::Invalid: break;
331 }
332 }
333 else if( m_defaultUnits == Unit::Mil )
334 {
335 switch( convertFrom )
336 {
337 case Unit::Inch: retval.value.dValue = 1.0 * 1000.0; break;
338 case Unit::Mil: retval.value.dValue = 1.0; break;
339 case Unit::MM: retval.value.dValue = 1000.0 / 25.4; break;
340 case Unit::CM: retval.value.dValue = 1000.0 / 2.54; break;
341 case Unit::Invalid: break;
342 }
343 }
344 }
345 else if( isalpha( ch ))
346 {
347 // VAR
348 const char* cptr = &m_token.input[ m_token.pos ];
349 cptr++;
350
351 while( isalnum( *cptr ))
352 cptr++;
353
354 retval.token = VAR;
355 size_t bytesToCopy = cptr - &m_token.input[ m_token.pos ];
356
357 if( bytesToCopy >= sizeof( retval.value.text ) )
358 bytesToCopy = sizeof( retval.value.text ) - 1;
359
360 strncpy( retval.value.text, &m_token.input[ m_token.pos ], bytesToCopy );
361 retval.value.text[ bytesToCopy ] = 0;
362 m_token.pos += cptr - &m_token.input[ m_token.pos ];
363 }
364 else
365 {
366 // Single char tokens
367 switch( ch )
368 {
369 case '+': retval.token = PLUS; break;
370 case '-': retval.token = MINUS; break;
371 case '*': retval.token = MULT; break;
372 case '/': retval.token = DIVIDE; break;
373 case '(': retval.token = PARENL; break;
374 case ')': retval.token = PARENR; break;
375 case '=': retval.token = ASSIGN; break;
376 case ';': retval.token = SEMCOL; break;
377 default: m_parseError = true; break; /* invalid character */
378 }
379
380 m_token.pos++;
381 }
382
383 if( !m_parseError )
384 retval.value.valid = true;
385
386 return retval;
387}
388
389void NUMERIC_EVALUATOR::SetVar( const wxString& aString, double aValue )
390{
391 m_varMap[ aString ] = aValue;
392}
393
394double NUMERIC_EVALUATOR::GetVar( const wxString& aString )
395{
396 if( m_varMap[ aString ] )
397 return m_varMap[ aString ];
398 else
399 return 0.0;
400}
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 SetVar(const wxString &aString, double aValue)
bool Process(const wxString &aString)
std::map< wxString, double > m_varMap
EDA_UNITS
Definition: eda_units.h:39
PARSE_RESULT Parse(const wxString &aString, NOTATION aNotation=NOTATION::SI, SIM_VALUE::TYPE aValueType=SIM_VALUE::TYPE_FLOAT)
Definition: sim_value.cpp:189
std::string Double2Str(double aValue)
Print a float number without using scientific notation and no trailing 0 We want to avoid scientific ...
numEval::TokenType value