Skip to content

Commit 8862cac

Browse files
committed
Bug: Fix occasional unsafe brace removing with nested ifs.
1 parent b1a2621 commit 8862cac

File tree

3 files changed

+20
-2
lines changed

3 files changed

+20
-2
lines changed

ShaderShrinker/Shrinker.Lexer/StringExtensions.cs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,11 +48,14 @@ public static int GetCodeCharCount(this string glsl)
4848

4949
public static bool IsNewline(this char ch) => ch == '\n' || ch == '\r';
5050

51+
/// <summary>
52+
/// Remove start/end braces if the content is a single-line instruction.
53+
/// </summary>
5154
public static string AllowBraceRemoval(this string s)
5255
{
5356
s = s.Trim();
5457
if (s.StartsWith("{") && s.EndsWith("}") && s.Count(ch => ch == ';') == 1)
55-
return s.Trim('{', '}', ' ');
58+
return s.Substring(1, s.Length - 2).Trim();
5659
return s;
5760
}
5861

ShaderShrinker/Shrinker.Parser/GlslOutputFormatter.cs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -328,7 +328,9 @@ o.Parent is not VariableDeclarationSyntaxNode && // ...not defined in within a d
328328

329329
var braceCode = new StringBuilder();
330330
AppendCode(braceCode, o.TrueBranch);
331-
var trueBranch = braceCode.ToString().AllowBraceRemoval();
331+
var trueBranch = braceCode.ToString();
332+
if (o.TrueBranch.Children.FirstOrDefault() is not IfSyntaxNode || o.FalseBranch == null)
333+
trueBranch = trueBranch.AllowBraceRemoval();
332334
sb.AppendLine(trueBranch);
333335

334336
if (o.FalseBranch != null)

ShaderShrinker/UnitTests/ShrinkerTests.cs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1844,6 +1844,19 @@ public void CheckStatementBracketsNotRemovedWhenSimplifyingArithmetic(
18441844
Assert.That(rootNode.ToCode().ToSimple(), Is.EqualTo(code));
18451845
}
18461846

1847+
[Test]
1848+
public void CheckBracesNotRemovedInIfWithNestedIf()
1849+
{
1850+
var lexer = new Lexer();
1851+
lexer.Load("int main() { if (true) { if (false) return 1; } else { return 2; } }");
1852+
1853+
var rootNode = new Parser(lexer)
1854+
.Parse()
1855+
.Simplify(CustomOptions.None());
1856+
1857+
Assert.That(rootNode.ToCode().ToSimple(), Is.EqualTo("int main() { if (true) { if (false) return 1; } else return 2; }"));
1858+
}
1859+
18471860
[Test]
18481861
public void CheckSupportForTernaryOperator()
18491862
{

0 commit comments

Comments
 (0)