idlize
75 строк · 2.7 Кб
1/*
2* Copyright (c) 2024 Huawei Device Co., Ltd.
3* Licensed under the Apache License, Version 2.0 (the "License");
4* you may not use this file except in compliance with the License.
5* You may obtain a copy of the License at
6*
7* http://www.apache.org/licenses/LICENSE-2.0
8*
9* Unless required by applicable law or agreed to in writing, software
10* distributed under the License is distributed on an "AS IS" BASIS,
11* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12* See the License for the specific language governing permissions and
13* limitations under the License.
14*/
15
16
17import * as ts from "typescript";
18import { getDeclarationsByNode } from "../util";
19import { PeerGeneratorConfig } from "./PeerGeneratorConfig";
20
21export enum InheritanceRole {
22Finalizable,
23PeerNode,
24Root,
25Heir,
26Standalone,
27}
28
29export function determineInheritanceRole(name: string): InheritanceRole {
30if (PeerGeneratorConfig.rootComponents.includes(name)) return InheritanceRole.Root
31if (PeerGeneratorConfig.standaloneComponents.includes(name)) return InheritanceRole.Standalone
32return InheritanceRole.Heir
33}
34
35export function determineParentRole(name: string|undefined, parent: string | undefined): InheritanceRole {
36if (!name) throw new Error(`name must be known: ${parent}`)
37if (parent === undefined) {
38if (isStandalone(name)) return InheritanceRole.PeerNode
39if (isCommonMethod(name)) return InheritanceRole.PeerNode
40if (isRoot(name)) return InheritanceRole.PeerNode
41throw new Error(`Expected check to be exhaustive. node: ${name}`)
42}
43if (isRoot(parent)) return InheritanceRole.Root
44return InheritanceRole.Heir
45}
46
47export function isCommonMethod(name: string): boolean {
48return name === "CommonMethod"
49}
50
51export function isRoot(name: string): boolean {
52return determineInheritanceRole(name) === InheritanceRole.Root
53}
54
55export function isStandalone(name: string): boolean {
56return determineInheritanceRole(name) === InheritanceRole.Standalone
57}
58
59export function isHeir(name: string): boolean {
60return determineInheritanceRole(name) === InheritanceRole.Heir
61}
62
63export function singleParentDeclaration(
64typeChecker: ts.TypeChecker,
65component: ts.ClassDeclaration | ts.InterfaceDeclaration
66): ts.ClassDeclaration | ts.InterfaceDeclaration | undefined {
67const parentTypeNode = component.heritageClauses
68?.filter(it => it.token == ts.SyntaxKind.ExtendsKeyword)[0]?.types[0]?.expression
69if (parentTypeNode) {
70const declaration = getDeclarationsByNode(typeChecker, parentTypeNode)
71.find(it => ts.isClassDeclaration(it) || ts.isInterfaceDeclaration(it))
72return declaration as (ts.ClassDeclaration | ts.InterfaceDeclaration | undefined)
73}
74return undefined
75}
76