我遇到了一个非常奇怪的问题,在调试 Visual Studio .NET 单元测试时,我的执行从半可预测的位置跳到另一个位置。发生这种奇怪行为的方法是下面的“Parse(...)”。我在这个方法中指出了执行将跳转到的位置(“//EXCEPTION”)。我还指出了几个地方,在我的测试中,执行是在它奇怪地跳跃时(“//JUMP”)。跳跃会经常从同一个地方连续多次发生,然后从一个新的位置连续开始跳跃。执行跳转的这些地方要么是 switch 语句的开头,要么是代码块的结尾,这向我暗示指令指针发生了一些奇怪的事情,但我对 .NET 的了解还不够深,无法知道那可能是什么是。如果它有任何不同,执行不会跳转到“throw”语句之前,而是跳到刚刚抛出异常的执行点。很奇怪。
根据我的经验,执行跳转只会在解析嵌套命名组的内容时发生。
以下代码的目的背景:我试图实现的解决方案是一个简单的正则表达式解析器。这不是一个完整的正则表达式解析器。我的需要只是能够在正则表达式中找到特定的命名组,并用其他内容替换一些命名组的内容。所以基本上我只是运行一个正则表达式并跟踪我找到的命名组。我还跟踪未命名的组,因为我需要注意括号匹配和注释,以便注释的括号不会扰乱括号匹配。考虑到替换后,一段单独的(目前尚未实现的)代码将重建包含正则表达式的字符串。
我非常感谢任何关于可能发生的事情的建议;我很困惑!
示例解决方案
Here is a Visual Studio 2010 Solution (TAR 格式)包含我在下面讨论的所有代码。我在运行此解决方案时遇到错误(将单元测试项目“TestRegexParserLibTest”作为启动项目。)由于这似乎是一个偶发错误,如果其他人遇到同样的问题。
代码
我使用一些简单的类来组织结果:
// The root of the regex we are parsing
public class RegexGroupStructureRoot : ISuperRegexGroupStructure
{
public List<RegexGroupStructure> SubStructures { get; set; }
public RegexGroupStructureRoot()
{
SubStructures = new List<RegexGroupStructure>();
}
public override bool Equals(object obj) { ... }
}
// Either a RegexGroupStructureGroup or a RegexGroupStructureRegex
// Contained within the SubStructures of both RegexGroupStructureRoot and RegexGroupStructureGroup
public abstract class RegexGroupStructure
{
}
// A run of text containing regular expression characters (but not groups)
public class RegexGroupStructureRegex : RegexGroupStructure
{
public string Regex { get; set; }
public override bool Equals(object obj) { ... }
}
// A regular expression group
public class RegexGroupStructureGroup : RegexGroupStructure, ISuperRegexGroupStructure
{
// Name == null indicates an unnamed group
public string Name { get; set; }
public List<RegexGroupStructure> SubStructures { get; set; }
public RegexGroupStructureGroup()
{
SubStructures = new List<RegexGroupStructure>();
}
public override bool Equals(object obj) { ... }
}
// Items that contain SubStructures
// Either a RegexGroupStructureGroup or a RegexGroupStructureRoot
interface ISuperRegexGroupStructure
{
List<RegexGroupStructure> SubStructures { get; }
}
这是我实际解析正则表达式的方法(和关联的枚举/静态成员),返回一个 RegexGroupStructureRoot,其中包含所有已命名的组、未命名的组和找到的其他正则表达式字符。
using Re = System.Text.RegularExpressions
enum Mode
{
TopLevel, // Not in any group
BeginGroup, // Just encountered a character beginning a group: "("
BeginGroupTypeControl, // Just encountered a character controlling group type, immediately after beginning a group: "?"
NamedGroupName, // Reading the named group name (must have encountered a character indicating a named group type immediately following a group type control character: "<" after "?")
NamedGroup, // Reading the contents of a named group
UnnamedGroup, // Reading the contents of an unnamed group
}
static string _NamedGroupNameValidCharRePattern = "[A-Za-z0-9_]";
static Re.Regex _NamedGroupNameValidCharRe;
static RegexGroupStructureParser()
{
_NamedGroupNameValidCharRe = new Re.Regex(_NamedGroupNameValidCharRePattern);
}
public static RegexGroupStructureRoot Parse(string regex)
{
string newLine = Environment.NewLine;
int newLineLen = newLine.Length;
// A record of the parent structures that the parser has created
Stack<ISuperRegexGroupStructure> parentStructures = new Stack<ISuperRegexGroupStructure>();
// The current text we've encountered
StringBuilder textConsumer = new StringBuilder();
// Whether the parser is in an escape sequence
bool escaped = false;
// Whether the parser is in an end-of-line comment (such comments run from a hash-sign ('#') to the end of the line
// The other type of .NET regular expression comment is the group-comment: (?#This is a comment)
// We do not need to specially handle this type of comment since it is treated like an unnamed
// group.
bool commented = false;
// The current mode of the parsing process
Mode mode = Mode.TopLevel;
// Push a root onto the parents to accept whatever regexes/groups we encounter
parentStructures.Push(new RegexGroupStructureRoot());
foreach (char chr in regex.ToArray())
{
if (escaped) // JUMP
{
textConsumer.Append(chr);
escaped = false;
}
else if (chr.Equals('#'))
{
textConsumer.Append(chr);
commented = true;
}
else if (commented)
{
textConsumer.Append(chr);
string txt = textConsumer.ToString();
int txtLen = txt.Length;
if (txtLen >= newLineLen &&
// Does the current text end with a NewLine?
txt.Substring(txtLen - 1 - newLineLen, newLineLen) == newLine)
{
// If so we're no longer in the comment
commented = false;
}
}
else
{
switch (mode) // JUMP
{
case Mode.TopLevel:
switch (chr)
{
case '\\':
textConsumer.Append(chr); // Append the backslash
escaped = true;
break;
case '(':
beginNewGroup(parentStructures, ref textConsumer, ref mode);
break;
case ')':
// Can't close a group if we're already at the top-level
throw new InvalidRegexFormatException("Too many ')'s.");
default:
textConsumer.Append(chr);
break;
}
break;
case Mode.BeginGroup:
switch (chr)
{
case '?':
// If it's an unnamed group, we'll re-add the question mark.
// If it's a named group, named groups reconstruct question marks so no need to add it.
mode = Mode.BeginGroupTypeControl;
break;
default:
// Only a '?' can begin a named group. So anything else begins an unnamed group.
parentStructures.Peek().SubStructures.Add(new RegexGroupStructureRegex()
{
Regex = textConsumer.ToString()
});
textConsumer = new StringBuilder();
parentStructures.Push(new RegexGroupStructureGroup()
{
Name = null, // null indicates an unnamed group
SubStructures = new List<RegexGroupStructure>()
});
mode = Mode.UnnamedGroup;
break;
}
break;
case Mode.BeginGroupTypeControl:
switch (chr)
{
case '<':
mode = Mode.NamedGroupName;
break;
default:
// We previously read a question mark to get here, but the group turned out not to be a named group
// So add back in the question mark, since unnamed groups don't reconstruct with question marks
textConsumer.Append('?' + chr);
mode = Mode.UnnamedGroup;
break;
}
break;
case Mode.NamedGroupName:
if (chr.Equals( '>'))
{
// '>' closes the named group name. So extract the name
string namedGroupName = textConsumer.ToString();
if (namedGroupName == String.Empty)
throw new InvalidRegexFormatException("Named group names cannot be empty.");
// Create the new named group
RegexGroupStructureGroup newNamedGroup = new RegexGroupStructureGroup() {
Name = namedGroupName,
SubStructures = new List<RegexGroupStructure>()
};
// Add this group to the current parent
parentStructures.Peek().SubStructures.Add(newNamedGroup);
// ...and make it the new parent.
parentStructures.Push(newNamedGroup);
textConsumer = new StringBuilder();
mode = Mode.NamedGroup;
}
else if (_NamedGroupNameValidCharRe.IsMatch(chr.ToString()))
{
// Append any valid named group name char to the growing named group name
textConsumer.Append(chr);
}
else
{
// chr is neither a valid named group name character, nor the character that closes the named group name (">"). Error.
throw new InvalidRegexFormatException(String.Format("Invalid named group name character: {0}", chr)); // EXCEPTION
}
break; // JUMP
case Mode.NamedGroup:
case Mode.UnnamedGroup:
switch (chr) // JUMP
{
case '\\':
textConsumer.Append(chr);
escaped = true;
break;
case ')':
closeGroup(parentStructures, ref textConsumer, ref mode);
break;
case '(':
beginNewGroup(parentStructures, ref textConsumer, ref mode);
break;
default:
textConsumer.Append(chr);
break;
}
break;
default:
throw new Exception("Exhausted Modes");
}
} // JUMP
}
ISuperRegexGroupStructure finalParent = parentStructures.Pop();
Debug.Assert(parentStructures.Count < 1, "Left parent structures on the stack.");
Debug.Assert(finalParent.GetType().Equals(typeof(RegexGroupStructureRoot)), "The final parent must be a RegexGroupStructureRoot");
string finalRegex = textConsumer.ToString();
if (!String.IsNullOrEmpty(finalRegex))
finalParent.SubStructures.Add(new RegexGroupStructureRegex() {
Regex = finalRegex
});
return finalParent as RegexGroupStructureRoot;
}
这是一个单元测试,将测试该方法是否有效(注意,可能不是 100% 正确,因为我什至没有通过对 RegexGroupStructureParser.Parse 的调用。)
[TestMethod]
public void ParseTest_Short()
{
string regex = @"
(?<Group1>
,?\s+
(?<Group1_SubGroup>
[\d–-]+ # One or more digits, hyphen, and/or n-dash
)
)
";
RegexGroupStructureRoot expected = new RegexGroupStructureRoot()
{
SubStructures = new List<RegexGroupStructure>()
{
new RegexGroupStructureGroup() {
Name = "Group1",
SubStructures = new List<RegexGroupStructure> {
new RegexGroupStructureRegex() {
Regex = @"
,?\s+
"
},
new RegexGroupStructureGroup() {
Name = "Group1_Subgroup",
SubStructures = new List<RegexGroupStructure>() {
new RegexGroupStructureRegex() {
Regex = @"
[\d–-]+ # One or more digits, hyphen, and/or n-dash
"
}
}
},
new RegexGroupStructureRegex() {
Regex = @"
"
}
}
},
new RegexGroupStructureRegex() {
Regex = @"
"
},
}
};
RegexGroupStructureRoot actual = RegexGroupStructureParser.Parse(regex);
Assert.AreEqual(expected, actual);
}
最佳答案
您的解决方案的测试用例确实导致抛出的“无效命名组名称字符”异常在 break;
而不是 throw
处停止线。我在一个案例中使用嵌套 if 装配了一个测试文件,以查看异常是否在我的一个项目中类似地触发,但它没有:停止的行是 throw
语句本身。
但是,当我启用编辑(在您的项目中使用编辑并继续)时,当前行倒回到 throw 语句。我没有查看生成的 IL,但我怀疑抛出(这将终止案例而不需要像这样遵循“中断”:)
case 1:
do something
break;
case 2:
throw ... //No break required.
case 3:
正在以一种混淆显示的方式进行优化,但不会混淆实际执行,甚至不会混淆编辑和继续功能。如果编辑并继续工作并且抛出的异常被正确捕获或显示,我怀疑您有一个可以忽略的显示异常(尽管我会将其与该文件一起报告给 Microsoft,因为它 是可重现的) .
关于c# - 调试单元测试时执行随机跳转到抛出的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6567861/