cxx.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. """
  2. C++ code printer
  3. """
  4. from itertools import chain
  5. from sympy.codegen.ast import Type, none
  6. from .c import C89CodePrinter, C99CodePrinter
  7. # These are defined in the other file so we can avoid importing sympy.codegen
  8. # from the top-level 'import sympy'. Export them here as well.
  9. from sympy.printing.codeprinter import cxxcode # noqa:F401
  10. # from http://en.cppreference.com/w/cpp/keyword
  11. reserved = {
  12. 'C++98': [
  13. 'and', 'and_eq', 'asm', 'auto', 'bitand', 'bitor', 'bool', 'break',
  14. 'case', 'catch,', 'char', 'class', 'compl', 'const', 'const_cast',
  15. 'continue', 'default', 'delete', 'do', 'double', 'dynamic_cast',
  16. 'else', 'enum', 'explicit', 'export', 'extern', 'false', 'float',
  17. 'for', 'friend', 'goto', 'if', 'inline', 'int', 'long', 'mutable',
  18. 'namespace', 'new', 'not', 'not_eq', 'operator', 'or', 'or_eq',
  19. 'private', 'protected', 'public', 'register', 'reinterpret_cast',
  20. 'return', 'short', 'signed', 'sizeof', 'static', 'static_cast',
  21. 'struct', 'switch', 'template', 'this', 'throw', 'true', 'try',
  22. 'typedef', 'typeid', 'typename', 'union', 'unsigned', 'using',
  23. 'virtual', 'void', 'volatile', 'wchar_t', 'while', 'xor', 'xor_eq'
  24. ]
  25. }
  26. reserved['C++11'] = reserved['C++98'][:] + [
  27. 'alignas', 'alignof', 'char16_t', 'char32_t', 'constexpr', 'decltype',
  28. 'noexcept', 'nullptr', 'static_assert', 'thread_local'
  29. ]
  30. reserved['C++17'] = reserved['C++11'][:]
  31. reserved['C++17'].remove('register')
  32. # TM TS: atomic_cancel, atomic_commit, atomic_noexcept, synchronized
  33. # concepts TS: concept, requires
  34. # module TS: import, module
  35. _math_functions = {
  36. 'C++98': {
  37. 'Mod': 'fmod',
  38. 'ceiling': 'ceil',
  39. },
  40. 'C++11': {
  41. 'gamma': 'tgamma',
  42. },
  43. 'C++17': {
  44. 'beta': 'beta',
  45. 'Ei': 'expint',
  46. 'zeta': 'riemann_zeta',
  47. }
  48. }
  49. # from http://en.cppreference.com/w/cpp/header/cmath
  50. for k in ('Abs', 'exp', 'log', 'log10', 'sqrt', 'sin', 'cos', 'tan', # 'Pow'
  51. 'asin', 'acos', 'atan', 'atan2', 'sinh', 'cosh', 'tanh', 'floor'):
  52. _math_functions['C++98'][k] = k.lower()
  53. for k in ('asinh', 'acosh', 'atanh', 'erf', 'erfc'):
  54. _math_functions['C++11'][k] = k.lower()
  55. def _attach_print_method(cls, sympy_name, func_name):
  56. meth_name = '_print_%s' % sympy_name
  57. if hasattr(cls, meth_name):
  58. raise ValueError("Edit method (or subclass) instead of overwriting.")
  59. def _print_method(self, expr):
  60. return '{}{}({})'.format(self._ns, func_name, ', '.join(map(self._print, expr.args)))
  61. _print_method.__doc__ = "Prints code for %s" % k
  62. setattr(cls, meth_name, _print_method)
  63. def _attach_print_methods(cls, cont):
  64. for sympy_name, cxx_name in cont[cls.standard].items():
  65. _attach_print_method(cls, sympy_name, cxx_name)
  66. class _CXXCodePrinterBase:
  67. printmethod = "_cxxcode"
  68. language = 'C++'
  69. _ns = 'std::' # namespace
  70. def __init__(self, settings=None):
  71. super().__init__(settings or {})
  72. def _print_Max(self, expr):
  73. from sympy.functions.elementary.miscellaneous import Max
  74. if len(expr.args) == 1:
  75. return self._print(expr.args[0])
  76. return "%smax(%s, %s)" % (self._ns, self._print(expr.args[0]),
  77. self._print(Max(*expr.args[1:])))
  78. def _print_Min(self, expr):
  79. from sympy.functions.elementary.miscellaneous import Min
  80. if len(expr.args) == 1:
  81. return self._print(expr.args[0])
  82. return "%smin(%s, %s)" % (self._ns, self._print(expr.args[0]),
  83. self._print(Min(*expr.args[1:])))
  84. def _print_using(self, expr):
  85. if expr.alias == none:
  86. return 'using %s' % expr.type
  87. else:
  88. raise ValueError("C++98 does not support type aliases")
  89. class CXX98CodePrinter(_CXXCodePrinterBase, C89CodePrinter):
  90. standard = 'C++98'
  91. reserved_words = set(reserved['C++98'])
  92. # _attach_print_methods(CXX98CodePrinter, _math_functions)
  93. class CXX11CodePrinter(_CXXCodePrinterBase, C99CodePrinter):
  94. standard = 'C++11'
  95. reserved_words = set(reserved['C++11'])
  96. type_mappings = dict(chain(
  97. CXX98CodePrinter.type_mappings.items(),
  98. {
  99. Type('int8'): ('int8_t', {'cstdint'}),
  100. Type('int16'): ('int16_t', {'cstdint'}),
  101. Type('int32'): ('int32_t', {'cstdint'}),
  102. Type('int64'): ('int64_t', {'cstdint'}),
  103. Type('uint8'): ('uint8_t', {'cstdint'}),
  104. Type('uint16'): ('uint16_t', {'cstdint'}),
  105. Type('uint32'): ('uint32_t', {'cstdint'}),
  106. Type('uint64'): ('uint64_t', {'cstdint'}),
  107. Type('complex64'): ('std::complex<float>', {'complex'}),
  108. Type('complex128'): ('std::complex<double>', {'complex'}),
  109. Type('bool'): ('bool', None),
  110. }.items()
  111. ))
  112. def _print_using(self, expr):
  113. if expr.alias == none:
  114. return super()._print_using(expr)
  115. else:
  116. return 'using %(alias)s = %(type)s' % expr.kwargs(apply=self._print)
  117. # _attach_print_methods(CXX11CodePrinter, _math_functions)
  118. class CXX17CodePrinter(_CXXCodePrinterBase, C99CodePrinter):
  119. standard = 'C++17'
  120. reserved_words = set(reserved['C++17'])
  121. _kf = dict(C99CodePrinter._kf, **_math_functions['C++17'])
  122. def _print_beta(self, expr):
  123. return self._print_math_func(expr)
  124. def _print_Ei(self, expr):
  125. return self._print_math_func(expr)
  126. def _print_zeta(self, expr):
  127. return self._print_math_func(expr)
  128. # _attach_print_methods(CXX17CodePrinter, _math_functions)
  129. cxx_code_printers = {
  130. 'c++98': CXX98CodePrinter,
  131. 'c++11': CXX11CodePrinter,
  132. 'c++17': CXX17CodePrinter
  133. }