Skip to content
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

Fix invalid writing of special characters when writing to a YAML file #37

Merged
merged 4 commits into from
Feb 12, 2024
Merged
Show file tree
Hide file tree
Changes from 3 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
12 changes: 12 additions & 0 deletions ballerina/Dependencies.toml
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,17 @@ org = "ballerina"
name = "lang.object"
version = "0.0.0"

[[package]]
org = "ballerina"
name = "lang.regexp"
version = "0.0.0"
dependencies = [
{org = "ballerina", name = "jballerina.java"}
]
modules = [
{org = "ballerina", packageName = "lang.regexp", moduleName = "lang.regexp"}
]

[[package]]
org = "ballerina"
name = "lang.value"
Expand Down Expand Up @@ -141,6 +152,7 @@ dependencies = [
{org = "ballerina", name = "file"},
{org = "ballerina", name = "io"},
{org = "ballerina", name = "lang.array"},
{org = "ballerina", name = "lang.regexp"},
{org = "ballerina", name = "log"},
{org = "ballerina", name = "test"}
]
Expand Down
2 changes: 1 addition & 1 deletion ballerina/modules/lexer/lexer.bal
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ public isolated function scan(LexerState state) returns LexerState|LexicalError
return state.index == 0 ? state.tokenize(EMPTY_LINE) : state.tokenize(EOL);
}

// Check for line breaks when reading form string
// Check for line breaks when reading from string
if state.peek() == "\n" && state.context != LEXER_DOUBLE_QUOTE {
state.isNewLine = true;
return state.tokenize(EOL);
Expand Down
15 changes: 15 additions & 0 deletions ballerina/modules/parser/parser.bal
Original file line number Diff line number Diff line change
Expand Up @@ -244,3 +244,18 @@

return generateGrammarError(state, string `Invalid token '${state.currentToken.token}' as the first for generating an event`);
}

# Check if the given string is a valid planar scalar.
#
# + value - The string to be checked
# + return - True if the string is a valid planar scalar. Else, false.
public isolated function isValidPlanarScalar(string value) returns boolean {
string? planarScalarResult = ();
do {
ParserState parserState = check new ([value]);
planarScalarResult = check planarScalar(parserState, false);
} on fail {
return false;

Check warning on line 258 in ballerina/modules/parser/parser.bal

View check run for this annotation

Codecov / codecov/patch

ballerina/modules/parser/parser.bal#L258

Added line #L258 was not covered by tests
}
return planarScalarResult is string && planarScalarResult.trim() == value.trim();
}
7 changes: 4 additions & 3 deletions ballerina/modules/parser/scalar.bal
Original file line number Diff line number Diff line change
Expand Up @@ -169,14 +169,15 @@ isolated function singleQuoteScalar(ParserState state) returns ParsingError|stri

# Parse the string of a planar scalar.
#
# + state - Current parser state
# + state - Current parser state
# + allowTokensAsPlanar - If set, then the restricted tokens are allowed as planar scalar
# + return - Parsed planar scalar value
isolated function planarScalar(ParserState state) returns ParsingError|string {
isolated function planarScalar(ParserState state, boolean allowTokensAsPlanar = true) returns ParsingError|string {
// Process the first planar char
string lexemeBuffer = state.currentToken.value;
boolean isFirstLine = true;
string newLineBuffer = "";
state.lexerState.allowTokensAsPlanar = true;
state.lexerState.allowTokensAsPlanar = allowTokensAsPlanar;

check checkToken(state, peek = true);

Expand Down
17 changes: 8 additions & 9 deletions ballerina/modules/serializer/node.bal
Original file line number Diff line number Diff line change
Expand Up @@ -14,18 +14,17 @@

import yaml.common;
import yaml.schema;

const string INVALID_PLANAR_PATTERN = "([\\w|\\s]*[\\-|\\?|:|] [\\w|\\s]*)|"
+ "([\\w|\\s]* #[\\w|\\s]*)|"
+ "([,|\\[|\\]|\\{|\\}|&\\*|!\\||>|'|\"|%|@|`][\\w|\\s]*)";
import yaml.parser;
import ballerina/lang.regexp;

isolated function serializeString(SerializerState state, json data, string tag) {
string value = data.toString();
state.events.push({
value: re `${INVALID_PLANAR_PATTERN}`.isFullMatch(value) || state.forceQuotes
? string `${state.delimiter}${value}${state.delimiter}` : value,
tag
});
if value.includes("\n") {
NipunaRanasinghe marked this conversation as resolved.
Show resolved Hide resolved

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if value.includes("\n") {
if value.includes("\n" || value.includes("\r\n") {

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Supporting OS-specific new lines is tracked with another issue: ballerina-platform/ballerina-library#4330.

value = state.delimiter + regexp:replaceAll(re `\n`, data.toString(), "\\n") + state.delimiter;
} else {
value = (!parser:isValidPlanarScalar(value) || state.forceQuotes) ? state.delimiter + value + state.delimiter : value;
}
state.events.push({value, tag});
}

isolated function serializeSequence(SerializerState state, json[] data, string tag, int depthLevel) returns schema:SchemaError? {
Expand Down
33 changes: 31 additions & 2 deletions ballerina/modules/serializer/tests/lib_test.bal
Original file line number Diff line number Diff line change
Expand Up @@ -86,14 +86,43 @@ function testQuotesForInvalidPlanarChar(string line) returns error? {

function invalidPlanarDataGen() returns map<[string]> {
return {
"comment": [" #"],
"comment": [" # comment"],
"explicit key": ["? "],
"sequence entry": ["- "],
"mapping value": [": "],
"flow indicator": ["}a"]
"flow indicator": ["}a"],
"alias": ["*/*"],
"collect-entry": [", "],
"anchor": ["&anchor"],
"tag": ["!tag"],
"directive": ["%YAML 1.2"]
};
}

@test:Config {
dataProvider: scalarWithNewLinesDataGen,
groups: ["serializer"]
}
function testScalarWithNewLines(json line, string[] expectedOutputs) returns error? {
common:Event[] events = check getSerializedEvents(line);
int index = 0;
foreach common:Event event in events {
if event is common:ScalarEvent {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We need to add a assertFail scenario for the else condition

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The test is designed to consider only the ScalarEvents and ignore the rest, as the new lines are only processed in these events. Hence, the events that are not ScalarEvents form a valid stream for the given input.

test:assertEquals(event.value, string `"${expectedOutputs[++index]}"`);
break;
}
}
}

function scalarWithNewLinesDataGen()returns map<[json, string[]]> =>
{
"simple scalar": ["first\nsecond", ["first\\nsecond"]],
"sequence": [[["first\nsecond"], ["first\nsecond\n\nthird"]], ["first\\nsecond", "first\\nsecond\\n\\nthird"]],
"nested sequence": [[[["first\nsecond"]]], ["first\\nsecond"]],
"mapping": [{"key\nline": "first\nsecond"}, ["key\\nline", "first\\nsecond"]],
"nested mapping": [{"key\nline": {"nested\nline": "first\nsecond"}}, ["key\\nline", "nested\\nline", "first\\nsecond"]]
};

@test:Config {
groups: ["serializer"]
}
Expand Down
Loading