-
Notifications
You must be signed in to change notification settings - Fork 3
/
CharParsers.cs
101 lines (88 loc) · 3.02 KB
/
CharParsers.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.Text;
using Utility.BaseTypes;
namespace ParserCombinators
{
public class CharParsers : Parsers<char>
{
/// <summary>
/// Succeed for any character. Return the parsed character.
/// </summary>
public static Parser<char, char> AnyChar
{
get { return Satisfy(c => true); }
}
/// <summary>
/// Succeed for any character that satisfies 'predicate'. Return the parsed character.
/// </summary>
public static Parser<char, char> Satisfy(Func<char, bool> predicate)
{
return from c in AnyToken
where predicate(c)
select c;
}
/// <summary>
/// Succeed for a character that is equal to 'ch'. Return the parsed character.
/// </summary>
public static Parser<char, char> Char(char ch)
{
return Satisfy(c => c == ch);
}
/// <summary>
/// Succeed for a character that is a digit. Return the parsed character.
/// </summary>
public static Parser<char, char> Digit
{
get { return Satisfy(c => c.IsDigit()); }
}
/// <summary>
/// Succeed for a character that is an octal digit. Return the parsed character.
/// </summary>
public static Parser<char, char> OctDigit
{
get { return Satisfy(c => c.IsOctDigit()); }
}
/// <summary>
/// Succeed for a character that is a hexadecimal digit. Return the parsed character.
/// </summary>
public static Parser<char, char> HexDigit
{
get { return Satisfy(c => c.IsHexDigit()); }
}
/// <summary>
/// Succeed for a character that is equal to any in the string 'chars'.
/// Return the parsed character.
/// </summary>
public static Parser<char, char> OneOf(string chars)
{
return Satisfy(c => chars.IndexOf(c) >= 0);
}
/// <summary>
/// Succeed for a character that is NOT equal to any in the string 'chars'.
/// Return the parsed character.
/// </summary>
public static Parser<char, char> NoneOf(string chars)
{
return Satisfy(c => chars.IndexOf(c) < 0);
}
/// <summary>
/// Parse a sequence of characters given by 's'. Return the parsed string.
/// </summary>
public static Parser<char, string> String(string s)
{
// TODO: implement IgnoreCase flag
return consList =>
{
StringBuilder sb = new StringBuilder();
foreach (char c in s.ToCharArray())
{
if (consList.IsEmpty || consList.Head != c)
return null;
sb.Append(consList.Head);
consList = consList.Tail;
}
return new Result<char, string>(sb.ToString(), consList);
};
}
}
}