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 CSourceWriter(FileWriter): 24 """Represents a C or C++ source 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.headers: dict[str, None] = {} 42 43 @override 44 def write_prologue(self, f: TextIO): 45 if self.desc.kind != FileKind.TEMPLATE: 46 f.write("#pragma clang diagnostic push\n") 47 f.write('#pragma clang diagnostic ignored "-Weverything"\n') 48 f.write('#pragma clang diagnostic warning "-Wextra"\n') 49 f.write('#pragma clang diagnostic warning "-Wall"\n') 50 for header in self.headers: 51 f.write(f'#include "{header}"\n') 52 53 @override 54 def write_epilogue(self, f: TextIO): 55 if self.desc.kind != FileKind.TEMPLATE: 56 f.write("#pragma clang diagnostic pop\n") 57 58 def add_include(self, *headers: str): 59 for header in headers: 60 self.headers.setdefault(header, None) 61 62 63class CHeaderWriter(CSourceWriter): 64 """Represents a C or C++ header file.""" 65 66 @override 67 def write_prologue(self, f: TextIO): 68 f.write("#pragma once\n") 69 super().write_prologue(f)