htmlcc/htmlcc/emitter/__init__.py
2025-05-14 18:26:10 +10:00

74 lines
2.1 KiB
Python

# htmlcc - Statically compiled HTML templates for C
# Copyright (C) 2025 Lee Yingtong Li
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
class Emitter:
"""Base class for emitters"""
def emit(self, s: str) -> None:
print(s)
def emit_raw_c(self, raw_c: str) -> None:
"""Emit raw C code"""
self.emit(raw_c)
def emit_preamble(self) -> None:
"""Emit the preamble for the output file"""
return
def output_literal_string(self, literal_string: str) -> None:
"""Emit code to output a literal string"""
raise NotImplementedError()
def output_variable_as_attr(self, variable: str) -> None:
"""Emit code to output a variable, escaping for HTML text"""
raise NotImplementedError()
def output_variable_as_text(self, variable: str) -> None:
"""Emit code to output a variable, escaping for HTML text"""
raise NotImplementedError()
def start_page(self, page_name: str) -> None:
"""Called at {% page ... %}"""
self.emit('void ' + page_name + '(void) {')
def end_page(self) -> None:
"""Called at {% endpage %}"""
self.emit('}')
# Utility functions
@staticmethod
def escape_cstr(s: str) -> str:
"""Escape the string as a C string, wrapping with `"` character"""
s = s.replace('\\', '\\\\')
s = s.replace('"', '\\"')
s = s.replace('\n', '\\n')
return f'"{s}"'
# Known emitter registry
known_emitters = {}
def register_emitter(name: str, emitter: type[Emitter]) -> None:
known_emitters[name] = emitter