microsoft/typespec

Public

mirrored from https://github.com/microsoft/typespecAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
copilot/fix-1919

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

packages/asset-emitter/src/ref-scope.ts

40lines · modecode

1import type { Declaration, Scope } from "./types.js";
2
3export function scopeChain<T>(scope: Scope<T> | null) {
4 const chain = [];
5 while (scope) {
6 chain.unshift(scope);
7 scope = scope.parentScope;
8 }
9
10 return chain;
11}
12
13/**
14 * Resolve relative scopes between the current scope and the target declaration.
15 * @param target The target declaration
16 * @param currentScope Current scope
17 * @returns
18 */
19export function resolveDeclarationReferenceScope<T>(
20 target: Declaration<T>,
21 currentScope: Scope<T>,
22) {
23 const targetScope = target.scope;
24 const targetChain = scopeChain(targetScope);
25 const currentChain = scopeChain(currentScope);
26 let diffStart = 0;
27 while (
28 targetChain[diffStart] &&
29 currentChain[diffStart] &&
30 targetChain[diffStart] === currentChain[diffStart]
31 ) {
32 diffStart++;
33 }
34
35 const pathUp: Scope<T>[] = currentChain.slice(diffStart);
36 const pathDown: Scope<T>[] = targetChain.slice(diffStart);
37
38 const commonScope = targetChain[diffStart - 1] ?? null;
39 return { pathUp, pathDown, commonScope };
40}
41