* Allocates a declaration binding, sanitizing and disambiguating its preferred name. * * **Details** * * Exact names throw when invalid or already reserved. Names also avoid enclosing and nested scopes.
(
preferredName: string,
options?: { readonly exact?: boolean | undefined; readonly scope?: Scope | undefined }
)
| 454 | * Exact names throw when invalid or already reserved. Names also avoid enclosing and nested scopes. |
| 455 | */ |
| 456 | declare( |
| 457 | preferredName: string, |
| 458 | options?: { readonly exact?: boolean | undefined; readonly scope?: Scope | undefined } |
| 459 | ): DeclarationBinding { |
| 460 | const scope = this.#getScope(options?.scope ?? this.#root) |
| 461 | const takenBy = (name: string): string | undefined => { |
| 462 | if (this.#reserved.has(name)) return "it is reserved" |
| 463 | if (scope.nested.has(name)) return "a nested scope declares it" |
| 464 | for (let current: ScopeState | undefined = scope; current !== undefined; current = current.parent) { |
| 465 | if (current.taken.has(name)) { |
| 466 | return current === scope |
| 467 | ? "this scope declares it" |
| 468 | : "an enclosing scope declares it" |
| 469 | } |
| 470 | } |
| 471 | return undefined |
| 472 | } |
| 473 | if (options?.exact) { |
| 474 | const reason = isIdentifier(preferredName) ? takenBy(preferredName) : "it is not an identifier" |
| 475 | if (reason !== undefined) throw new Error(`Cannot declare exact name ${literal(preferredName)}: ${reason}`) |
| 476 | } |
| 477 | const name = options?.exact ? preferredName : allocate(preferredName, (name) => takenBy(name) !== undefined) |
| 478 | const local: DeclarationBinding = { ...binding(preferredName), name } |
| 479 | reserve(scope, name) |
| 480 | this.#bindings.set(local, name) |
| 481 | return local |
| 482 | } |
| 483 | |
| 484 | /** |
| 485 | * Registers a binding's declaration fragments and eager initialization dependencies. |