c.py 26 KB

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