diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 192e718f8e0fc..618526fada11f 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -4374,6 +4374,11 @@ namespace ts { return position >= span.start && position < textSpanEnd(span); } + /* @internal */ + export function textRangeContainsPositionInclusive(span: TextRange, position: number): boolean { + return position >= span.pos && position <= span.end; + } + // Returns true if 'span' contains 'other'. export function textSpanContainsTextSpan(span: TextSpan, other: TextSpan) { return other.start >= span.start && textSpanEnd(other) <= textSpanEnd(span); diff --git a/src/services/goToDefinition.ts b/src/services/goToDefinition.ts index 7060ffad6121e..b63e628403eef 100644 --- a/src/services/goToDefinition.ts +++ b/src/services/goToDefinition.ts @@ -271,7 +271,7 @@ namespace ts.GoToDefinition { } export function findReferenceInPosition(refs: ReadonlyArray, pos: number): FileReference | undefined { - return find(refs, ref => ref.pos <= pos && pos <= ref.end); + return find(refs, ref => textRangeContainsPositionInclusive(ref, pos)); } function getDefinitionInfoForFileReference(name: string, targetFileName: string): DefinitionInfo { diff --git a/src/services/utilities.ts b/src/services/utilities.ts index 86e6ebeb66a7b..789882a491c24 100644 --- a/src/services/utilities.ts +++ b/src/services/utilities.ts @@ -729,21 +729,14 @@ namespace ts { // this is token that starts at the end of previous token - return it return n; } - - const children = n.getChildren(); - for (const child of children) { + return firstDefined(n.getChildren(), child => { const shouldDiveInChildNode = // previous token is enclosed somewhere in the child (child.pos <= previousToken.pos && child.end > previousToken.end) || // previous token ends exactly at the beginning of child (child.pos === previousToken.end); - - if (shouldDiveInChildNode && nodeHasTokens(child, sourceFile)) { - return find(child); - } - } - - return undefined; + return shouldDiveInChildNode && nodeHasTokens(child, sourceFile) ? find(child) : undefined; + }); } } diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index 9d6917517c938..3eba56495178a 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -6627,6 +6627,7 @@ declare namespace ts { function textSpanEnd(span: TextSpan): number; function textSpanIsEmpty(span: TextSpan): boolean; function textSpanContainsPosition(span: TextSpan, position: number): boolean; + function textRangeContainsPositionInclusive(span: TextRange, position: number): boolean; function textSpanContainsTextSpan(span: TextSpan, other: TextSpan): boolean; function textSpanOverlapsWith(span: TextSpan, other: TextSpan): boolean; function textSpanOverlap(span1: TextSpan, span2: TextSpan): TextSpan | undefined;