c.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747
  1. """
  2. C code printer
  3. The C89CodePrinter & C99CodePrinter converts single SymPy expressions into
  4. single C expressions, using the functions defined in math.h where possible.
  5. A complete code generator, which uses ccode extensively, can be found in
  6. sympy.utilities.codegen. The codegen module can be used to generate complete
  7. source code files that are compilable without further modifications.
  8. """
  9. from __future__ import annotations
  10. from typing import Any
  11. from functools import wraps
  12. from itertools import chain
  13. from sympy.core import S
  14. from sympy.core.numbers import equal_valued
  15. from sympy.codegen.ast import (
  16. Assignment, Pointer, Variable, Declaration, Type,
  17. real, complex_, integer, bool_, float32, float64, float80,
  18. complex64, complex128, intc, value_const, pointer_const,
  19. int8, int16, int32, int64, uint8, uint16, uint32, uint64, untyped,
  20. none
  21. )
  22. from sympy.printing.codeprinter import CodePrinter, requires
  23. from sympy.printing.precedence import precedence, PRECEDENCE
  24. from sympy.sets.fancysets import Range
  25. # These are defined in the other file so we can avoid importing sympy.codegen
  26. # from the top-level 'import sympy'. Export them here as well.
  27. from sympy.printing.codeprinter import ccode, print_ccode # noqa:F401
  28. # dictionary mapping SymPy function to (argument_conditions, C_function).
  29. # Used in C89CodePrinter._print_Function(self)
  30. known_functions_C89 = {
  31. "Abs": [(lambda x: not x.is_integer, "fabs"), (lambda x: x.is_integer, "abs")],
  32. "sin": "sin",
  33. "cos": "cos",
  34. "tan": "tan",
  35. "asin": "asin",
  36. "acos": "acos",
  37. "atan": "atan",
  38. "atan2": "atan2",
  39. "exp": "exp",
  40. "log": "log",
  41. "sinh": "sinh",
  42. "cosh": "cosh",
  43. "tanh": "tanh",
  44. "floor": "floor",
  45. "ceiling": "ceil",
  46. "sqrt": "sqrt", # To enable automatic rewrites
  47. }
  48. known_functions_C99 = dict(known_functions_C89, **{
  49. 'exp2': 'exp2',
  50. 'expm1': 'expm1',
  51. 'log10': 'log10',
  52. 'log2': 'log2',
  53. 'log1p': 'log1p',
  54. 'Cbrt': 'cbrt',
  55. 'hypot': 'hypot',
  56. 'fma': 'fma',
  57. 'loggamma': 'lgamma',
  58. 'erfc': 'erfc',
  59. 'Max': 'fmax',
  60. 'Min': 'fmin',
  61. "asinh": "asinh",
  62. "acosh": "acosh",
  63. "atanh": "atanh",
  64. "erf": "erf",
  65. "gamma": "tgamma",
  66. })
  67. # These are the core reserved words in the C language. Taken from:
  68. # https://en.cppreference.com/w/c/keyword
  69. reserved_words = [
  70. 'auto', 'break', 'case', 'char', 'const', 'continue', 'default', 'do',
  71. 'double', 'else', 'enum', 'extern', 'float', 'for', 'goto', 'if', 'int',
  72. 'long', 'register', 'return', 'short', 'signed', 'sizeof', 'static',
  73. 'struct', 'entry', # never standardized, we'll leave it here anyway
  74. 'switch', 'typedef', 'union', 'unsigned', 'void', 'volatile', 'while'
  75. ]
  76. reserved_words_c99 = ['inline', 'restrict']
  77. def get_math_macros():
  78. """ Returns a dictionary with math-related macros from math.h/cmath
  79. Note that these macros are not strictly required by the C/C++-standard.
  80. For MSVC they are enabled by defining "_USE_MATH_DEFINES" (preferably
  81. via a compilation flag).
  82. Returns
  83. =======
  84. Dictionary mapping SymPy expressions to strings (macro names)
  85. """
  86. from sympy.codegen.cfunctions import log2, Sqrt
  87. from sympy.functions.elementary.exponential import log
  88. from sympy.functions.elementary.miscellaneous import sqrt
  89. return {
  90. S.Exp1: 'M_E',
  91. log2(S.Exp1): 'M_LOG2E',
  92. 1/log(2): 'M_LOG2E',
  93. log(2): 'M_LN2',
  94. log(10): 'M_LN10',
  95. S.Pi: 'M_PI',
  96. S.Pi/2: 'M_PI_2',
  97. S.Pi/4: 'M_PI_4',
  98. 1/S.Pi: 'M_1_PI',
  99. 2/S.Pi: 'M_2_PI',
  100. 2/sqrt(S.Pi): 'M_2_SQRTPI',
  101. 2/Sqrt(S.Pi): 'M_2_SQRTPI',
  102. sqrt(2): 'M_SQRT2',
  103. Sqrt(2): 'M_SQRT2',
  104. 1/sqrt(2): 'M_SQRT1_2',
  105. 1/Sqrt(2): 'M_SQRT1_2'
  106. }
  107. def _as_macro_if_defined(meth):
  108. """ Decorator for printer methods
  109. When a Printer's method is decorated using this decorator the expressions printed
  110. will first be looked for in the attribute ``math_macros``, and if present it will
  111. print the macro name in ``math_macros`` followed by a type suffix for the type
  112. ``real``. e.g. printing ``sympy.pi`` would print ``M_PIl`` if real is mapped to float80.
  113. """
  114. @wraps(meth)
  115. def _meth_wrapper(self, expr, **kwargs):
  116. if expr in self.math_macros:
  117. return '%s%s' % (self.math_macros[expr], self._get_math_macro_suffix(real))
  118. else:
  119. return meth(self, expr, **kwargs)
  120. return _meth_wrapper
  121. class C89CodePrinter(CodePrinter):
  122. """A printer to convert Python expressions to strings of C code"""
  123. printmethod = "_ccode"
  124. language = "C"
  125. standard = "C89"
  126. reserved_words = set(reserved_words)
  127. _default_settings: dict[str, Any] = {
  128. 'order': None,
  129. 'full_prec': 'auto',
  130. 'precision': 17,
  131. 'user_functions': {},
  132. 'human': True,
  133. 'allow_unknown_functions': False,
  134. 'contract': True,
  135. 'dereference': set(),
  136. 'error_on_reserved': False,
  137. 'reserved_word_suffix': '_',
  138. }
  139. type_aliases = {
  140. real: float64,
  141. complex_: complex128,
  142. integer: intc
  143. }
  144. type_mappings: dict[Type, Any] = {
  145. real: 'double',
  146. intc: 'int',
  147. float32: 'float',
  148. float64: 'double',
  149. integer: 'int',
  150. bool_: 'bool',
  151. int8: 'int8_t',
  152. int16: 'int16_t',
  153. int32: 'int32_t',
  154. int64: 'int64_t',
  155. uint8: 'int8_t',
  156. uint16: 'int16_t',
  157. uint32: 'int32_t',
  158. uint64: 'int64_t',
  159. }
  160. type_headers = {
  161. bool_: {'stdbool.h'},
  162. int8: {'stdint.h'},
  163. int16: {'stdint.h'},
  164. int32: {'stdint.h'},
  165. int64: {'stdint.h'},
  166. uint8: {'stdint.h'},
  167. uint16: {'stdint.h'},
  168. uint32: {'stdint.h'},
  169. uint64: {'stdint.h'},
  170. }
  171. # Macros needed to be defined when using a Type
  172. type_macros: dict[Type, tuple[str, ...]] = {}
  173. type_func_suffixes = {
  174. float32: 'f',
  175. float64: '',
  176. float80: 'l'
  177. }
  178. type_literal_suffixes = {
  179. float32: 'F',
  180. float64: '',
  181. float80: 'L'
  182. }
  183. type_math_macro_suffixes = {
  184. float80: 'l'
  185. }
  186. math_macros = None
  187. _ns = '' # namespace, C++ uses 'std::'
  188. # known_functions-dict to copy
  189. _kf: dict[str, Any] = known_functions_C89
  190. def __init__(self, settings=None):
  191. settings = settings or {}
  192. if self.math_macros is None:
  193. self.math_macros = settings.pop('math_macros', get_math_macros())
  194. self.type_aliases = dict(chain(self.type_aliases.items(),
  195. settings.pop('type_aliases', {}).items()))
  196. self.type_mappings = dict(chain(self.type_mappings.items(),
  197. settings.pop('type_mappings', {}).items()))
  198. self.type_headers = dict(chain(self.type_headers.items(),
  199. settings.pop('type_headers', {}).items()))
  200. self.type_macros = dict(chain(self.type_macros.items(),
  201. settings.pop('type_macros', {}).items()))
  202. self.type_func_suffixes = dict(chain(self.type_func_suffixes.items(),
  203. settings.pop('type_func_suffixes', {}).items()))
  204. self.type_literal_suffixes = dict(chain(self.type_literal_suffixes.items(),
  205. settings.pop('type_literal_suffixes', {}).items()))
  206. self.type_math_macro_suffixes = dict(chain(self.type_math_macro_suffixes.items(),
  207. settings.pop('type_math_macro_suffixes', {}).items()))
  208. super().__init__(settings)
  209. self.known_functions = dict(self._kf, **settings.get('user_functions', {}))
  210. self._dereference = set(settings.get('dereference', []))
  211. self.headers = set()
  212. self.libraries = set()
  213. self.macros = set()
  214. def _rate_index_position(self, p):
  215. return p*5
  216. def _get_statement(self, codestring):
  217. """ Get code string as a statement - i.e. ending with a semicolon. """
  218. return codestring if codestring.endswith(';') else codestring + ';'
  219. def _get_comment(self, text):
  220. return "/* {} */".format(text)
  221. def _declare_number_const(self, name, value):
  222. type_ = self.type_aliases[real]
  223. var = Variable(name, type=type_, value=value.evalf(type_.decimal_dig), attrs={value_const})
  224. decl = Declaration(var)
  225. return self._get_statement(self._print(decl))
  226. def _format_code(self, lines):
  227. return self.indent_code(lines)
  228. def _traverse_matrix_indices(self, mat):
  229. rows, cols = mat.shape
  230. return ((i, j) for i in range(rows) for j in range(cols))
  231. @_as_macro_if_defined
  232. def _print_Mul(self, expr, **kwargs):
  233. return super()._print_Mul(expr, **kwargs)
  234. @_as_macro_if_defined
  235. def _print_Pow(self, expr):
  236. if "Pow" in self.known_functions:
  237. return self._print_Function(expr)
  238. PREC = precedence(expr)
  239. suffix = self._get_func_suffix(real)
  240. if equal_valued(expr.exp, -1):
  241. literal_suffix = self._get_literal_suffix(real)
  242. return '1.0%s/%s' % (literal_suffix, self.parenthesize(expr.base, PREC))
  243. elif equal_valued(expr.exp, 0.5):
  244. return '%ssqrt%s(%s)' % (self._ns, suffix, self._print(expr.base))
  245. elif expr.exp == S.One/3 and self.standard != 'C89':
  246. return '%scbrt%s(%s)' % (self._ns, suffix, self._print(expr.base))
  247. else:
  248. return '%spow%s(%s, %s)' % (self._ns, suffix, self._print(expr.base),
  249. self._print(expr.exp))
  250. def _print_Mod(self, expr):
  251. num, den = expr.args
  252. if num.is_integer and den.is_integer:
  253. PREC = precedence(expr)
  254. snum, sden = [self.parenthesize(arg, PREC) for arg in expr.args]
  255. # % is remainder (same sign as numerator), not modulo (same sign as
  256. # denominator), in C. Hence, % only works as modulo if both numbers
  257. # have the same sign
  258. if (num.is_nonnegative and den.is_nonnegative or
  259. num.is_nonpositive and den.is_nonpositive):
  260. return f"{snum} % {sden}"
  261. return f"(({snum} % {sden}) + {sden}) % {sden}"
  262. # Not guaranteed integer
  263. return self._print_math_func(expr, known='fmod')
  264. def _print_Rational(self, expr):
  265. p, q = int(expr.p), int(expr.q)
  266. suffix = self._get_literal_suffix(real)
  267. return '%d.0%s/%d.0%s' % (p, suffix, q, suffix)
  268. def _print_Indexed(self, expr):
  269. # calculate index for 1d array
  270. offset = getattr(expr.base, 'offset', S.Zero)
  271. strides = getattr(expr.base, 'strides', None)
  272. indices = expr.indices
  273. if strides is None or isinstance(strides, str):
  274. dims = expr.shape
  275. shift = S.One
  276. temp = ()
  277. if strides == 'C' or strides is None:
  278. traversal = reversed(range(expr.rank))
  279. indices = indices[::-1]
  280. elif strides == 'F':
  281. traversal = range(expr.rank)
  282. for i in traversal:
  283. temp += (shift,)
  284. shift *= dims[i]
  285. strides = temp
  286. flat_index = sum([x[0]*x[1] for x in zip(indices, strides)]) + offset
  287. return "%s[%s]" % (self._print(expr.base.label),
  288. self._print(flat_index))
  289. def _print_Idx(self, expr):
  290. return self._print(expr.label)
  291. @_as_macro_if_defined
  292. def _print_NumberSymbol(self, expr):
  293. return super()._print_NumberSymbol(expr)
  294. def _print_Infinity(self, expr):
  295. return 'HUGE_VAL'
  296. def _print_NegativeInfinity(self, expr):
  297. return '-HUGE_VAL'
  298. def _print_Piecewise(self, expr):
  299. if expr.args[-1].cond != True:
  300. # We need the last conditional to be a True, otherwise the resulting
  301. # function may not return a result.
  302. raise ValueError("All Piecewise expressions must contain an "
  303. "(expr, True) statement to be used as a default "
  304. "condition. Without one, the generated "
  305. "expression may not evaluate to anything under "
  306. "some condition.")
  307. lines = []
  308. if expr.has(Assignment):
  309. for i, (e, c) in enumerate(expr.args):
  310. if i == 0:
  311. lines.append("if (%s) {" % self._print(c))
  312. elif i == len(expr.args) - 1 and c == True:
  313. lines.append("else {")
  314. else:
  315. lines.append("else if (%s) {" % self._print(c))
  316. code0 = self._print(e)
  317. lines.append(code0)
  318. lines.append("}")
  319. return "\n".join(lines)
  320. else:
  321. # The piecewise was used in an expression, need to do inline
  322. # operators. This has the downside that inline operators will
  323. # not work for statements that span multiple lines (Matrix or
  324. # Indexed expressions).
  325. ecpairs = ["((%s) ? (\n%s\n)\n" % (self._print(c),
  326. self._print(e))
  327. for e, c in expr.args[:-1]]
  328. last_line = ": (\n%s\n)" % self._print(expr.args[-1].expr)
  329. return ": ".join(ecpairs) + last_line + " ".join([")"*len(ecpairs)])
  330. def _print_ITE(self, expr):
  331. from sympy.functions import Piecewise
  332. return self._print(expr.rewrite(Piecewise, deep=False))
  333. def _print_MatrixElement(self, expr):
  334. return "{}[{}]".format(self.parenthesize(expr.parent, PRECEDENCE["Atom"],
  335. strict=True), expr.j + expr.i*expr.parent.shape[1])
  336. def _print_Symbol(self, expr):
  337. name = super()._print_Symbol(expr)
  338. if expr in self._settings['dereference']:
  339. return '(*{})'.format(name)
  340. else:
  341. return name
  342. def _print_Relational(self, expr):
  343. lhs_code = self._print(expr.lhs)
  344. rhs_code = self._print(expr.rhs)
  345. op = expr.rel_op
  346. return "{} {} {}".format(lhs_code, op, rhs_code)
  347. def _print_For(self, expr):
  348. target = self._print(expr.target)
  349. if isinstance(expr.iterable, Range):
  350. start, stop, step = expr.iterable.args
  351. else:
  352. raise NotImplementedError("Only iterable currently supported is Range")
  353. body = self._print(expr.body)
  354. return ('for ({target} = {start}; {target} < {stop}; {target} += '
  355. '{step}) {{\n{body}\n}}').format(target=target, start=start,
  356. stop=stop, step=step, body=body)
  357. def _print_sign(self, func):
  358. return '((({0}) > 0) - (({0}) < 0))'.format(self._print(func.args[0]))
  359. def _print_Max(self, expr):
  360. if "Max" in self.known_functions:
  361. return self._print_Function(expr)
  362. def inner_print_max(args): # The more natural abstraction of creating
  363. if len(args) == 1: # and printing smaller Max objects is slow
  364. return self._print(args[0]) # when there are many arguments.
  365. half = len(args) // 2
  366. return "((%(a)s > %(b)s) ? %(a)s : %(b)s)" % {
  367. 'a': inner_print_max(args[:half]),
  368. 'b': inner_print_max(args[half:])
  369. }
  370. return inner_print_max(expr.args)
  371. def _print_Min(self, expr):
  372. if "Min" in self.known_functions:
  373. return self._print_Function(expr)
  374. def inner_print_min(args): # The more natural abstraction of creating
  375. if len(args) == 1: # and printing smaller Min objects is slow
  376. return self._print(args[0]) # when there are many arguments.
  377. half = len(args) // 2
  378. return "((%(a)s < %(b)s) ? %(a)s : %(b)s)" % {
  379. 'a': inner_print_min(args[:half]),
  380. 'b': inner_print_min(args[half:])
  381. }
  382. return inner_print_min(expr.args)
  383. def indent_code(self, code):
  384. """Accepts a string of code or a list of code lines"""
  385. if isinstance(code, str):
  386. code_lines = self.indent_code(code.splitlines(True))
  387. return ''.join(code_lines)
  388. tab = " "
  389. inc_token = ('{', '(', '{\n', '(\n')
  390. dec_token = ('}', ')')
  391. code = [line.lstrip(' \t') for line in code]
  392. increase = [int(any(map(line.endswith, inc_token))) for line in code]
  393. decrease = [int(any(map(line.startswith, dec_token))) for line in code]
  394. pretty = []
  395. level = 0
  396. for n, line in enumerate(code):
  397. if line in ('', '\n'):
  398. pretty.append(line)
  399. continue
  400. level -= decrease[n]
  401. pretty.append("%s%s" % (tab*level, line))
  402. level += increase[n]
  403. return pretty
  404. def _get_func_suffix(self, type_):
  405. return self.type_func_suffixes[self.type_aliases.get(type_, type_)]
  406. def _get_literal_suffix(self, type_):
  407. return self.type_literal_suffixes[self.type_aliases.get(type_, type_)]
  408. def _get_math_macro_suffix(self, type_):
  409. alias = self.type_aliases.get(type_, type_)
  410. dflt = self.type_math_macro_suffixes.get(alias, '')
  411. return self.type_math_macro_suffixes.get(type_, dflt)
  412. def _print_Tuple(self, expr):
  413. return '{'+', '.join(self._print(e) for e in expr)+'}'
  414. _print_List = _print_Tuple
  415. def _print_Type(self, type_):
  416. self.headers.update(self.type_headers.get(type_, set()))
  417. self.macros.update(self.type_macros.get(type_, set()))
  418. return self._print(self.type_mappings.get(type_, type_.name))
  419. def _print_Declaration(self, decl):
  420. from sympy.codegen.cnodes import restrict
  421. var = decl.variable
  422. val = var.value
  423. if var.type == untyped:
  424. raise ValueError("C does not support untyped variables")
  425. if isinstance(var, Pointer):
  426. result = '{vc}{t} *{pc} {r}{s}'.format(
  427. vc='const ' if value_const in var.attrs else '',
  428. t=self._print(var.type),
  429. pc=' const' if pointer_const in var.attrs else '',
  430. r='restrict ' if restrict in var.attrs else '',
  431. s=self._print(var.symbol)
  432. )
  433. elif isinstance(var, Variable):
  434. result = '{vc}{t} {s}'.format(
  435. vc='const ' if value_const in var.attrs else '',
  436. t=self._print(var.type),
  437. s=self._print(var.symbol)
  438. )
  439. else:
  440. raise NotImplementedError("Unknown type of var: %s" % type(var))
  441. if val != None: # Must be "!= None", cannot be "is not None"
  442. result += ' = %s' % self._print(val)
  443. return result
  444. def _print_Float(self, flt):
  445. type_ = self.type_aliases.get(real, real)
  446. self.macros.update(self.type_macros.get(type_, set()))
  447. suffix = self._get_literal_suffix(type_)
  448. num = str(flt.evalf(type_.decimal_dig))
  449. if 'e' not in num and '.' not in num:
  450. num += '.0'
  451. num_parts = num.split('e')
  452. num_parts[0] = num_parts[0].rstrip('0')
  453. if num_parts[0].endswith('.'):
  454. num_parts[0] += '0'
  455. return 'e'.join(num_parts) + suffix
  456. @requires(headers={'stdbool.h'})
  457. def _print_BooleanTrue(self, expr):
  458. return 'true'
  459. @requires(headers={'stdbool.h'})
  460. def _print_BooleanFalse(self, expr):
  461. return 'false'
  462. def _print_Element(self, elem):
  463. if elem.strides == None: # Must be "== None", cannot be "is None"
  464. if elem.offset != None: # Must be "!= None", cannot be "is not None"
  465. raise ValueError("Expected strides when offset is given")
  466. idxs = ']['.join((self._print(arg) for arg in elem.indices))
  467. else:
  468. global_idx = sum([i*s for i, s in zip(elem.indices, elem.strides)])
  469. if elem.offset != None: # Must be "!= None", cannot be "is not None"
  470. global_idx += elem.offset
  471. idxs = self._print(global_idx)
  472. return "{symb}[{idxs}]".format(
  473. symb=self._print(elem.symbol),
  474. idxs=idxs
  475. )
  476. def _print_CodeBlock(self, expr):
  477. """ Elements of code blocks printed as statements. """
  478. return '\n'.join([self._get_statement(self._print(i)) for i in expr.args])
  479. def _print_While(self, expr):
  480. return 'while ({condition}) {{\n{body}\n}}'.format(**expr.kwargs(
  481. apply=lambda arg: self._print(arg)))
  482. def _print_Scope(self, expr):
  483. return '{\n%s\n}' % self._print_CodeBlock(expr.body)
  484. @requires(headers={'stdio.h'})
  485. def _print_Print(self, expr):
  486. return 'printf({fmt}, {pargs})'.format(
  487. fmt=self._print(expr.format_string),
  488. pargs=', '.join((self._print(arg) for arg in expr.print_args))
  489. )
  490. def _print_FunctionPrototype(self, expr):
  491. pars = ', '.join((self._print(Declaration(arg)) for arg in expr.parameters))
  492. return "%s %s(%s)" % (
  493. tuple((self._print(arg) for arg in (expr.return_type, expr.name))) + (pars,)
  494. )
  495. def _print_FunctionDefinition(self, expr):
  496. return "%s%s" % (self._print_FunctionPrototype(expr),
  497. self._print_Scope(expr))
  498. def _print_Return(self, expr):
  499. arg, = expr.args
  500. return 'return %s' % self._print(arg)
  501. def _print_CommaOperator(self, expr):
  502. return '(%s)' % ', '.join((self._print(arg) for arg in expr.args))
  503. def _print_Label(self, expr):
  504. if expr.body == none:
  505. return '%s:' % str(expr.name)
  506. if len(expr.body.args) == 1:
  507. return '%s:\n%s' % (str(expr.name), self._print_CodeBlock(expr.body))
  508. return '%s:\n{\n%s\n}' % (str(expr.name), self._print_CodeBlock(expr.body))
  509. def _print_goto(self, expr):
  510. return 'goto %s' % expr.label.name
  511. def _print_PreIncrement(self, expr):
  512. arg, = expr.args
  513. return '++(%s)' % self._print(arg)
  514. def _print_PostIncrement(self, expr):
  515. arg, = expr.args
  516. return '(%s)++' % self._print(arg)
  517. def _print_PreDecrement(self, expr):
  518. arg, = expr.args
  519. return '--(%s)' % self._print(arg)
  520. def _print_PostDecrement(self, expr):
  521. arg, = expr.args
  522. return '(%s)--' % self._print(arg)
  523. def _print_struct(self, expr):
  524. return "%(keyword)s %(name)s {\n%(lines)s}" % {
  525. "keyword": expr.__class__.__name__, "name": expr.name, "lines": ';\n'.join(
  526. [self._print(decl) for decl in expr.declarations] + [''])
  527. }
  528. def _print_BreakToken(self, _):
  529. return 'break'
  530. def _print_ContinueToken(self, _):
  531. return 'continue'
  532. _print_union = _print_struct
  533. class C99CodePrinter(C89CodePrinter):
  534. standard = 'C99'
  535. reserved_words = set(reserved_words + reserved_words_c99)
  536. type_mappings=dict(chain(C89CodePrinter.type_mappings.items(), {
  537. complex64: 'float complex',
  538. complex128: 'double complex',
  539. }.items()))
  540. type_headers = dict(chain(C89CodePrinter.type_headers.items(), {
  541. complex64: {'complex.h'},
  542. complex128: {'complex.h'}
  543. }.items()))
  544. # known_functions-dict to copy
  545. _kf: dict[str, Any] = known_functions_C99
  546. # functions with versions with 'f' and 'l' suffixes:
  547. _prec_funcs = ('fabs fmod remainder remquo fma fmax fmin fdim nan exp exp2'
  548. ' expm1 log log10 log2 log1p pow sqrt cbrt hypot sin cos tan'
  549. ' asin acos atan atan2 sinh cosh tanh asinh acosh atanh erf'
  550. ' erfc tgamma lgamma ceil floor trunc round nearbyint rint'
  551. ' frexp ldexp modf scalbn ilogb logb nextafter copysign').split()
  552. def _print_Infinity(self, expr):
  553. return 'INFINITY'
  554. def _print_NegativeInfinity(self, expr):
  555. return '-INFINITY'
  556. def _print_NaN(self, expr):
  557. return 'NAN'
  558. # tgamma was already covered by 'known_functions' dict
  559. @requires(headers={'math.h'}, libraries={'m'})
  560. @_as_macro_if_defined
  561. def _print_math_func(self, expr, nest=False, known=None):
  562. if known is None:
  563. known = self.known_functions[expr.__class__.__name__]
  564. if not isinstance(known, str):
  565. for cb, name in known:
  566. if cb(*expr.args):
  567. known = name
  568. break
  569. else:
  570. raise ValueError("No matching printer")
  571. try:
  572. return known(self, *expr.args)
  573. except TypeError:
  574. suffix = self._get_func_suffix(real) if self._ns + known in self._prec_funcs else ''
  575. if nest:
  576. args = self._print(expr.args[0])
  577. if len(expr.args) > 1:
  578. paren_pile = ''
  579. for curr_arg in expr.args[1:-1]:
  580. paren_pile += ')'
  581. args += ', {ns}{name}{suffix}({next}'.format(
  582. ns=self._ns,
  583. name=known,
  584. suffix=suffix,
  585. next = self._print(curr_arg)
  586. )
  587. args += ', %s%s' % (
  588. self._print(expr.func(expr.args[-1])),
  589. paren_pile
  590. )
  591. else:
  592. args = ', '.join((self._print(arg) for arg in expr.args))
  593. return '{ns}{name}{suffix}({args})'.format(
  594. ns=self._ns,
  595. name=known,
  596. suffix=suffix,
  597. args=args
  598. )
  599. def _print_Max(self, expr):
  600. return self._print_math_func(expr, nest=True)
  601. def _print_Min(self, expr):
  602. return self._print_math_func(expr, nest=True)
  603. def _get_loop_opening_ending(self, indices):
  604. open_lines = []
  605. close_lines = []
  606. loopstart = "for (int %(var)s=%(start)s; %(var)s<%(end)s; %(var)s++){" # C99
  607. for i in indices:
  608. # C arrays start at 0 and end at dimension-1
  609. open_lines.append(loopstart % {
  610. 'var': self._print(i.label),
  611. 'start': self._print(i.lower),
  612. 'end': self._print(i.upper + 1)})
  613. close_lines.append("}")
  614. return open_lines, close_lines
  615. for k in ('Abs Sqrt exp exp2 expm1 log log10 log2 log1p Cbrt hypot fma'
  616. ' loggamma sin cos tan asin acos atan atan2 sinh cosh tanh asinh acosh '
  617. 'atanh erf erfc loggamma gamma ceiling floor').split():
  618. setattr(C99CodePrinter, '_print_%s' % k, C99CodePrinter._print_math_func)
  619. class C11CodePrinter(C99CodePrinter):
  620. @requires(headers={'stdalign.h'})
  621. def _print_alignof(self, expr):
  622. arg, = expr.args
  623. return 'alignof(%s)' % self._print(arg)
  624. c_code_printers = {
  625. 'c89': C89CodePrinter,
  626. 'c99': C99CodePrinter,
  627. 'c11': C11CodePrinter
  628. }