This repository has been archived by the owner on Apr 28, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathParser.cs
433 lines (417 loc) · 16.2 KB
/
Parser.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
/*
* Vha.AOML
* Copyright (C) 2010-2011 Remco van Oosterhout
* See Credits.txt for all aknowledgements.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License only.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*/
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace Vha.AOML
{
public enum ParserMode
{
/// <summary>
/// Allows only properly formatted attributes inside tags
/// </summary>
Strict,
/// <summary>
/// Allows attributes without " or ' wrapper inside tags
/// </summary>
Normal,
/// <summary>
/// Allows attributes without closing ' inside tags
/// </summary>
Compatibility
}
/// <summary>
/// This class allows you to transform a string of AOML into a NodeCollection
/// </summary>
public class Parser
{
/// <summary>
/// Configures the parser's sensitivity to parse errors
/// </summary>
public ParserMode Mode
{
get { return this.mode; }
set
{
this.mode = value;
this.regex = null;
}
}
/// <summary>
/// Whether to automatically convert newline symbols in a ContentNode to an OpenNode("br", "", true)
/// </summary>
public bool NewlineToBreak { get; set; }
/// <summary>
/// Whether to automatically convert invalid element nodes to content nodes
/// </summary>
public bool InvalidElementsToContent { get; set; }
/// <summary>
/// Parses an AOML string into open, close and content nodes
/// </summary>
/// <param name="aoml">The aoml string to be parsed</param>
public NodeCollection Parse(string aoml)
{
NodeCollection nodes = new NodeCollection();
// Create regular expression instance
if (this.regex == null)
{
this.regex = new Regex(
"[<]\\s*(?<closer>[/]?)\\s*" +
"(?<name>[a-z]+)" +
"(\\s+((?<attribute>[a-z_\\-]+)\\s*" +
"(=\\s*(" +
/**/ (Mode == ParserMode.Strict ? "" : "(?<value>[^\\s<>'\"]+)|") +
/**/ "[\"](?<value>[^\"]*)[\"]|" +
/**/ (Mode == ParserMode.Compatibility ? "['](?<value>[^'>]*)[']?)|" : "['](?<value>[^']*)['])|") +
/**/ "(?<value>)" +
")?)\\s*)*" +
"\\s*(?<closed>[/]?)[>]",
RegexOptions.IgnoreCase|RegexOptions.Compiled|RegexOptions.Multiline);
}
// Some setup
int regexCloser = this.regex.GroupNumberFromName("closer");
int regexName = this.regex.GroupNumberFromName("name");
int regexAttribute = this.regex.GroupNumberFromName("attribute");
int regexValue = this.regex.GroupNumberFromName("value");
int regexClosed = this.regex.GroupNumberFromName("closed");
// Convert to unix line endings
aoml = aoml.Replace("\r\n", "\n");
// Parse AOML
MatchCollection matches = this.regex.Matches(aoml);
int offset = 0;
foreach (Match match in matches)
{
// Extract content
if (match.Index > offset)
{
string content = aoml.Substring(offset, match.Index - offset);
AddContent(nodes, content, content);
}
offset = match.Index + match.Length;
// Extract tag
string raw = match.Groups[0].Value;
string name = match.Groups[regexName].Value;
if (string.IsNullOrEmpty(name))
{
// No name, let's assume it's just text
AddContent(nodes, raw, raw);
continue;
}
bool closer = !string.IsNullOrEmpty(match.Groups[regexCloser].Value);
bool closed = !string.IsNullOrEmpty(match.Groups[regexClosed].Value);
if (closer)
{
// Closing tag
nodes.Add(new CloseNode(name, raw));
}
else
{
// Opening tag
OpenNode node = new OpenNode(name, raw, closed);
// Add attributes
for (int i = 0; i < match.Groups[regexAttribute].Captures.Count; i++)
{
node.AddAttribute(
match.Groups[regexAttribute].Captures[i].Value,
match.Groups[regexValue].Captures[i].Value);
}
nodes.Add(node);
}
}
// Remainder is content
if (offset < aoml.Length)
{
string content = aoml.Substring(offset);
AddContent(nodes, content, content);
}
return nodes;
}
/// <summary>
/// Sanitizes the stream of nodes into exclusively valid AOML.
/// This process involves changing and removing nodes.
/// </summary>
public void Sanitize(NodeCollection nodes)
{
if (nodes == null) { throw new ArgumentNullException(); }
// Loop through all nodes
nodes.Reset();
Node node = null;
while ((node = nodes.Next()) != null)
{
// Skip content nodes
if (node.Type == NodeType.Content) { continue; }
// Gather info
OpenNode openNode = null;
CloseNode closeNode = null;
string name = null;
if (node.Type == NodeType.Open)
{
openNode = (OpenNode)node;
name = openNode.Name;
// Check attributes
for (int i = 0; i < openNode.Count; i++)
{
string attr = openNode.GetAttributeName(i);
if (!validAttributes.Contains(attr))
{
openNode.RemoveAttribute(attr);
i--;
}
}
}
else if (node.Type == NodeType.Close)
{
closeNode = (CloseNode)node;
name = closeNode.Name;
}
// Singular elements
if (singularElements.Contains(name))
{
// Singular elements don't have closing nodes
if (closeNode != null)
{
nodes.Remove(closeNode);
}
// Singular elements are always self-closing
if (openNode != null)
{
openNode.Closed = true;
}
continue;
}
else if (inlineElements.Contains(name) || blockElements.Contains(name))
{
if (openNode == null) { continue; }
// Let's not use self-closing elements here
if (openNode.Closed)
{
openNode.Closed = false;
nodes.InsertAfter(openNode, new CloseNode(name, ""));
}
continue;
}
// Replace node as content node
if (this.InvalidElementsToContent)
{
// Replace node as content
this.ReplaceContent(nodes, node, node.Raw, node.Raw);
}
else
{
// Remove node
this.ReplaceContent(nodes, node, "", "");
}
}
// And we're done!
nodes.Reset();
}
/// <summary>
/// Balances out the stream of nodes to form a valid tree.
/// This process will always try to resolve conflicts by introducing extra inline elements over block elements.
/// </summary>
public void Balance(NodeCollection nodes)
{
if (nodes == null) { throw new ArgumentNullException(); }
// Fill in missing elements
List<string> nameStack = new List<string>();
nodes.Reset();
Node node = null;
while ((node = nodes.Next()) != null)
{
switch (node.Type)
{
case NodeType.Open:
OpenNode openNode = (OpenNode)node;
if (openNode.Closed) { continue; }
nameStack.Insert(0, openNode.Name);
break;
case NodeType.Close:
CloseNode closeNode = (CloseNode)node;
if (!nameStack.Contains(closeNode.Name))
{
// Found CloseNode without OpenNode
// Fix by insert an OpenNode before it
nodes.InsertBefore(
closeNode,
new OpenNode(closeNode.Name, "", false));
}
nameStack.Remove(closeNode.Name);
break;
}
}
while (nameStack.Count > 0)
{
// Found OpenNode without CloseNode
// Fix by adding a CloseNode at the end of the stream
string name = nameStack[0];
nameStack.RemoveAt(0);
nodes.Add(new CloseNode(name, ""));
}
// Resolve tree structure
List<OpenNode> nodeStack = new List<OpenNode>();
nodes.Reset();
while ((node = nodes.Next()) != null)
{
switch (node.Type)
{
case NodeType.Open:
OpenNode on = (OpenNode)node;
if (on.Closed) { continue; }
nodeStack.Insert(0, on);
break;
case NodeType.Close:
// A bit of setup
CloseNode closeNode = (CloseNode)node;
bool block = blockElements.Contains(closeNode.Name);
// Find matching OpenNode
OpenNode openNode = null;
foreach (OpenNode o in nodeStack)
{
if (o.Name == closeNode.Name)
{
openNode = o;
break;
}
}
if (openNode == null)
{
throw new InvalidOperationException("Unable to find matching OpenNode to CloseNode");
}
// Handle incorrect balance
int offset = 0;
while (nodeStack[offset].Name != closeNode.Name)
{
OpenNode n = nodeStack[offset];
if (block)
{
nodes.InsertBefore(node, new CloseNode(n.Name, ""));
nodes.InsertAfter(node, n.Clone());
nodeStack.RemoveAt(offset);
offset--;
}
else
{
nodes.InsertBefore(n, closeNode.Clone());
nodes.InsertAfter(n, openNode.Clone());
}
offset++;
}
// All fixed
nodeStack.RemoveAt(offset);
break;
}
}
// And we're done!
nodes.Reset();
}
#region Constructors
public Parser()
{
// Default values
this.NewlineToBreak = false;
this.InvalidElementsToContent = true;
// Create lists
this.singularElements = new List<string>(new string[] {
"br",
"img" });
this.inlineElements = new List<string>(new string[] {
"font",
"a",
"u",
"i"
});
this.blockElements = new List<string>(new string[]{
"div",
"center",
"left",
"right"
});
this.validAttributes = new List<string>(new string[] {
"color",
"align",
"href",
"style",
"src"
});
}
#endregion
#region Internal
private Regex regex = null;
private ParserMode mode = ParserMode.Normal;
private List<string> singularElements;
private List<string> inlineElements;
private List<string> blockElements;
private List<string> validAttributes;
private Node[] CreateContent(string content, string raw)
{
List<Node> nodes = new List<Node>();
if (string.IsNullOrEmpty(content))
{
return nodes.ToArray();
}
if (this.NewlineToBreak)
{
string[] contentParts = content.Split('\n');
string[] rawParts = raw != null ? raw.Split('\n') : new string[] { };
int i = 0;
foreach (string c in contentParts)
{
nodes.Add(new ContentNode(c, raw.Length > i ? rawParts[i] : ""));
if (i + 1 < contentParts.Length)
{
nodes.Add(new OpenNode("br", raw.Length > i ? "\n" : "", true));
}
i++;
}
}
else
{
nodes.Add(new ContentNode(content, raw));
}
return nodes.ToArray();
}
private void AddContent(NodeCollection nodes, string content, string raw)
{
if (nodes == null)
{
throw new ArgumentNullException();
}
Node[] nn = CreateContent(content, raw);
foreach (Node n in nn)
{
nodes.Add(n);
}
}
private void ReplaceContent(NodeCollection nodes, Node target, string content, string raw)
{
if (nodes == null || target == null)
{
throw new ArgumentNullException();
}
Node[] nn = CreateContent(content, raw);
foreach (Node n in nn)
{
nodes.InsertBefore(target, n);
}
nodes.Remove(target);
}
#endregion
}
}