Skip to content

java: Optimize Location #385

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Mar 30, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ This document is formatted according to the principles of [Keep A CHANGELOG](htt

## [Unreleased]
### Changed
- [Java] Optimize Location performance ([#385](https://github.com/cucumber/gherkin/pull/385))
- [Java] Optimize AstNode performance ([#383](https://github.com/cucumber/gherkin/pull/383))
- [Java] Optimize EncodingParser performance ([#382](https://github.com/cucumber/gherkin/pull/382))
- [Java] Optimize GherkinDialect performance ([#380](https://github.com/cucumber/gherkin/pull/380))
Expand Down
2 changes: 1 addition & 1 deletion java/gherkin-java.razor
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ class @Model.ParserClassName<T> {

endRule(context, [email protected]);

if (context.errors.size() > 0) {
if (!context.errors.isEmpty()) {
throw new ParserException.CompositeParserException(context.errors);
}

Expand Down
4 changes: 3 additions & 1 deletion java/src/main/java/io/cucumber/gherkin/AstNode.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

import static io.cucumber.gherkin.Parser.RuleType;
import static io.cucumber.gherkin.Parser.TokenType;
import static java.util.Objects.requireNonNull;

class AstNode {
// subItems is relatively sparse, so pre-initializing all values with empty
Expand All @@ -28,6 +29,7 @@ void add(RuleType ruleType, Object obj) {
items.add(obj);
}

@SuppressWarnings("unchecked")
<T> T getSingle(RuleType ruleType, T defaultResult) {
// if not null, then at least one item is present because
// the list was created in add(), so no need to check isEmpty()
Expand All @@ -45,7 +47,7 @@ <T> List<T> getItems(RuleType ruleType) {
}

Token getToken(TokenType tokenType) {
return getSingle(tokenType.ruleType, new Token(null, null));
return requireNonNull(getSingle(tokenType.ruleType, null));
}

List<Token> getTokens(TokenType tokenType) {
Expand Down
39 changes: 15 additions & 24 deletions java/src/main/java/io/cucumber/gherkin/GherkinDocumentBuilder.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import java.util.List;
import java.util.stream.Collectors;

import static io.cucumber.gherkin.Locations.atColumn;
import static io.cucumber.gherkin.Parser.Builder;
import static io.cucumber.gherkin.Parser.RuleType;
import static io.cucumber.gherkin.Parser.TokenType;
Expand Down Expand Up @@ -54,7 +55,7 @@ private AstNode currentNode() {
@Override
public void build(Token token) {
if (token.matchedType == TokenType.Comment) {
Comment comment = new Comment(getLocation(token, 0), token.matchedText);
Comment comment = new Comment(token.location, token.matchedText);
comments.add(comment);
} else {
currentNode().add(token.matchedType.ruleType, token);
Expand All @@ -78,7 +79,7 @@ private Object getTransformedNode(AstNode node) {
case Step: {
Token stepLine = node.getToken(TokenType.StepLine);
return new Step(
getLocation(stepLine, 0),
stepLine.location,
stepLine.matchedKeyword,
stepLine.keywordType,
stepLine.matchedText,
Expand All @@ -100,7 +101,7 @@ private Object getTransformedNode(AstNode node) {
}

return new DocString(
getLocation(separatorToken, 0),
separatorToken.location,
mediaType,
content.toString(),
separatorToken.matchedKeyword
Expand All @@ -113,7 +114,7 @@ private Object getTransformedNode(AstNode node) {
case Background: {
Token backgroundLine = node.getToken(TokenType.BackgroundLine);
return new Background(
getLocation(backgroundLine, 0),
backgroundLine.location,
backgroundLine.matchedKeyword,
backgroundLine.matchedText,
getDescription(node),
Expand All @@ -126,7 +127,7 @@ private Object getTransformedNode(AstNode node) {
Token scenarioLine = scenarioNode.getToken(TokenType.ScenarioLine);

return new Scenario(
getLocation(scenarioLine, 0),
scenarioLine.location,
getTags(node),
scenarioLine.matchedKeyword,
scenarioLine.matchedText,
Expand All @@ -144,7 +145,7 @@ private Object getTransformedNode(AstNode node) {
List<TableRow> tableBody = rows != null && !rows.isEmpty() ? rows.subList(1, rows.size()) : Collections.emptyList();

return new Examples(
getLocation(examplesLine, 0),
examplesLine.location,
getTags(node),
examplesLine.matchedKeyword,
examplesLine.matchedText,
Expand Down Expand Up @@ -195,7 +196,7 @@ private Object getTransformedNode(AstNode node) {
String language = featureLine.matchedGherkinDialect.getLanguage();

return new Feature(
getLocation(featureLine, 0),
featureLine.location,
tags,
language,
featureLine.matchedKeyword,
Expand Down Expand Up @@ -223,7 +224,7 @@ private Object getTransformedNode(AstNode node) {
}

return new Rule(
getLocation(ruleLine, 0),
ruleLine.location,
tags,
ruleLine.matchedKeyword,
ruleLine.matchedText,
Expand All @@ -247,7 +248,7 @@ private List<TableRow> getTableRows(AstNode node) {
List<TableRow> rows = new ArrayList<>(tokens.size());

for (Token token : tokens) {
rows.add(new TableRow(getLocation(token, 0), getCells(token), idGenerator.newId()));
rows.add(new TableRow(token.location, getCells(token), idGenerator.newId()));
}
ensureCellCount(rows);
return rows;
Expand All @@ -260,21 +261,16 @@ private void ensureCellCount(List<TableRow> rows) {
int cellCount = rows.get(0).getCells().size();
for (TableRow row : rows) {
if (row.getCells().size() != cellCount) {
io.cucumber.messages.types.Location rowLocation = row.getLocation();
io.cucumber.gherkin.Location location = new io.cucumber.gherkin.Location(
rowLocation.getLine().intValue(),
rowLocation.getColumn().orElse(0L).intValue()
);
throw new ParserException.AstBuilderException("inconsistent cell count within the table", location);
throw new ParserException.AstBuilderException("inconsistent cell count within the table", row.getLocation());
}
}
}

private List<TableCell> getCells(Token token) {
List<TableCell> cells = new ArrayList<>();
List<TableCell> cells = new ArrayList<>(token.matchedItems.size());
for (GherkinLineSpan cellItem : token.matchedItems) {
TableCell tableCell = new TableCell(
getLocation(token, cellItem.column),
atColumn(token.location, cellItem.column),
cellItem.text
);
cells.add(tableCell);
Expand All @@ -286,25 +282,20 @@ private List<Step> getSteps(AstNode node) {
return node.getItems(RuleType.Step);
}

private io.cucumber.messages.types.Location getLocation(Token token, int column) {
column = column == 0 ? token.location.getColumn() : column;
return new io.cucumber.messages.types.Location((long) token.location.getLine(), (long) column);
}

private String getDescription(AstNode node) {
return node.getSingle(RuleType.Description, "");
}

private List<Tag> getTags(AstNode node) {
AstNode tagsNode = node.getSingle(RuleType.Tags, new AstNode(RuleType.None));
if (tagsNode == null)
return new ArrayList<>();
return Collections.emptyList();

List<Token> tokens = tagsNode.getTokens(TokenType.TagLine);
List<Tag> tags = new ArrayList<>();
for (Token token : tokens) {
for (GherkinLineSpan tagItem : token.matchedItems) {
tags.add(new Tag(getLocation(token, tagItem.column), tagItem.text, idGenerator.newId()));
tags.add(new Tag(atColumn(token.location, tagItem.column), tagItem.text, idGenerator.newId()));
}
}
return tags;
Expand Down
18 changes: 10 additions & 8 deletions java/src/main/java/io/cucumber/gherkin/GherkinLine.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package io.cucumber.gherkin;

import io.cucumber.messages.types.Location;

import java.util.ArrayList;
import java.util.List;
import java.util.PrimitiveIterator;
Expand All @@ -12,19 +14,20 @@
import static io.cucumber.gherkin.StringUtils.rtrimKeepNewLines;
import static io.cucumber.gherkin.StringUtils.symbolCount;
import static io.cucumber.gherkin.StringUtils.trim;
import static java.util.Objects.requireNonNull;

class GherkinLine implements IGherkinLine {
// TODO: set this to 0 when/if we change to 0-indexed columns
private static final int OFFSET = 1;
private final String lineText;
private final String trimmedLineText;
private final int indent;
private final int line;
private final Location line;

public GherkinLine(String lineText, int line) {
this.lineText = lineText;
public GherkinLine(String lineText, Location line) {
this.lineText = requireNonNull(lineText);
this.trimmedLineText = trim(lineText);
this.line = line;
this.line = requireNonNull(line);
indent = symbolCount(lineText) - symbolCount(ltrim(lineText));
}

Expand All @@ -47,7 +50,7 @@ public String getLineText(int indentToRemove) {

@Override
public boolean isEmpty() {
return trimmedLineText.length() == 0;
return trimmedLineText.isEmpty();
}

@Override
Expand Down Expand Up @@ -76,7 +79,7 @@ public List<GherkinLineSpan> getTags() {
int symbolLength = uncommentedLine.codePointCount(0, indexInUncommentedLine);
int column = indent() + symbolLength + 1;
if (!token.matches("^\\S+$")) {
throw new ParserException("A tag may not contain whitespace", new Location(line, column));
throw new ParserException("A tag may not contain whitespace", Locations.atColumn(line, column));
}
tags.add(new GherkinLineSpan(column, TAG_PREFIX + token));
indexInUncommentedLine += element.length() + 1;
Expand Down Expand Up @@ -142,8 +145,7 @@ public boolean startsWithTitleKeyword(String text) {
int textLength = text.length();
return trimmedLineText.length() > textLength &&
trimmedLineText.startsWith(text) &&
trimmedLineText.substring(textLength, textLength + GherkinLanguageConstants.TITLE_KEYWORD_SEPARATOR.length())
.equals(GherkinLanguageConstants.TITLE_KEYWORD_SEPARATOR);
trimmedLineText.startsWith(GherkinLanguageConstants.TITLE_KEYWORD_SEPARATOR, textLength);
}

}
9 changes: 1 addition & 8 deletions java/src/main/java/io/cucumber/gherkin/GherkinParser.java
Original file line number Diff line number Diff line change
Expand Up @@ -149,19 +149,12 @@ private List<Envelope> parse(String uri, String data) {
}

private Envelope createParseError(ParserException e, String uri) {
long line = e.location.getLine();
long column = e.location.getColumn();
return Envelope.of(new ParseError(
new SourceReference(
uri,
null,
null,
// We want 0 values not to be serialised, which is why we set them to null
// This is a legacy requirement brought over from old protobuf behaviour
new io.cucumber.messages.types.Location(
line,
column == 0 ? null : column
)
e.location
),
e.getMessage()
));
Expand Down
19 changes: 0 additions & 19 deletions java/src/main/java/io/cucumber/gherkin/Location.java

This file was deleted.

39 changes: 39 additions & 0 deletions java/src/main/java/io/cucumber/gherkin/Locations.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package io.cucumber.gherkin;

import io.cucumber.messages.types.Location;

import static java.util.Objects.requireNonNull;

class Locations {

/**
* Cache of Long objects for the range 0-3999. This is used
* to avoid creating a huge amount of Long objects in getLocation().
* We can't use Long.valueOf() because it caches only the first 128
* values, and typical feature files have much more lines.
*/
private final static Long[] longs = new Long[4000];
static {
for (int i = 0; i < longs.length; i++) {
longs[i] = (long) i;
}
}

private static Long getLong(int i) {
if (i>=longs.length) return (long) i;
return longs[i];
}

static Location atColumn(Location location, int column) {
requireNonNull(location);
if (column <= 0) {
throw new IllegalArgumentException("Columns are index-1 based");
}
return new Location(location.getLine(), getLong(column));
}

static Location atLine(int line) {
return new Location(getLong(line), null);
}

}
2 changes: 1 addition & 1 deletion java/src/main/java/io/cucumber/gherkin/Parser.java
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ T parse(ITokenScanner tokenScanner, ITokenMatcher tokenMatcher, String uri) {

endRule(context, RuleType.GherkinDocument);

if (context.errors.size() > 0) {
if (!context.errors.isEmpty()) {
throw new ParserException.CompositeParserException(context.errors);
}

Expand Down
Loading