• 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
18import builtins
19import types
20from typing import Any, List, Optional, Protocol, Tuple, Type, runtime_checkable
21
22from ..logs import logger
23
24LOG = logger(__name__)
25
26DEFAULT_ARKTS_STR_DEPTH = 10
27
28
29class MirrorMeta(type):
30    def __new__(mcls, name: str, bases: Tuple[type], namespace: dict[str, Any], module: Any = None, **kwargs: Any):
31        namespace = {
32            **namespace,
33            "__arkts_mirror_type__": True,
34        }
35        if module:
36            namespace["__module__"] = module
37        return super().__new__(mcls, name, bases, namespace, **kwargs)
38
39    def __hash__(self) -> int:
40        return id(self)
41
42
43def is_mirror_type(t: Type) -> bool:
44    return getattr(t, "__arkts_mirror_type__", False)
45
46
47@runtime_checkable
48class ArkPrintable(Protocol):
49    def __arkts_str__(
50        self,
51        *,
52        depth: Optional[int] = None,
53    ) -> str:
54        pass
55
56
57def _arkts_str(obj: Any, *, depth: Optional[int] = None) -> str:
58    if isinstance(obj, ArkPrintable):
59        return obj.__arkts_str__(depth=depth)
60
61    b = builtins
62    t = types
63    match type(obj):
64        case b.bool:
65            return "true" if obj else "false"
66        case b.int | b.float:
67            return str(obj)
68        case b.str:
69            return obj  # It should be changed to 'repr()' when the string representation in runtime is corrected.
70        case t.NoneType:
71            return "null"
72        case b.list:
73            if depth == 0:
74                return "[...]"
75            next_depth = depth - 1 if depth is not None else None
76            return f"[{', '.join([_arkts_str(o, depth=next_depth) for o in obj])}]"
77        case _:
78            return repr(obj)
79
80
81def arkts_str(*objs, depth: Optional[int] = DEFAULT_ARKTS_STR_DEPTH) -> str:
82    match len(objs):
83        case 0:
84            return ""
85        case 1:
86            return _arkts_str(objs[0], depth=depth)
87        case _:
88            return ", ".join(arkts_str_list(list(objs), depth=depth))
89
90
91def arkts_str_list(objs: List, depth: Optional[int] = DEFAULT_ARKTS_STR_DEPTH) -> List[str]:
92    return [_arkts_str(o, depth=depth) for o in objs]
93