Skip to content

Commit

Permalink
Fix directive name parsing during minification
Browse files Browse the repository at this point in the history
Fixes #3
  • Loading branch information
atifaziz authored May 21, 2019
1 parent adfb6ee commit be79539
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 5 deletions.
23 changes: 18 additions & 5 deletions src/CSharpMinifier/Minifier.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,18 +48,31 @@ from t in Scanner.Scan(source)
&& t.Kind != TokenKind.NewLine
select t;

bool IsWordChar(char ch) =>
char.IsLetter(ch) || ch >= '0' && ch <= '9' || ch == '_';
bool IsSpaceOrTab (char ch) => ch == ' ' || ch == '\t';
bool IsAsciiLetter(char ch) => (ch = (char) (ch & ~0x20)) >= 'A' && ch <= 'z';
bool IsWordChar (char ch) => char.IsLetter(ch)
|| ch >= '0' && ch <= '9'
|| ch == '_';

var lastCh = (char?)null;
foreach (var t in tokens)
{
if (t.Kind == TokenKind.PreprocessorDirective)
{
var ei = source.IndexOfAny(SpaceOrTab, t.Start.Offset, t.Length);
var tei = t.End.Offset;

var si = t.Start.Offset + 1;
var length = (ei < 0 ? t.End.Offset : ei) - si;
if ( string.CompareOrdinal("region" , 0, source, si, length) != 0
while (si < tei && IsSpaceOrTab(source[si]))
si++;

var ei = si;
while (ei < tei && IsAsciiLetter(source[ei]))
ei++;

var length = ei - si;

if (length == 0
|| string.CompareOrdinal("region" , 0, source, si, length) != 0
&& string.CompareOrdinal("endregion", 0, source, si, length) != 0)
{
if (lastCh != null)
Expand Down
9 changes: 9 additions & 0 deletions tests/MinifierTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ public void MinifyNullSource()
public void Minify()
{
const string source = @"
#line 1
# line 1
/* https://unlicense.org/
*
* This is free and unencumbered software released into the public domain.
Expand Down Expand Up @@ -63,6 +65,10 @@ public void Minify()
* For more information, please refer to <http://unlicense.org>
*/
#region!
#! // not really valid
#endregion!
#region Imports
using System;
#endregion
Expand Down Expand Up @@ -91,6 +97,9 @@ In at fringilla ipsum.
.ToDelimitedString(string.Empty);

const string expected =
"#line 1\n" +
"# line 1\n" +
"#!\n" +
"using System;" +
"static class Program{" +
"static void Main(){" +
Expand Down

0 comments on commit be79539

Please sign in to comment.