Skip to content

Commit

Permalink
Make whitespace skipping explicit when tokenizing expressions
Browse files Browse the repository at this point in the history
This prevents some invalid expressions from being parsed - for example, whitespace isn't valid in identifiers
  • Loading branch information
coderbot16 committed Sep 11, 2021
1 parent 66acab6 commit 689fd0d
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 4 deletions.
7 changes: 4 additions & 3 deletions src/main/java/kroppeb/stareval/parser/StringReader.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import kroppeb.stareval.exception.UnexpectedCharacterException;

/**
* A class to facilitate the reading of strings, will completely ignore all spaces.
* A class to facilitate the reading of strings.
*/
public class StringReader {
/**
Expand Down Expand Up @@ -47,6 +47,9 @@ private void advanceOneCharacter() {
this.nextIndex++;
}

/**
* Skips all whitespace characters until a non-whitespace character is encountered.
*/
public void skipWhitespace() {
while (this.nextIndex < this.string.length() && this.string.charAt(this.nextIndex) == ' ') {
this.nextIndex++;
Expand All @@ -73,7 +76,6 @@ public void skipOneCharacter() {
public char read() {
char current = this.peek();
this.skipOneCharacter();
this.skipWhitespace();
return current;
}

Expand Down Expand Up @@ -106,7 +108,6 @@ public boolean tryRead(char c) {
}

this.skipOneCharacter();
this.skipWhitespace();
return true;
}

Expand Down
8 changes: 8 additions & 0 deletions src/main/java/kroppeb/stareval/parser/Tokenizer.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,20 @@ static Expression parseInternal(StringReader input, ParserOptions options) throw
ParserOptions.TokenRules tokenRules = options.getTokenRules();

while (input.canRead()) {
input.skipWhitespace();

if (!input.canRead()) {
break;
}

char c = input.read();

if (tokenRules.isIdStart(c)) {
final String id = readWhile(input, tokenRules::isIdPart);
stack.visitId(id);
} else if (c == '.' && stack.canReadAccess()) {
input.skipWhitespace();

if (input.canRead()) {
char start = input.read();

Expand Down
5 changes: 4 additions & 1 deletion src/test/resources/shouldBeAbleToBeParsed.csv
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,7 @@ a * b / c % d
a + b - c
a == b && b != c || c < d || d >= e || e <= f && f > h
a + b * c - d % r * f * f / f - u + u

test.field
test. field
test .field
test . field
1 change: 1 addition & 0 deletions src/test/resources/shouldNotBeAbleToBeParsed.csv
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,4 @@ stone,
,5
5,
5+,
spaces in identifiers are not valid

0 comments on commit 689fd0d

Please sign in to comment.