| #!/usr/bin/env python3 | |
| """Generate the zmij blocks in include/fmt/format.h and format-inl.h. | |
| Usage: | |
| import-zmij.py <zmij-dir> | |
| Replaces the block in format.h with zmij.h and the one in format-inl.h with | |
| zmij.cc, at the commit checked out in <zmij-dir>, without the integer | |
| formatting, in fmt::zmij and with the ZMIJ_ macros replaced with fmt's or | |
| renamed to FMT_ZMIJ_. The configuration before the format.h block is maintained | |
| by hand, as is the global module fragment in src/fmt.cc, which must include the | |
| standard headers that zmij uses. | |
| """ | |
| import os, re, subprocess, sys | |
| fmt_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | |
| include_dir = os.path.join(fmt_dir, 'include', 'fmt') | |
| marker = '// Generated by support/import-zmij.py' | |
| # The format.h block has no header, so it is found by the includes it starts | |
| # with. | |
| h_marker = '#ifndef FMT_MODULE\n# include <assert.h> // assert\n' | |
| end_marker = '\nFMT_END_NAMESPACE\n' | |
| # ZMIJ_ macros that are replaced with the FMT_ ones of the same name, so that | |
| # zmij follows fmt's configuration, e.g. not using __int128 with NVCC and | |
| # clang-cl. The rest are renamed to FMT_ZMIJ_. | |
| fmt_macros = ['CPLUSPLUS', 'MSC_VERSION', 'CLANG_VERSION', 'HAS_BUILTIN', | |
| 'HAS_CPP_ATTRIBUTE', 'USE_CONSTEXPR', 'CONSTEXPR', 'CONSTEXPR20', | |
| 'USE_INT128', 'USE_FLOAT128', 'INLINE', 'OPTIMIZE_SIZE', | |
| 'USE_IS_CONSTANT_EVALUATED'] | |
| def sub(text, old, new): | |
| """Replaces old with new, failing unless old occurs exactly once, so that a | |
| change in zmij's layout stops the import instead of breaking the block.""" | |
| n = text.count(old) | |
| if n != 1: | |
| sys.exit(f'{old[:60]!r} occurs {n} times, expected 1') | |
| return text.replace(old, new) | |
| def cut(text, begin, end): | |
| """Removes text from begin, which must occur once, through the next end.""" | |
| i = text.find(begin) | |
| if i < 0 or text.find(begin, i + 1) >= 0: | |
| sys.exit(f'{begin[:60]!r} must occur once') | |
| j = text.find(end, i) | |
| if j < 0: | |
| sys.exit(f'{end[:60]!r} not found after {begin[:60]!r}') | |
| return text[:i] + text[j + len(end):] | |
| def read(filename): | |
| with open(filename, encoding='utf-8') as f: | |
| return f.read() | |
| def rename_macros(text): | |
| text = re.sub(r'\bZMIJ_(' + '|'.join(fmt_macros) + r')\b', r'FMT_\1', text) | |
| return text.replace('ZMIJ_', 'FMT_ZMIJ_') | |
| def generate(zmij_dir): | |
| git = ['git', '-C', zmij_dir] | |
| if subprocess.check_output(git + ['status', '--porcelain', 'zmij.h', | |
| 'zmij.cc']): | |
| sys.exit('zmij.h or zmij.cc has uncommitted changes') | |
| commit = subprocess.check_output(git + ['rev-parse', 'HEAD'], | |
| text=True).strip() | |
| h = read(os.path.join(zmij_dir, 'zmij.h')) | |
| cc = read(os.path.join(zmij_dir, 'zmij.cc')) | |
| license = re.match(r'(//.*\n)+', h).group(0) | |
| h = sub(h, license + '\n#ifndef ZMIJ_H_\n#define ZMIJ_H_\n\n', '') | |
| h = sub(h, '\n#endif // ZMIJ_H_\n', '') | |
| # The module includes standard headers in its global module fragment. | |
| h = sub(h, '#include <assert.h> // assert\n', | |
| '#ifndef FMT_MODULE\n#include <assert.h> // assert\n') | |
| h = sub(h, '#include <type_traits> // std::conditional\n', | |
| '#include <type_traits> // std::conditional\n#endif\n') | |
| h = sub(h, '#if ZMIJ_CPLUSPLUS >= 202002L\n', | |
| '#if ZMIJ_CPLUSPLUS >= 202002L && !defined(FMT_MODULE)\n') | |
| # fmt defines the macros in fmt_macros. | |
| h = sub(h, '#ifdef _MSC_VER\n' | |
| '# include <intrin.h> // __lzcnt64/_umul128/__umulh\n' | |
| '# define ZMIJ_MSC_VERSION _MSC_VER\n' | |
| '#else\n' | |
| '# define ZMIJ_MSC_VERSION 0\n' | |
| '#endif\n', | |
| '#if defined(_MSC_VER) && !defined(FMT_MODULE)\n' | |
| '# include <intrin.h> // __lzcnt64/_umul128/__umulh\n' | |
| '#endif\n') | |
| h = cut(h, '#ifdef _MSVC_LANG\n', '#endif\n\n') | |
| h = cut(h, '#if defined(__has_builtin)', '#endif\n') | |
| h = cut(h, '#ifdef __has_cpp_attribute\n', '#endif\n') | |
| h = cut(h, '// Disabling C++14 relaxed constexpr', '#endif\n') | |
| h = cut(h, '#if ZMIJ_USE_CONSTEXPR\n', '#endif\n\n') | |
| h = cut(h, '#if defined(__cpp_lib_is_constant_evaluated) && ' | |
| 'ZMIJ_USE_CONSTEXPR\n', '#endif\n\n') | |
| h = cut(h, '#ifdef ZMIJ_USE_INT128\n', '#endif\n\n') | |
| h = cut(h, '#ifdef ZMIJ_USE_FLOAT128\n', '#endif\n\n') | |
| h = cut(h, '#if ZMIJ_HAS_ATTRIBUTE(always_inline)', '#endif\n\n') | |
| h = cut(h, '#ifdef ZMIJ_OPTIMIZE_SIZE\n', '#endif\n\n') | |
| h = cut(h, '#ifdef ZMIJ_USE_IS_CONSTANT_EVALUATED\n', '#endif\n\n') | |
| # fmt's is_constant_evaluated does the same, with a workaround for clang 14. | |
| h = sub(h, 'constexpr auto is_constant_evaluated() noexcept -> bool {\n' | |
| '#ifdef __cpp_lib_is_constant_evaluated\n' | |
| ' return std::is_constant_evaluated();\n' | |
| '#elif ZMIJ_USE_IS_CONSTANT_EVALUATED\n' | |
| ' return __builtin_is_constant_evaluated();\n' | |
| '#else\n' | |
| ' return false;\n' | |
| '#endif\n' | |
| '}\n', 'using fmt::detail::is_constant_evaluated;\n') | |
| # fmt's clz has the same implementation. | |
| h = sub(h, 'inline ZMIJ_CONSTEXPR20 auto clz(uint64_t x) noexcept -> int {\n' | |
| ' assert(x != 0);\n' | |
| ' if (!is_constant_evaluated()) {\n' | |
| '#if ZMIJ_HAS_BUILTIN(__builtin_clzll) || ZMIJ_GNUC_BUILTINS\n' | |
| ' return __builtin_clzll(x);\n' | |
| '#elif defined(_M_AMD64) && defined(__AVX2__)\n' | |
| ' // Use lzcnt only on AVX2-capable CPUs that have this BMI ' | |
| 'instruction.\n' | |
| ' return __lzcnt64(x);\n' | |
| '#elif defined(_M_AMD64) || defined(_M_ARM64)\n' | |
| ' unsigned long idx;\n' | |
| ' _BitScanReverse64(&idx, x);\n' | |
| ' return 63 - idx;\n' | |
| '#elif ZMIJ_MSC_VERSION\n' | |
| ' unsigned long idx;\n' | |
| ' if (_BitScanReverse(&idx, uint32_t(x >> 32))) return 31 - idx;\n' | |
| ' _BitScanReverse(&idx, uint32_t(x));\n' | |
| ' return 63 - idx;\n' | |
| '#endif\n' | |
| ' }\n' | |
| ' int n = 64;\n' | |
| ' for (; x > 0; x >>= 1) --n;\n' | |
| ' return n;\n' | |
| '}\n', 'using fmt::detail::clz;\n') | |
| # Integer formatting. | |
| h = cut(h, '// Minimum buffer capacities for integer write functions.', | |
| '};\n\n') | |
| h = cut(h, '// Writes the decimal representation of unsigned value', | |
| 'auto write_signed(char* out, Int value) noexcept -> char*;\n\n') | |
| h = cut(h, '/// Writes the decimal representation of `value` to `out`', | |
| '#endif // ZMIJ_USE_INT128\n\n') | |
| # The explicit instantiation declarations refer to explicit instantiations | |
| # that a header can't have, and ZMIJ_NOINLINE is only used by them. | |
| h = cut(h, '// Not inlined, so that callers use the instantiations in ' | |
| 'zmij.cc. On the\n', '#endif\n\n') | |
| h = cut(h, '// Not inlined, so that callers use the instantiations in ' | |
| 'zmij.cc.\n', '#endif\n\n') | |
| h = cut(h, '#if ZMIJ_HAS_ATTRIBUTE(noinline)\n', '#endif\n\n') | |
| # Only ZMIJ_INLINE and ZMIJ_NOINLINE use ZMIJ_HAS_ATTRIBUTE. | |
| h = cut(h, '#ifdef __has_attribute\n', '#endif\n') | |
| for name in ['NOINLINE', 'HAS_ATTRIBUTE', 'extern template', | |
| 'write_unsigned', 'write_signed']: | |
| if name in h: | |
| sys.exit(f'{name} is still in zmij.h') | |
| cc = sub(cc, license + '\n#include "zmij.h"\n\n', '') | |
| # zmij.h includes the same headers. | |
| cc = cut(cc, '#include <assert.h> // assert\n', | |
| '#include <type_traits> // std::conditional\n\n') | |
| simd_includes = ('#if ZMIJ_USE_NEON\n# include <arm_neon.h>\n#endif\n' | |
| '#if ZMIJ_USE_SSE4_1\n# include <smmintrin.h>\n' | |
| '#elif ZMIJ_USE_SSE\n# include <emmintrin.h>\n#endif\n') | |
| cc = sub(cc, simd_includes, | |
| '#ifndef FMT_MODULE\n' + simd_includes + '#endif\n') | |
| # fmt defines the macros in fmt_macros. | |
| cc = cut(cc, '#ifdef __clang__\n', '#endif\n\n') | |
| for name in fmt_macros: | |
| if re.search(r'define ZMIJ_' + name + r'\b', h + cc): | |
| sys.exit(f'ZMIJ_{name} is still defined') | |
| # A header can't have explicit instantiation definitions. | |
| cc = cut(cc, 'template auto to_decimal(float value) noexcept ' | |
| '-> dec_fp<>;\n', '#endif\n\n') | |
| if 'template auto' in cc: | |
| sys.exit('explicit instantiations are still in zmij.cc') | |
| # The anonymous namespace becomes zmij, which encloses zmij::detail, so | |
| # unqualified names in zmij::detail still find its contents, and a leading | |
| # :: that referred to it becomes zmij::. | |
| cc = sub(cc, '\nnamespace {\n', '\nnamespace zmij {\n') | |
| cc = sub(cc, '\n} // namespace\n', '\n} // namespace zmij\n') | |
| cc = re.sub(r'(?<![\w:>])::(?=[A-Za-z_])', 'zmij::', cc) | |
| # Non-template functions defined in a header must be inline. | |
| lines = cc.split('\n') | |
| for i, line in enumerate(lines): | |
| if not lines[i - 1].startswith('template'): | |
| lines[i] = re.sub(r'^(\[\[\w+\]\] )?((ZMIJ_CONSTEXPR(20)? )?' | |
| r'(auto|void) )', r'\1inline \2', line) | |
| cc = '\n'.join(lines) | |
| # Variables that inline functions odr-use must not have internal linkage. | |
| cc = sub(cc, '\nconstexpr uint64_t pow10s[] = {\n', | |
| '\nFMT_INLINE_VARIABLE constexpr uint64_t pow10s[] = {\n') | |
| cc = sub(cc, '\nconstexpr uint64_t zeros = ', | |
| '\nFMT_INLINE_VARIABLE constexpr uint64_t zeros = ') | |
| cc = sub(cc, '\nalignas(64) constexpr data static_data = {};\n', | |
| '\nalignas(64) FMT_INLINE_VARIABLE constexpr data static_data ' | |
| '= {};\n') | |
| i = h.index('namespace zmij {\n') | |
| j = cc.index('namespace zmij {\n') | |
| h = h[:i] + 'FMT_BEGIN_NAMESPACE\n' + h[i:] + 'FMT_END_NAMESPACE\n' | |
| cc = (f'{marker} from zmij.cc at\n// {commit}.\n//\n' + license + '\n' + | |
| cc[:j] + 'FMT_BEGIN_NAMESPACE\n' + cc[j:] + 'FMT_END_NAMESPACE\n') | |
| return rename_macros(h), rename_macros(cc) | |
| def main(): | |
| if len(sys.argv) != 2: | |
| sys.exit(__doc__) | |
| updates = [] | |
| for filename, begin_marker, block in zip(['format.h', 'format-inl.h'], | |
| [h_marker, marker], | |
| generate(sys.argv[1])): | |
| path = os.path.join(include_dir, filename) | |
| block = subprocess.run(['clang-format', '--style=file', | |
| '--assume-filename=' + path], input=block, | |
| stdout=subprocess.PIPE, text=True, | |
| check=True).stdout | |
| if not block.startswith(begin_marker): | |
| sys.exit(f'the {filename} block must start with {begin_marker!r}') | |
| text = read(path) | |
| begin = text.find(begin_marker) | |
| if begin < 0 or text.find(begin_marker, begin + 1) >= 0: | |
| sys.exit(f'{path} must have one block starting with ' | |
| f'{begin_marker!r}') | |
| end = text.index(end_marker, begin) + len(end_marker) | |
| updates.append((path, text[:begin] + block + text[end:])) | |
| for path, text in updates: | |
| with open(path, 'w', encoding='utf-8', newline='\n') as f: | |
| f.write(text) | |
| if __name__ == '__main__': | |
| main() |