|
| 1 | +# Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | +# |
| 3 | +# This source code is licensed under the MIT license found in the |
| 4 | +# LICENSE file in the root directory of this source tree. |
| 5 | + |
| 6 | +from __future__ import annotations |
| 7 | + |
| 8 | +from typing import TYPE_CHECKING |
| 9 | + |
| 10 | +from natsort import natsorted |
| 11 | + |
| 12 | +from ..utils import qualify_type_str |
| 13 | +from .base_scope_kind import ScopeKind |
| 14 | + |
| 15 | +if TYPE_CHECKING: |
| 16 | + from .scope import Scope |
| 17 | + |
| 18 | + |
| 19 | +class ProtocolScopeKind(ScopeKind): |
| 20 | + class Base: |
| 21 | + def __init__( |
| 22 | + self, name: str, protection: str, virtual: bool, refid: str |
| 23 | + ) -> None: |
| 24 | + self.name: str = name |
| 25 | + self.protection: str = protection |
| 26 | + self.virtual: bool = virtual |
| 27 | + self.refid: str = refid |
| 28 | + |
| 29 | + def __init__(self) -> None: |
| 30 | + super().__init__("protocol") |
| 31 | + self.base_classes: [ProtocolScopeKind.Base] = [] |
| 32 | + |
| 33 | + def add_base(self, base: ProtocolScopeKind.Base | [ProtocolScopeKind.Base]) -> None: |
| 34 | + if isinstance(base, list): |
| 35 | + for b in base: |
| 36 | + self.base_classes.append(b) |
| 37 | + else: |
| 38 | + self.base_classes.append(base) |
| 39 | + |
| 40 | + def close(self, scope: Scope) -> None: |
| 41 | + """Qualify base class names and their template arguments.""" |
| 42 | + for base in self.base_classes: |
| 43 | + base.name = qualify_type_str(base.name, scope) |
| 44 | + |
| 45 | + def to_string(self, scope: Scope) -> str: |
| 46 | + result = "" |
| 47 | + |
| 48 | + bases = [] |
| 49 | + for base in self.base_classes: |
| 50 | + base_text = [base.protection] |
| 51 | + if base.virtual: |
| 52 | + base_text.append("virtual") |
| 53 | + base_text.append(base.name) |
| 54 | + bases.append(" ".join(base_text)) |
| 55 | + |
| 56 | + inheritance_string = " : " + ", ".join(bases) if bases else "" |
| 57 | + |
| 58 | + result += f"{self.name} {scope.get_qualified_name()}{inheritance_string} {{" |
| 59 | + |
| 60 | + stringified_members = [] |
| 61 | + for member in scope.get_members(): |
| 62 | + stringified_members.append(member.to_string(2)) |
| 63 | + stringified_members = natsorted(stringified_members) |
| 64 | + result += ("\n" if len(stringified_members) > 0 else "") + "\n".join( |
| 65 | + stringified_members |
| 66 | + ) |
| 67 | + |
| 68 | + result += "\n}" |
| 69 | + |
| 70 | + return result |
0 commit comments