Skip to content

Commit 13e41ad

Browse files
committed
Fixes #3085: dotnet new crashes if template contains #ifdef
Problem was that in `if` statement above took path where `tokens` doesn't add any token, reason for that is that there was no `whitespace` or `brace` token after it, instead just "Literal" which is not fully parsed yet and can't be added to `tokens`, at least thats my understanding... What is weird about current logic is... that `#ifBAR` is same as `#if BAR`... Easy fix would be to do add space after `if`, but might cause other issues... I think lets not invest too much enery into this and lets just fix crash if user types `#iffoo bar` so it doesn't crash...
1 parent e224acf commit 13e41ad

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

src/Microsoft.TemplateEngine.Core/Expressions/Cpp/CppStyleEvaluatorDefinition.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,7 @@ public static bool Evaluate(IProcessorState processor, ref int bufferLength, ref
114114
}
115115

116116
int braceDepth = 0;
117-
if (tokens[0].Family == TokenFamily.OpenBrace)
117+
if (tokens.Count > 0 && tokens[0].Family == TokenFamily.OpenBrace)
118118
{
119119
++braceDepth;
120120
}

test/Microsoft.TemplateEngine.Core.UnitTests/ConditionalTests.CStyleEvaluator.cs

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1596,5 +1596,34 @@ public void VerifyEmitStrayToken()
15961596
// pretend it's false because the inputs and outputs are the same
15971597
Verify(Encoding.UTF8, output, false, value, expected);
15981598
}
1599+
1600+
[Theory]
1601+
[InlineData("foo", true)]
1602+
[InlineData("foo", false)]
1603+
[InlineData("def", true)]
1604+
[InlineData("def", false)]
1605+
// dotnet new crashes if template contains #ifdef
1606+
// https://github.com/dotnet/templating/issues/3085
1607+
public void VerifyMisstypedIfTokenDoesntCrash(string varName, bool varValue)
1608+
{
1609+
string value = @"#ifdef
1610+
GAGA
1611+
#endif
1612+
";
1613+
string expected = varName == "def" && varValue ? @"GAGA
1614+
" : "";
1615+
1616+
byte[] valueBytes = Encoding.UTF8.GetBytes(value);
1617+
MemoryStream input = new MemoryStream(valueBytes);
1618+
MemoryStream output = new MemoryStream();
1619+
1620+
VariableCollection vc = new VariableCollection()
1621+
{
1622+
[varName] = varValue
1623+
};
1624+
IProcessor processor = SetupCStyleNoCommentsProcessor(vc);
1625+
processor.Run(input, output, 999);
1626+
Verify(Encoding.UTF8, output, true, value, expected);
1627+
}
15991628
}
16001629
}

0 commit comments

Comments
 (0)