• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python3
2# -*- coding: utf-8 -*-
3#
4# Copyright (c) 2024 Huawei Device Co., Ltd.
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16#
17
18from typing import Any, Generic, Optional, Tuple, Type, TypeVar
19
20import rich.repr
21
22from .base import MirrorMeta, arkts_str
23from .type_cache import type_cache
24
25T = TypeVar("T")
26
27
28class PrimitiveMeta(MirrorMeta):
29
30    def __new__(mcls, name: str, bases: Tuple[Type], namespace: dict[str, Any], **kwargs: Any):
31        cls = super().__new__(mcls, name, bases, namespace, **kwargs)
32        t: Type = rich.repr.auto(cls)
33        return t
34
35
36class Primitive(Generic[T], metaclass=PrimitiveMeta):
37    """Base class for ArkTS mirror primitives."""
38
39    value: T
40
41    __slots__ = ("value",)
42
43    def __init__(self, value: T | None = None) -> None:
44        if value is not None:
45            self.value = value
46
47    def __eq__(self, other: Any) -> bool:
48        if type(self) is type(other) or type(self).__name__ == type(other).__name__:
49            value = other.value if hasattr(other, "value") else other
50            return self.value == value
51        if not hasattr(other, "value"):
52            return self.value == other
53        return False
54
55    # CC-OFFNXT(G.NAM.05) Standard function from rich package
56    def __rich_repr__(self):
57        return [self.value]
58
59    # CC-OFFNXT(G.NAM.05) internal function name
60    def __arkts_str__(self, *, depth: Optional[int] = None) -> str:
61        return arkts_str(self.value)
62
63    def __hash__(self) -> int:
64        return hash(type(self).__name__) ^ hash(self.value)
65
66
67@type_cache(scope="session")
68def mirror_primitive_type(cls_name: str) -> Type:
69    return PrimitiveMeta(cls_name, (Primitive,), {}, module=__package__)
70
71
72def mirror_primitive(cls_name: str, value: T) -> Primitive[T]:
73    t = mirror_primitive_type(cls_name)
74    return t(value)
75