Skip to content

Commit 7910b1a

Browse files
authored
Optionally allow real numbers with no leading zeroes. (#55)
* Optionall allow reals with no leading zeroes.
1 parent 412f304 commit 7910b1a

File tree

3 files changed

+32
-1
lines changed

3 files changed

+32
-1
lines changed

.gitignore

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,4 +9,5 @@
99
*.nupkg
1010
*.dll
1111
*.targets
12-
project.lock.json
12+
project.lock.json
13+
.idea/

src/NReco.LambdaParser.Tests/LambdaParserTests.cs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -216,6 +216,22 @@ public void EvalCachePerf() {
216216
Console.WriteLine("10000 iterations: {0}", sw.Elapsed);
217217
}
218218

219+
[Fact]
220+
public void AllowNoLeadingZeroesFalse()
221+
{
222+
var parser = new LambdaParser { AllowNoLeadingZeroes = false };
223+
var exception = Assert.Throws<LambdaParserException>(() => parser.Eval(".6", new Dictionary<string, object>()));
224+
Assert.Equal(".6", exception.Expression);
225+
Assert.Equal(0, exception.Index);
226+
}
227+
228+
[Fact]
229+
public void AllowNoLeadingZeroesTrue()
230+
{
231+
var parser = new LambdaParser { AllowNoLeadingZeroes = true };
232+
var result = parser.Eval(".6", new Dictionary<string, object>());
233+
Assert.Equal(0.6m, result);
234+
}
219235

220236
public class TestBaseClass
221237
{

src/NReco.LambdaParser/Linq/LambdaParser.cs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,11 @@ public class LambdaParser {
4444
/// Gets or sets whether LambdaParser should use the cache for parsed expressions.
4545
/// </summary>
4646
public bool UseCache { get; set; }
47+
48+
/// <summary>
49+
/// Gets or sets whether LambdaParser should allow numbers without leading zeroes.
50+
/// </summary>
51+
public bool AllowNoLeadingZeroes { get; set; }
4752

4853
/// <summary>
4954
/// Allows usage of "=" for equality comparison (in addition to "=="). False by default.
@@ -72,6 +77,7 @@ public class LambdaParser {
7277

7378
public LambdaParser() {
7479
UseCache = true;
80+
AllowNoLeadingZeroes = false;
7581
AllowSingleEqualSign = false;
7682
AllowVars = false;
7783
Comparer = ValueComparer.Instance;
@@ -191,6 +197,14 @@ protected Lexem ReadLexem(string s, int startIdx) {
191197
if (Array.IndexOf(delimiters, s[lexem.End]) >= 0) {
192198
if (lexem.Type == LexemType.Unknown) {
193199
lexem.End++;
200+
if (AllowNoLeadingZeroes
201+
&& lexem.Start == lexem.End - 1
202+
&& s[lexem.Start] == '.'
203+
&& lexem.End < s.Length
204+
&& char.IsDigit(s[lexem.End])) {
205+
lexem.Type = LexemType.NumberConstant;
206+
continue;
207+
}
194208
lexem.Type = LexemType.Delimiter;
195209
return lexem;
196210
}

0 commit comments

Comments
 (0)