|
cc5d8294
»
|
jagregory |
2008-09-01 |
Implemented brace matching.... |
1 |
using System; |
| |
2 |
using System.Collections.Generic; |
| |
3 |
|
| |
4 |
namespace Boo.BooLangService.StringParsing |
| |
5 |
{ |
| |
6 |
public class StringWalker |
| |
7 |
{ |
| |
8 |
private const char LeftParenthesis = '('; |
| |
9 |
private const char RightParenthesis = ')'; |
| |
10 |
private const char DoubleQuote = '"'; |
| |
11 |
private const char BackSlash = '\\'; |
| |
12 |
|
| |
13 |
private bool abort; |
| |
14 |
private Stack<StringWalkerState> state; |
| |
15 |
|
| |
16 |
public IEnumerable<StringPosition> Iterate(string value) |
| |
17 |
{ |
| |
18 |
state = new Stack<StringWalkerState>(); |
| |
19 |
|
| |
20 |
for (var currentIndex = 0; currentIndex < value.Length; currentIndex++) |
| |
21 |
{ |
| |
22 |
if (abort) break; |
| |
23 |
|
| |
24 |
var currentChar = value[currentIndex]; |
| |
25 |
|
| |
26 |
if (currentChar == LeftParenthesis) |
| |
27 |
state.Push(StringWalkerState.InsideParentheses); |
| |
28 |
else if (currentChar == RightParenthesis && StateIs(StringWalkerState.InsideParentheses)) |
| |
29 |
state.Pop(); |
| |
30 |
else if (currentChar == DoubleQuote && StateIs(StringWalkerState.InsideString)) |
| |
31 |
state.Pop(); |
| |
32 |
else if (currentChar == DoubleQuote) |
| |
33 |
state.Push(StringWalkerState.InsideString); |
| |
34 |
else if (currentChar == BackSlash && StateIs(StringWalkerState.InsideString)) |
| |
35 |
currentIndex += 1; // skip next (escaped) char |
| |
36 |
|
|
54d4bcef
»
|
jagregory |
2008-09-01 |
Some changes to brace match... |
37 |
if (ShouldYield(currentChar)) |
| |
38 |
yield return new StringPosition(currentChar, currentIndex); |
|
cc5d8294
»
|
jagregory |
2008-09-01 |
Implemented brace matching.... |
39 |
} |
| |
40 |
} |
| |
41 |
|
|
54d4bcef
»
|
jagregory |
2008-09-01 |
Some changes to brace match... |
42 |
protected virtual bool ShouldYield(char currentChar) |
| |
43 |
{ |
| |
44 |
return true; |
| |
45 |
} |
| |
46 |
|
|
cc5d8294
»
|
jagregory |
2008-09-01 |
Implemented brace matching.... |
47 |
public bool StateIs(StringWalkerState expectedState) |
| |
48 |
{ |
| |
49 |
if (state.Count == 0) return false; |
| |
50 |
|
| |
51 |
return state.Peek() == expectedState; |
| |
52 |
} |
| |
53 |
|
| |
54 |
public void Abort() |
| |
55 |
{ |
| |
56 |
abort = true; |
| |
57 |
} |
| |
58 |
|
| |
59 |
public bool HasNoState |
| |
60 |
{ |
| |
61 |
get { return state == null || state.Count == 0; } |
| |
62 |
} |
| |
63 |
} |
| |
64 |
} |