/
Parser.String.cs
101 lines (93 loc) · 3.44 KB
/
Parser.String.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
namespace Pidgin
{
public static partial class Parser
{
/// <summary>
/// Creates a parser that parses and returns a literal string
/// </summary>
/// <param name="str">The string to parse</param>
/// <returns>A parser that parses and returns a literal string</returns>
///
public static Parser<char, string> String(string str)
{
if (str == null)
{
throw new ArgumentNullException(nameof(str));
}
return Parser<char>.Sequence<string>(str);
}
/// <summary>
/// Creates a parser that parses and returns a literal string, in a case insensitive manner.
/// The parser returns the actual string parsed.
/// </summary>
/// <param name="str">The string to parse</param>
/// <returns>A parser that parses and returns a literal string, in a case insensitive manner.</returns>
public static Parser<char, string> CIString(string str)
{
if (str == null)
{
throw new ArgumentNullException(nameof(str));
}
return new CIStringParser(str);
}
private sealed class CIStringParser : Parser<char, string>
{
private readonly string _value;
private Expected<char> _expected;
private Expected<char> Expected
{
get
{
if (_expected.InternalTokens.IsDefault)
{
_expected = new Expected<char>(_value.ToImmutableArray());
}
return _expected;
}
}
public CIStringParser(string value)
{
_value = value;
}
internal sealed override InternalResult<string> Parse(ref ParseState<char> state)
{
var consumedInput = false;
var builder = new InplaceStringBuilder(_value.Length);
foreach (var c in _value)
{
if (!state.HasCurrent)
{
state.Error = new InternalError<char>(
Maybe.Nothing<char>(),
true,
state.SourcePos,
null
);
state.AddExpected(Expected);
return InternalResult.Failure<string>(consumedInput);
}
var token = state.Current;
if (char.ToLowerInvariant(token) != char.ToLowerInvariant(c))
{
state.Error = new InternalError<char>(
Maybe.Just(token),
false,
state.SourcePos,
null
);
state.AddExpected(Expected);
return InternalResult.Failure<string>(consumedInput);
}
consumedInput = true;
builder.Append(token);
state.Advance();
}
return InternalResult.Success<string>(builder.ToString(), consumedInput);
}
}
}
}