Skip to content

Commit 3f2a54a

Browse files
FranklinWhaleriknoll
authored andcommitted
Parenthesized expression fix (microsoft#5876)
* Fixes microsoft/pxt-microbit#2399 * Fixes microsoft/pxt-microbit#2345 * Typo fix * Update to_string_arg.ts * use charAt instead of startsWith and endsWith * Fix parentheses check * Return false directly if last char is not )
1 parent 99399e1 commit 3f2a54a

File tree

3 files changed

+24
-8
lines changed

3 files changed

+24
-8
lines changed

pxtblocks/blocklycompiler.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -1158,7 +1158,7 @@ namespace pxt.blocks {
11581158
}
11591159

11601160
if (p.shadowOptions && p.shadowOptions.toString && returnType(e, target) !== pString) {
1161-
return H.mkSimpleCall("+", [H.mkStringLiteral(""), compileExpression(e, target, comments)]);
1161+
return H.mkSimpleCall("+", [H.mkStringLiteral(""), H.mkParenthesizedExpression(compileExpression(e, target, comments))]);
11621162
}
11631163

11641164
return compileExpression(e, target, comments)

pxtlib/jsoutput.ts

+21-5
Original file line numberDiff line numberDiff line change
@@ -219,11 +219,7 @@ namespace pxt.blocks {
219219
}
220220

221221
export function mkParenthesizedExpression(expression: JsNode): JsNode {
222-
return mkGroup([
223-
mkText("("),
224-
expression,
225-
mkText(")")
226-
])
222+
return isParenthesized(flattenNode([expression]).output) ? expression : mkGroup([mkText("("), expression, mkText(")")]);
227223
}
228224
}
229225

@@ -439,4 +435,24 @@ namespace pxt.blocks {
439435
export function isReservedWord(str: string) {
440436
return reservedWords.indexOf(str) !== -1;
441437
}
438+
439+
export function isParenthesized(fnOutput: string): boolean {
440+
if (fnOutput[0] !== "(" || fnOutput[fnOutput.length - 1] !== ")") {
441+
return false;
442+
}
443+
let unclosedParentheses = 1;
444+
for (let i = 1; i < fnOutput.length; i++) {
445+
const c = fnOutput[i];
446+
if (c === "(") {
447+
unclosedParentheses++;
448+
}
449+
else if (c === ")") {
450+
unclosedParentheses--;
451+
if (unclosedParentheses === 0) {
452+
return i === fnOutput.length - 1;
453+
}
454+
}
455+
}
456+
return false;
457+
}
442458
}
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
let item = 0
22
console.log("")
3-
console.log("" + 5)
4-
console.log("" + item)
3+
console.log("" + (5))
4+
console.log("" + (item))
55
console.log("" + (0 == 0))

0 commit comments

Comments
 (0)