我遇到一个非常奇怪的问题,即在调试Visual Studio .NET单元测试时,我的执行从半可预测位置跳转到另一个位置。发生这种奇怪行为的方法是“Parse(...)”,如下所示。我在这个方法中指出了执行将跳转到的一个位置(“// EXCEPTION”)。我还指出了几个地方,在我的测试中,执行是奇怪的跳跃(“// JUMP”)。跳跃将经常连续几次从同一个地方发生,然后连续地从新位置开始跳跃。这些执行跳转的地方要么是switch语句的开头,要么是代码块的结尾,这对我来说,指令指针有一些时髦的东西,但是我不够精通.NET知道那些东西可能是什么是。如果它有任何区别,执行不会跳转到“throw”语句之前,而是跳转到刚刚抛出异常的执行点。很奇怪。
根据我的经验,执行跳转仅在解析嵌套命名组的内容时发生。
下面的代码声称要做的背景:我试图实现的解决方案是一个简单的正则表达式解析器。这不是一个完整的正则表达式解析器。我的需求只是能够在正则表达式中定位特定的命名组,并用其他内容替换一些命名组的内容。所以基本上我只是运行正则表达式并跟踪我找到的命名组。我还跟踪未命名的组,因为我需要知道括号匹配和注释,因此注释括号不会扰乱paren-matching。在考虑替换后,单独的(并且尚未实现的)代码将重构包含正则表达式的字符串。
我非常感谢有关可能正在发生的事情的任何建议;我很困惑!
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);
}
答案 0 :(得分:1)
您的解决方案的测试用例 导致抛出的“无效的命名组名称字符”异常停止在break;
而不是throw
行。我在一个案例中使用嵌套if来装配一个测试文件,以查看异常是否在我的一个项目中触发相似而不是:停止的行是throw
语句本身。
但是,当我启用编辑(在项目中使用编辑和继续)时,当前行会回退到throw语句。我没有看过生成的IL,但是我怀疑是throw(它会终止这个案例而不需要像“break”那样遵循:)
case 1:
do something
break;
case 2:
throw ... //No break required.
case 3:
正在以混淆显示的方式进行优化,而不是实际执行甚至是编辑和继续功能。如果编辑并继续工作并且正确捕获或显示抛出的异常,我怀疑您有一个可以忽略的显示异常(尽管我会将其与该文件一起报告给Microsoft,因为它 可重现) 。
答案 1 :(得分:0)
终于解决了这个问题。在closeGroup
中,我在问题中引用并存在于链接代码中,我将模式设置为NamedGroupName
而不是NamedGroup
。这仍然没有回答奇怪的指令指针/异常业务,但至少现在我没有得到意外的异常并且解析器解析。