mirror of
https://github.com/chylex/Code-Statistics.git
synced 2025-03-15 00:15:42 +01:00
Add JavaCodeParser.SkipToIfBalanced with unit tests
This commit is contained in:
parent
6158a62c18
commit
f0daf254b5
CodeStatistics/Handling/Languages/Java
CodeStatisticsTests/Languages/Java
@ -17,6 +17,39 @@ namespace CodeStatistics.Handling.Languages.Java{
|
||||
return new JavaCodeParser(newCode ?? string.Empty);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Skips to the next matching character where the brackets ([{ }]) are balanced, and returns itself.
|
||||
/// If the skip fails, the cursor will not move.
|
||||
/// </summary>
|
||||
public JavaCodeParser SkipToIfBalanced(char chr){
|
||||
int prevCursor = cursor;
|
||||
Stack<char> bracketStack = new Stack<char>(4);
|
||||
|
||||
while(cursor < length){
|
||||
if (bracketStack.Count == 0 && Char == chr)break;
|
||||
|
||||
switch(Char){
|
||||
case '(': bracketStack.Push(')'); break;
|
||||
case '[': bracketStack.Push(']'); break;
|
||||
case '{': bracketStack.Push('}'); break;
|
||||
|
||||
case ')': case ']': case '}':
|
||||
if (bracketStack.Count == 0 || bracketStack.Pop() != Char){
|
||||
cursor = prevCursor;
|
||||
return this;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
++cursor;
|
||||
}
|
||||
|
||||
if (Char != chr || bracketStack.Count > 0)cursor = prevCursor;
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the entire full type name, which consists of one or more identifiers separated by the dot character. <para/>
|
||||
/// https://docs.oracle.com/javase/specs/jls/se8/html/jls-6.html#d5e7695
|
||||
|
@ -36,5 +36,31 @@ namespace CodeStatisticsTests.Languages.Java{
|
||||
Annotation? annotation8 = new JavaCodeParser("@123").ReadAnnotation();
|
||||
Assert.IsFalse(annotation8.HasValue);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TestBalanceSkip(){
|
||||
JavaCodeParser parser1 = new JavaCodeParser("simple;D");
|
||||
parser1.SkipToIfBalanced(';');
|
||||
Assert.AreEqual(';',parser1.Char);
|
||||
Assert.AreEqual('D',parser1.Next());
|
||||
|
||||
JavaCodeParser parser2 = new JavaCodeParser("find ( ;semicolon {[ ( ; ) ; ]} ; keep looking ) ;-)");
|
||||
parser2.SkipToIfBalanced(';');
|
||||
Assert.AreEqual(';',parser2.Char);
|
||||
Assert.AreEqual('-',parser2.Next());
|
||||
Assert.AreEqual(')',parser2.Next());
|
||||
|
||||
JavaCodeParser parser3 = new JavaCodeParser("nope");
|
||||
parser3.SkipToIfBalanced(';');
|
||||
Assert.AreEqual('n',parser3.Char);
|
||||
|
||||
JavaCodeParser parser4 = new JavaCodeParser("cannot find (;;;)");
|
||||
parser4.SkipToIfBalanced(';');
|
||||
Assert.AreEqual('c',parser4.Char);
|
||||
|
||||
JavaCodeParser parser5 = new JavaCodeParser("( invalid [ balance ) ] ;");
|
||||
parser5.SkipToIfBalanced(';');
|
||||
Assert.AreEqual('(',parser5.Char);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user