1# coding=utf-8 2# 3# Copyright (c) 2025 Huawei Device Co., Ltd. 4# Licensed under the Apache License, Version 2.0 (the "License"); 5# you may not use this file except in compliance with the License. 6# You may obtain a copy of the License at 7# 8# http://www.apache.org/licenses/LICENSE-2.0 9# 10# Unless required by applicable law or agreed to in writing, software 11# distributed under the License is distributed on an "AS IS" BASIS, 12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13# See the License for the specific language governing permissions and 14# limitations under the License. 15 16from typing import TextIO 17 18from typing_extensions import override 19 20from taihe.utils.outputs import DEFAULT_INDENT, FileKind, FileWriter, OutputManager 21 22 23class StsWriter(FileWriter): 24 """Represents a static type script (sts) file.""" 25 26 @override 27 def __init__( 28 self, 29 om: OutputManager, 30 relative_path: str, 31 file_kind: FileKind, 32 indent_unit: str = DEFAULT_INDENT, 33 ): 34 super().__init__( 35 om, 36 relative_path=relative_path, 37 file_kind=file_kind, 38 default_indent=indent_unit, 39 comment_prefix="// ", 40 ) 41 self.import_dict: dict[str, tuple[str, str | None]] = {} 42 43 @override 44 def write_prologue(self, f: TextIO): 45 f.write("'use static'\n") 46 for import_name, decl_pair in self.import_dict.items(): 47 module_name, decl_name = decl_pair 48 if decl_name is None: 49 import_str = f"* as {import_name}" 50 elif decl_name == "default": 51 import_str = import_name 52 elif decl_name == import_name: 53 import_str = f"{{{decl_name}}}" 54 else: 55 import_str = f"{{{decl_name} as {import_name}}}" 56 f.write(f"import {import_str} from '{module_name}';\n") 57 58 def add_import_module( 59 self, 60 module_name: str, 61 import_name: str, 62 ): 63 self._add_import(import_name, (module_name, None)) 64 65 def add_import_default( 66 self, 67 module_name: str, 68 import_name: str, 69 ): 70 self._add_import(import_name, (module_name, "default")) 71 72 def add_import_decl( 73 self, 74 module_name: str, 75 decl_name: str, 76 import_name: str | None = None, 77 ): 78 if import_name is None: 79 import_name = decl_name 80 self._add_import(import_name, (module_name, decl_name)) 81 82 def _add_import( 83 self, 84 import_name: str, 85 new_pair: tuple[str, str | None], 86 ): 87 import_dict = self.import_dict 88 old_pair = import_dict.setdefault(import_name, new_pair) 89 if old_pair != new_pair: 90 raise ValueError( 91 f"Duplicate import for {import_name!r}: {old_pair} vs {new_pair}" 92 )