Skip to content

Commit

Permalink
Fix tuple parsing in elm-string-representation
Browse files Browse the repository at this point in the history
Closes #15
  • Loading branch information
kachkaev committed Dec 20, 2018
1 parent 083a592 commit 1e58be7
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 9 deletions.
37 changes: 37 additions & 0 deletions packages/elm-string-representation/src/parse.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,17 @@ export const testCases: Array<{
b: 42,
},
},
{
input: ["{ x = True, y = False }"],
output: {
x: true,
y: false,
},
},
{
input: ['"{ x = True, y = False }"'],
output: "{ x = True, y = False }",
},
{
input: [
'{ type = "geoshape", filled = False, visible = True, stroke = "#000", strokeWidth = 0.1 }',
Expand Down Expand Up @@ -102,6 +113,32 @@ export const testCases: Array<{
b: 42,
},
},
{
input: ["( 1, 2 )", "(1,2)"],
output: [1, 2],
},
{
input: ["[ ( 1, 2 ) ]", "[(1,2)]"],
output: [[1, 2]],
},
{
input: ["[ ( 1, 2, 3 ), ( 4, 5, 6 ) ]", "[(1,2,3),(4,5,6)]"],
output: [[1, 2, 3], [4, 5, 6]],
},
{
input: ['{ a = "test", b = (1, 2, 3) }'],
output: {
a: "test",
b: [1, 2, 3],
},
},
{
input: ['{ a = "(1, 2, 3)", b = (1, 2, 3) }'],
output: {
a: "(1, 2, 3)",
b: [1, 2, 3],
},
},
{
input: [
"{ x = {",
Expand Down
32 changes: 23 additions & 9 deletions packages/elm-string-representation/src/parse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,21 +20,35 @@ export default (text: string): any => {
return null;
}

// Replacing using regexps is error-prone when searched
// strings are contained in values.
// The method should be rewritten as a tokenizer
// Replacing using regexps is potentially error-prone.
// The method may be rewritten as a tokenizer
// and a grammar parser to avoid this.
const patchedInput =
text.charAt(0) !== "{"
? text
: text
const inputChunks = text.split('"');
const outputChunks: string[] = [];

let insideString = false;
inputChunks.forEach((chunk) => {
if (insideString) {
outputChunks.push(chunk);
if (!chunk.endsWith("\\")) {
insideString = false;
}
} else {
outputChunks.push(
chunk
.replace(/ = True/g, " = true")
.replace(/ = False/g, " = false")
.replace(/(,|{)(| ([$a-zA-Z_0-9]+)) = /g, '$1 "$3": ');
.replace(/(,|{)(| ([$a-zA-Z_0-9]+)) = /g, '$1 "$3": ')
.replace(/\(/g, "[")
.replace(/\)/g, "]"),
);
insideString = true;
}
});

try {
return recursivelyConvertApplicableObjectsToArrays(
JSON.parse(patchedInput),
JSON.parse(outputChunks.join('"')),
);
} catch (e) {
throw new Error(
Expand Down

0 comments on commit 1e58be7

Please sign in to comment.