Skip to content

Commit 96d4b1b

Browse files
committed
Make GetDescendents bail out when the first match is found
Previously, it first got all matches by walking the entire subtree, then ordered the results by start index and finally took the first one. Now, it uses a depth-first search approach to find the first result and bails out as soon as a match is found.
1 parent dc9039c commit 96d4b1b

File tree

1 file changed

+31
-2
lines changed

1 file changed

+31
-2
lines changed

Rubberduck.Parsing/ParserRuleContextExtensions.cs

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -197,8 +197,31 @@ public static bool ContainsTokenIndex(this ParserRuleContext context, int tokenI
197197
/// </summary>
198198
public static TContext GetDescendent<TContext>(this ParserRuleContext context) where TContext : ParserRuleContext
199199
{
200-
var descendents = GetDescendents<TContext>(context);
201-
return descendents.OrderBy(descendent => descendent.Start.TokenIndex).FirstOrDefault();
200+
if (context?.children == null)
201+
{
202+
return null;
203+
}
204+
205+
foreach (var child in context.children)
206+
{
207+
if (child == null)
208+
{
209+
continue;
210+
}
211+
212+
if (child is TContext match)
213+
{
214+
return match;
215+
}
216+
217+
var childResult = (child as ParserRuleContext)?.GetDescendent<TContext>();
218+
if (childResult != null)
219+
{
220+
return childResult;
221+
}
222+
}
223+
224+
return null;
202225
}
203226

204227
/// <summary>
@@ -228,6 +251,12 @@ public static VBAParser.EndOfLineContext GetFirstEndOfLine(this VBAParser.EndOfS
228251
{
229252
//This dedicated method exists for performance reasons on hot-paths.
230253
var individualEndOfStatements = endOfStatement.individualNonEOFEndOfStatement();
254+
255+
if (individualEndOfStatements == null)
256+
{
257+
return null;
258+
}
259+
231260
foreach (var individualEndOfStatement in individualEndOfStatements)
232261
{
233262
var endOfLine = individualEndOfStatement.endOfLine();

0 commit comments

Comments
 (0)