Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/Unicode escape support #166

Merged
merged 26 commits into from
May 27, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
a52d832
Merge pull request #1 from axuno/master
karljj1 Nov 12, 2020
bf2379c
Merge remote-tracking branch 'Original/main'
karljj1 Apr 12, 2021
afd5b77
Update issue templates
axunonb Apr 17, 2021
1d22508
Inserted a link to merged version/v3 changes
axunonb Apr 27, 2021
11c3033
Updated README
axunonb Apr 27, 2021
d1779f9
Merge remote-tracking branch 'upstream/main' into version/v3.0
axunonb Apr 29, 2021
cb5559a
Make parser fully covered with unit tests
axunonb Apr 29, 2021
e327de5
Merge remote-tracking branch 'upstream/version/v3.0' into version/v3.0
axunonb Apr 29, 2021
cab97df
Updated CHANGES.md
axunonb Apr 29, 2021
e8d9c93
Merge remote-tracking branch 'upstream/version/v3.0' into version/v3.0
axunonb Apr 29, 2021
294f810
Merge remote-tracking branch 'upstream/version/v3.0' into version/v3.0
axunonb Apr 29, 2021
792c391
Merge remote-tracking branch 'upstream/version/v3.0' into version/v3.0
axunonb May 3, 2021
4f45a84
Merge remote-tracking branch 'upstream/version/v3.0' into version/v3.0
axunonb May 9, 2021
e49db1e
Merge remote-tracking branch 'upstream/version/v3.0' into version/v3.0
axunonb May 9, 2021
2c562b5
Merge remote-tracking branch 'upstream/version/v3.0' into version/v3.0
axunonb May 9, 2021
2ba8c5f
Updated .editorconfig
axunonb May 9, 2021
46f02d4
Added support for Unicode Escape sequences
karljj1 May 21, 2021
f358b60
Updated test with unicode escape sequence support and fixed some typos
karljj1 May 21, 2021
a525889
Fixed typo
karljj1 May 21, 2021
933e992
Some additional tests to keep code coverage happy
karljj1 May 21, 2021
7c3a12e
Merge remote-tracking branch 'upstream/version/v3.0' into version/v3.0
axunonb May 25, 2021
bda63e0
Merge remote-tracking branch 'upstream/version/v3.0' into version/v3.0
axunonb May 25, 2021
ef58744
Merge remote-tracking branch 'upstream/version/v3.0' into version/v3.0
axunonb May 26, 2021
503e0a5
Some additional tests to keep code coverage happy
karljj1 May 21, 2021
0477b1e
Rebased to version/v3.0
axunonb May 27, 2021
06c47eb
Rebased to version/v3.0
axunonb May 27, 2021
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 19 additions & 7 deletions src/SmartFormat.Tests/Core/LiteralTextTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@ public void FormatCharacterLiteralsAsString()
[Test]
public void AllSupportedCharacterLiteralsAsUnicode()
{
const string formatWithFileBehavior = @"All supported literal characters: \' \"" \\ \a \b \f \n \r \t \v \0!";
const string formatWithCodeBehavior = "All supported literal characters: \' \" \\ \a \b \f \n \r \t \v \0!";
const string formatWithFileBehavior = @"All supported literal characters: \' \"" \\ \a \b \f \n \r \t \v \0 \u2022!";
const string formatWithCodeBehavior = "All supported literal characters: \' \" \\ \a \b \f \n \r \t \v \0 \u2022!";

var formatter = Smart.CreateDefaultSmartFormat();
formatter.Settings.Parser.ConvertCharacterStringLiterals = true;
Expand All @@ -43,15 +43,27 @@ public void AllSupportedCharacterLiteralsAsUnicode()
Assert.AreEqual(formatWithCodeBehavior, result);
}

[Test]
public void UnsupportedCharacterLiteralEscapeSequence()
[TestCase(@"Some text \u2022 with the value {0}", "Some text \u2022 with the value 123")]
[TestCase(@"\u2015 {0}", "\u2015 123")]
[TestCase(@"\u2010 {0} \u2015", "\u2010 123 \u2015")]
public void UnicodeEscapeSequenceIsParsed(string format, string expectedOutput)
{
var formatter = Smart.CreateDefaultSmartFormat();
formatter.Settings.Parser.ConvertCharacterStringLiterals = true;
Assert.AreEqual(expectedOutput, formatter.Format(format, 123));
}

[TestCase(@"Some text {0} \uABCP", @"\uABCP")]
[TestCase(@"Some text {0} \u-123", @"\u-123")]
[TestCase(@"\u", @"\u")]
[TestCase(@"\y", @"\y")]
[TestCase(@"Some text \uuuuu {0}", @"\uuuuu")]
public void UnsupportedCharacterLiteralEscapeSequence(string format, string exMessage)
{
const string format = @"Not supported: \y - Supported: \a";

var formatter = Smart.CreateDefaultSmartFormat();
formatter.Settings.Parser.ConvertCharacterStringLiterals = true;

Assert.That( () => formatter.Format(format), Throws.ArgumentException.And.Message.Contains(@"\y"));
Assert.That( () => formatter.Format(format, 123), Throws.ArgumentException.And.Message.Contains(exMessage));
}

[Test]
Expand Down
21 changes: 21 additions & 0 deletions src/SmartFormat.Tests/Core/ParserTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -596,5 +596,26 @@ public void Parse_Options()
Assert.That(placeholder.Format?.Items.Count, Is.EqualTo(3));
Assert.That(string.Concat(placeholder.Format?.Items[0].ToString(), placeholder.Format?.Items[1].ToString(), placeholder.Format?.Items[2].ToString()), Is.EqualTo(literal.Replace("\\", "")));
}

[TestCase(@"\u1234", @"\u1234", 0, true)]
[TestCase(@"\u1234abc", @"\u1234", 0, true)]
[TestCase(@"abc\u1234", @"\u1234", 1, true)]
[TestCase(@"abc\u1234def", @"\u1234", 1, true)]
[TestCase(@"\uwxyz", @"\uwxyz", 0, false)] // Parser accepts illegal sequence
[TestCase(@"\uw", @"\uw", 0, false)] // Parser accepts illegal sequence, even if shorter than 4 characters
public void Parse_Unicode(string formatString, string unicodeLiteral, int itemIndex, bool isLegal)
{
var parser = GetRegularParser();
var result = parser.ParseFormat(formatString, new[] {"d"});

var literal = result.Items[itemIndex];
Assert.That(literal, Is.TypeOf(typeof(LiteralText)));
Assert.That(literal.BaseString.Substring(literal.StartIndex, literal.Length), Is.EqualTo(unicodeLiteral));

if(isLegal)
Assert.That(literal.ToString()[0], Is.EqualTo((char) int.Parse(unicodeLiteral.Substring(2), System.Globalization.NumberStyles.HexNumber)));
else
Assert.That(() => literal.ToString(), Throws.ArgumentException.And.Message.Contains(unicodeLiteral));
}
}
}
23 changes: 23 additions & 0 deletions src/SmartFormat/Core/Parsing/EscapedLiteral.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;

namespace SmartFormat.Core.Parsing
Expand Down Expand Up @@ -53,6 +54,20 @@ public static bool TryGetChar(char input, out char result, bool includeFormatter
: GeneralLookupTable.TryGetValue(input, out result);
}

private static char GetUnicode(string input, int startIndex)
{
var unicode = input.Length - startIndex >= 4
? input.Substring(startIndex, 4)
: input.Substring(startIndex);

if (int.TryParse(unicode, NumberStyles.HexNumber, null, out var result))
{
return (char) result;
}

throw new ArgumentException($"Unrecognized escape sequence in literal: \"\\u{unicode}\"");
}

/// <summary>
/// Converts escaped characters in input with real characters, e.g. "\\" => "\", if '\' is the escape character.
/// </summary>
Expand Down Expand Up @@ -84,6 +99,14 @@ public static ReadOnlySpan<char> UnEscapeCharLiterals(char escapingSequenceStart

if (input[inputIndex] == escapingSequenceStart)
{
if (input[nextInputIndex] == 'u')
{
// GetUnicode will throw if code is illegal
result[resultIndex++] = GetUnicode(input, nextInputIndex + 1);
inputIndex += 5; // move to last unicode character
continue;
}

if (TryGetChar(input[nextInputIndex], out var realChar, includeFormatterOptionChars))
{
result[resultIndex++] = realChar;
Expand Down
20 changes: 15 additions & 5 deletions src/SmartFormat/Core/Parsing/Parser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -408,7 +408,7 @@ private void ParseAlternativeEscaping(string inputFormat, Format currentFormat,
// index.NamedFormatterStart = PositionUndefined;

// See what is the next character
var indexNextChar = index.Current + 1;
var indexNextChar = index.SafeAdd(index.Current, 1);

// **** Alternative brace escaping with { or } following the escape character ****
if (indexNextChar < inputFormat.Length && (inputFormat[indexNextChar] == _parserSettings.PlaceholderBeginChar || inputFormat[indexNextChar] == _parserSettings.PlaceholderEndChar))
Expand All @@ -425,10 +425,20 @@ private void ParseAlternativeEscaping(string inputFormat, Format currentFormat,

// Finish the last text item:
if (index.Current != index.LastEnd) currentFormat.Items.Add(new LiteralText(Settings, currentFormat, index.LastEnd, index.Current));
index.LastEnd = index.SafeAdd(index.Current, 2);

// Next add the character literal INCLUDING the escape character, which LiteralText will expect
currentFormat.Items.Add(new LiteralText(Settings, currentFormat, index.Current, index.LastEnd));

// Is this a unicode escape sequence?
if (inputFormat[indexNextChar] == 'u')
{
// The next 4 characters must represent the unicode
index.LastEnd = index.SafeAdd(index.Current, 6);
currentFormat.Items.Add(new LiteralText(Settings, currentFormat, index.Current, index.LastEnd));
}
else
{
// Next add the character literal INCLUDING the escape character, which LiteralText will expect
index.LastEnd = index.SafeAdd(index.Current, 2);
currentFormat.Items.Add(new LiteralText(Settings, currentFormat, index.Current, index.LastEnd));
}

index.Current = index.SafeAdd(index.Current, 1);
}
Expand Down