I've got a method for a parser that looks like so:
It's a bit long, but the major thing I want you to notice is that it calls itself within an if, for, if, and for loop. The method is essentially doing a preorder tree traversal.
I want to convert that over to an iterative method using a Stack, but don't know how, especially given that C# does not let you jump into a loop with a goto statement, which makes good sense.
If you don't know, no worries, just saying hello I'm a new member here!
C#:
public List<SequenceTokenTableState> BuildSequenceTokenTableRecursive(string sequenceName = "", int level = 0, List<string> breadCrumbs = null, bool skipAddedEntries = true, bool printOnConsole = false)
{
List<SequenceTokenTableState> list = new List<SequenceTokenTableState>();
if (!string.IsNullOrEmpty(sequenceName))
{
var seq = new ParserSequence();
if (SequencesDictionary.ContainsKey(sequenceName))
{
seq = SequencesDictionary[sequenceName];
}
else { return new List<SequenceTokenTableState>(); }
for(int i=0;i<seq.Sections.Count;i++)
{
var sec = seq.Sections;
if (sec.HasTokens || sec.HasDynamicRules) {
if (sec.HasTokens)
{
foreach(var token in sec.Tokens)
{
list.Add(new SequenceTokenTableState()
{
CallEnum = CallEnum.LexerCheckStart,
Comments = InputLexer.RulesDictionary[token].RuleName + "/{" + InputLexer.RulesDictionary[token].StringToken + "} Opt:" + sec.IsOptional + " Rep:" + sec.IsRepeating,
Level = level
});
}
}
if (sec.HasDynamicRules)
{
foreach(var rule in sec.DynamicRules)
{
list.Add(new SequenceTokenTableState()
{
CallEnum = CallEnum.LexerCheckStart,
Comments = InputLexer.RulesDictionary[rule].RuleName + ":::Dynamic/{" + InputLexer.RulesDictionary[rule].StringToken + "} Opt:" + sec.IsOptional + " Rep:" + sec.IsRepeating,
Level = level
});
}
}
}
if (sec.HasSequences)
{
for (int ii = 0; ii < sec.Sequences.Length; ii++)
{
var seq1 = sec.Sequences[ii];
var rundata = BuildSequenceTokenTableRecursive(seq1, level + 1);
list.Add(new SequenceTokenTableState()
{
CallEnum = CallEnum.GetMethodCallResult,
Level = level,
InnerStates = rundata,
SequenceName = seq1,
Comments = "Opt:" + sec.IsOptional + " Rep:" + sec.IsRepeating
});
}
}
}
return list;
}
return new List<SequenceTokenTableState>();
}
I want to convert that over to an iterative method using a Stack, but don't know how, especially given that C# does not let you jump into a loop with a goto statement, which makes good sense.
If you don't know, no worries, just saying hello I'm a new member here!
Last edited by a moderator: