fortran.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782
  1. """
  2. Fortran code printer
  3. The FCodePrinter converts single SymPy expressions into single Fortran
  4. expressions, using the functions defined in the Fortran 77 standard where
  5. possible. Some useful pointers to Fortran can be found on wikipedia:
  6. https://en.wikipedia.org/wiki/Fortran
  7. Most of the code below is based on the "Professional Programmer\'s Guide to
  8. Fortran77" by Clive G. Page:
  9. https://www.star.le.ac.uk/~cgp/prof77.html
  10. Fortran is a case-insensitive language. This might cause trouble because
  11. SymPy is case sensitive. So, fcode adds underscores to variable names when
  12. it is necessary to make them different for Fortran.
  13. """
  14. from __future__ import annotations
  15. from typing import Any
  16. from collections import defaultdict
  17. from itertools import chain
  18. import string
  19. from sympy.codegen.ast import (
  20. Assignment, Declaration, Pointer, value_const,
  21. float32, float64, float80, complex64, complex128, int8, int16, int32,
  22. int64, intc, real, integer, bool_, complex_
  23. )
  24. from sympy.codegen.fnodes import (
  25. allocatable, isign, dsign, cmplx, merge, literal_dp, elemental, pure,
  26. intent_in, intent_out, intent_inout
  27. )
  28. from sympy.core import S, Add, N, Float, Symbol
  29. from sympy.core.function import Function
  30. from sympy.core.numbers import equal_valued
  31. from sympy.core.relational import Eq
  32. from sympy.sets import Range
  33. from sympy.printing.codeprinter import CodePrinter
  34. from sympy.printing.precedence import precedence, PRECEDENCE
  35. from sympy.printing.printer import printer_context
  36. # These are defined in the other file so we can avoid importing sympy.codegen
  37. # from the top-level 'import sympy'. Export them here as well.
  38. from sympy.printing.codeprinter import fcode, print_fcode # noqa:F401
  39. known_functions = {
  40. "sin": "sin",
  41. "cos": "cos",
  42. "tan": "tan",
  43. "asin": "asin",
  44. "acos": "acos",
  45. "atan": "atan",
  46. "atan2": "atan2",
  47. "sinh": "sinh",
  48. "cosh": "cosh",
  49. "tanh": "tanh",
  50. "log": "log",
  51. "exp": "exp",
  52. "erf": "erf",
  53. "Abs": "abs",
  54. "conjugate": "conjg",
  55. "Max": "max",
  56. "Min": "min",
  57. }
  58. class FCodePrinter(CodePrinter):
  59. """A printer to convert SymPy expressions to strings of Fortran code"""
  60. printmethod = "_fcode"
  61. language = "Fortran"
  62. type_aliases = {
  63. integer: int32,
  64. real: float64,
  65. complex_: complex128,
  66. }
  67. type_mappings = {
  68. intc: 'integer(c_int)',
  69. float32: 'real*4', # real(kind(0.e0))
  70. float64: 'real*8', # real(kind(0.d0))
  71. float80: 'real*10', # real(kind(????))
  72. complex64: 'complex*8',
  73. complex128: 'complex*16',
  74. int8: 'integer*1',
  75. int16: 'integer*2',
  76. int32: 'integer*4',
  77. int64: 'integer*8',
  78. bool_: 'logical'
  79. }
  80. type_modules = {
  81. intc: {'iso_c_binding': 'c_int'}
  82. }
  83. _default_settings: dict[str, Any] = {
  84. 'order': None,
  85. 'full_prec': 'auto',
  86. 'precision': 17,
  87. 'user_functions': {},
  88. 'human': True,
  89. 'allow_unknown_functions': False,
  90. 'source_format': 'fixed',
  91. 'contract': True,
  92. 'standard': 77,
  93. 'name_mangling': True,
  94. }
  95. _operators = {
  96. 'and': '.and.',
  97. 'or': '.or.',
  98. 'xor': '.neqv.',
  99. 'equivalent': '.eqv.',
  100. 'not': '.not. ',
  101. }
  102. _relationals = {
  103. '!=': '/=',
  104. }
  105. def __init__(self, settings=None):
  106. if not settings:
  107. settings = {}
  108. self.mangled_symbols = {} # Dict showing mapping of all words
  109. self.used_name = []
  110. self.type_aliases = dict(chain(self.type_aliases.items(),
  111. settings.pop('type_aliases', {}).items()))
  112. self.type_mappings = dict(chain(self.type_mappings.items(),
  113. settings.pop('type_mappings', {}).items()))
  114. super().__init__(settings)
  115. self.known_functions = dict(known_functions)
  116. userfuncs = settings.get('user_functions', {})
  117. self.known_functions.update(userfuncs)
  118. # leading columns depend on fixed or free format
  119. standards = {66, 77, 90, 95, 2003, 2008}
  120. if self._settings['standard'] not in standards:
  121. raise ValueError("Unknown Fortran standard: %s" % self._settings[
  122. 'standard'])
  123. self.module_uses = defaultdict(set) # e.g.: use iso_c_binding, only: c_int
  124. @property
  125. def _lead(self):
  126. if self._settings['source_format'] == 'fixed':
  127. return {'code': " ", 'cont': " @ ", 'comment': "C "}
  128. elif self._settings['source_format'] == 'free':
  129. return {'code': "", 'cont': " ", 'comment': "! "}
  130. else:
  131. raise ValueError("Unknown source format: %s" % self._settings['source_format'])
  132. def _print_Symbol(self, expr):
  133. if self._settings['name_mangling'] == True:
  134. if expr not in self.mangled_symbols:
  135. name = expr.name
  136. while name.lower() in self.used_name:
  137. name += '_'
  138. self.used_name.append(name.lower())
  139. if name == expr.name:
  140. self.mangled_symbols[expr] = expr
  141. else:
  142. self.mangled_symbols[expr] = Symbol(name)
  143. expr = expr.xreplace(self.mangled_symbols)
  144. name = super()._print_Symbol(expr)
  145. return name
  146. def _rate_index_position(self, p):
  147. return -p*5
  148. def _get_statement(self, codestring):
  149. return codestring
  150. def _get_comment(self, text):
  151. return "! {}".format(text)
  152. def _declare_number_const(self, name, value):
  153. return "parameter ({} = {})".format(name, self._print(value))
  154. def _print_NumberSymbol(self, expr):
  155. # A Number symbol that is not implemented here or with _printmethod
  156. # is registered and evaluated
  157. self._number_symbols.add((expr, Float(expr.evalf(self._settings['precision']))))
  158. return str(expr)
  159. def _format_code(self, lines):
  160. return self._wrap_fortran(self.indent_code(lines))
  161. def _traverse_matrix_indices(self, mat):
  162. rows, cols = mat.shape
  163. return ((i, j) for j in range(cols) for i in range(rows))
  164. def _get_loop_opening_ending(self, indices):
  165. open_lines = []
  166. close_lines = []
  167. for i in indices:
  168. # fortran arrays start at 1 and end at dimension
  169. var, start, stop = map(self._print,
  170. [i.label, i.lower + 1, i.upper + 1])
  171. open_lines.append("do %s = %s, %s" % (var, start, stop))
  172. close_lines.append("end do")
  173. return open_lines, close_lines
  174. def _print_sign(self, expr):
  175. from sympy.functions.elementary.complexes import Abs
  176. arg, = expr.args
  177. if arg.is_integer:
  178. new_expr = merge(0, isign(1, arg), Eq(arg, 0))
  179. elif (arg.is_complex or arg.is_infinite):
  180. new_expr = merge(cmplx(literal_dp(0), literal_dp(0)), arg/Abs(arg), Eq(Abs(arg), literal_dp(0)))
  181. else:
  182. new_expr = merge(literal_dp(0), dsign(literal_dp(1), arg), Eq(arg, literal_dp(0)))
  183. return self._print(new_expr)
  184. def _print_Piecewise(self, expr):
  185. if expr.args[-1].cond != True:
  186. # We need the last conditional to be a True, otherwise the resulting
  187. # function may not return a result.
  188. raise ValueError("All Piecewise expressions must contain an "
  189. "(expr, True) statement to be used as a default "
  190. "condition. Without one, the generated "
  191. "expression may not evaluate to anything under "
  192. "some condition.")
  193. lines = []
  194. if expr.has(Assignment):
  195. for i, (e, c) in enumerate(expr.args):
  196. if i == 0:
  197. lines.append("if (%s) then" % self._print(c))
  198. elif i == len(expr.args) - 1 and c == True:
  199. lines.append("else")
  200. else:
  201. lines.append("else if (%s) then" % self._print(c))
  202. lines.append(self._print(e))
  203. lines.append("end if")
  204. return "\n".join(lines)
  205. elif self._settings["standard"] >= 95:
  206. # Only supported in F95 and newer:
  207. # The piecewise was used in an expression, need to do inline
  208. # operators. This has the downside that inline operators will
  209. # not work for statements that span multiple lines (Matrix or
  210. # Indexed expressions).
  211. pattern = "merge({T}, {F}, {COND})"
  212. code = self._print(expr.args[-1].expr)
  213. terms = list(expr.args[:-1])
  214. while terms:
  215. e, c = terms.pop()
  216. expr = self._print(e)
  217. cond = self._print(c)
  218. code = pattern.format(T=expr, F=code, COND=cond)
  219. return code
  220. else:
  221. # `merge` is not supported prior to F95
  222. raise NotImplementedError("Using Piecewise as an expression using "
  223. "inline operators is not supported in "
  224. "standards earlier than Fortran95.")
  225. def _print_MatrixElement(self, expr):
  226. return "{}({}, {})".format(self.parenthesize(expr.parent,
  227. PRECEDENCE["Atom"], strict=True), expr.i + 1, expr.j + 1)
  228. def _print_Add(self, expr):
  229. # purpose: print complex numbers nicely in Fortran.
  230. # collect the purely real and purely imaginary parts:
  231. pure_real = []
  232. pure_imaginary = []
  233. mixed = []
  234. for arg in expr.args:
  235. if arg.is_number and arg.is_real:
  236. pure_real.append(arg)
  237. elif arg.is_number and arg.is_imaginary:
  238. pure_imaginary.append(arg)
  239. else:
  240. mixed.append(arg)
  241. if pure_imaginary:
  242. if mixed:
  243. PREC = precedence(expr)
  244. term = Add(*mixed)
  245. t = self._print(term)
  246. if t.startswith('-'):
  247. sign = "-"
  248. t = t[1:]
  249. else:
  250. sign = "+"
  251. if precedence(term) < PREC:
  252. t = "(%s)" % t
  253. return "cmplx(%s,%s) %s %s" % (
  254. self._print(Add(*pure_real)),
  255. self._print(-S.ImaginaryUnit*Add(*pure_imaginary)),
  256. sign, t,
  257. )
  258. else:
  259. return "cmplx(%s,%s)" % (
  260. self._print(Add(*pure_real)),
  261. self._print(-S.ImaginaryUnit*Add(*pure_imaginary)),
  262. )
  263. else:
  264. return CodePrinter._print_Add(self, expr)
  265. def _print_Function(self, expr):
  266. # All constant function args are evaluated as floats
  267. prec = self._settings['precision']
  268. args = [N(a, prec) for a in expr.args]
  269. eval_expr = expr.func(*args)
  270. if not isinstance(eval_expr, Function):
  271. return self._print(eval_expr)
  272. else:
  273. return CodePrinter._print_Function(self, expr.func(*args))
  274. def _print_Mod(self, expr):
  275. # NOTE : Fortran has the functions mod() and modulo(). modulo() behaves
  276. # the same wrt to the sign of the arguments as Python and SymPy's
  277. # modulus computations (% and Mod()) but is not available in Fortran 66
  278. # or Fortran 77, thus we raise an error.
  279. if self._settings['standard'] in [66, 77]:
  280. msg = ("Python % operator and SymPy's Mod() function are not "
  281. "supported by Fortran 66 or 77 standards.")
  282. raise NotImplementedError(msg)
  283. else:
  284. x, y = expr.args
  285. return " modulo({}, {})".format(self._print(x), self._print(y))
  286. def _print_ImaginaryUnit(self, expr):
  287. # purpose: print complex numbers nicely in Fortran.
  288. return "cmplx(0,1)"
  289. def _print_int(self, expr):
  290. return str(expr)
  291. def _print_Mul(self, expr):
  292. # purpose: print complex numbers nicely in Fortran.
  293. if expr.is_number and expr.is_imaginary:
  294. return "cmplx(0,%s)" % (
  295. self._print(-S.ImaginaryUnit*expr)
  296. )
  297. else:
  298. return CodePrinter._print_Mul(self, expr)
  299. def _print_Pow(self, expr):
  300. PREC = precedence(expr)
  301. if equal_valued(expr.exp, -1):
  302. return '%s/%s' % (
  303. self._print(literal_dp(1)),
  304. self.parenthesize(expr.base, PREC)
  305. )
  306. elif equal_valued(expr.exp, 0.5):
  307. if expr.base.is_integer:
  308. # Fortran intrinsic sqrt() does not accept integer argument
  309. if expr.base.is_Number:
  310. return 'sqrt(%s.0d0)' % self._print(expr.base)
  311. else:
  312. return 'sqrt(dble(%s))' % self._print(expr.base)
  313. else:
  314. return 'sqrt(%s)' % self._print(expr.base)
  315. else:
  316. return CodePrinter._print_Pow(self, expr)
  317. def _print_Rational(self, expr):
  318. p, q = int(expr.p), int(expr.q)
  319. return "%d.0d0/%d.0d0" % (p, q)
  320. def _print_Float(self, expr):
  321. printed = CodePrinter._print_Float(self, expr)
  322. e = printed.find('e')
  323. if e > -1:
  324. return "%sd%s" % (printed[:e], printed[e + 1:])
  325. return "%sd0" % printed
  326. def _print_Relational(self, expr):
  327. lhs_code = self._print(expr.lhs)
  328. rhs_code = self._print(expr.rhs)
  329. op = expr.rel_op
  330. op = op if op not in self._relationals else self._relationals[op]
  331. return "{} {} {}".format(lhs_code, op, rhs_code)
  332. def _print_Indexed(self, expr):
  333. inds = [ self._print(i) for i in expr.indices ]
  334. return "%s(%s)" % (self._print(expr.base.label), ", ".join(inds))
  335. def _print_Idx(self, expr):
  336. return self._print(expr.label)
  337. def _print_AugmentedAssignment(self, expr):
  338. lhs_code = self._print(expr.lhs)
  339. rhs_code = self._print(expr.rhs)
  340. return self._get_statement("{0} = {0} {1} {2}".format(
  341. self._print(lhs_code), self._print(expr.binop), self._print(rhs_code)))
  342. def _print_sum_(self, sm):
  343. params = self._print(sm.array)
  344. if sm.dim != None: # Must use '!= None', cannot use 'is not None'
  345. params += ', ' + self._print(sm.dim)
  346. if sm.mask != None: # Must use '!= None', cannot use 'is not None'
  347. params += ', mask=' + self._print(sm.mask)
  348. return '%s(%s)' % (sm.__class__.__name__.rstrip('_'), params)
  349. def _print_product_(self, prod):
  350. return self._print_sum_(prod)
  351. def _print_Do(self, do):
  352. excl = ['concurrent']
  353. if do.step == 1:
  354. excl.append('step')
  355. step = ''
  356. else:
  357. step = ', {step}'
  358. return (
  359. 'do {concurrent}{counter} = {first}, {last}'+step+'\n'
  360. '{body}\n'
  361. 'end do\n'
  362. ).format(
  363. concurrent='concurrent ' if do.concurrent else '',
  364. **do.kwargs(apply=lambda arg: self._print(arg), exclude=excl)
  365. )
  366. def _print_ImpliedDoLoop(self, idl):
  367. step = '' if idl.step == 1 else ', {step}'
  368. return ('({expr}, {counter} = {first}, {last}'+step+')').format(
  369. **idl.kwargs(apply=lambda arg: self._print(arg))
  370. )
  371. def _print_For(self, expr):
  372. target = self._print(expr.target)
  373. if isinstance(expr.iterable, Range):
  374. start, stop, step = expr.iterable.args
  375. else:
  376. raise NotImplementedError("Only iterable currently supported is Range")
  377. body = self._print(expr.body)
  378. return ('do {target} = {start}, {stop}, {step}\n'
  379. '{body}\n'
  380. 'end do').format(target=target, start=start, stop=stop - 1,
  381. step=step, body=body)
  382. def _print_Type(self, type_):
  383. type_ = self.type_aliases.get(type_, type_)
  384. type_str = self.type_mappings.get(type_, type_.name)
  385. module_uses = self.type_modules.get(type_)
  386. if module_uses:
  387. for k, v in module_uses:
  388. self.module_uses[k].add(v)
  389. return type_str
  390. def _print_Element(self, elem):
  391. return '{symbol}({idxs})'.format(
  392. symbol=self._print(elem.symbol),
  393. idxs=', '.join((self._print(arg) for arg in elem.indices))
  394. )
  395. def _print_Extent(self, ext):
  396. return str(ext)
  397. def _print_Declaration(self, expr):
  398. var = expr.variable
  399. val = var.value
  400. dim = var.attr_params('dimension')
  401. intents = [intent in var.attrs for intent in (intent_in, intent_out, intent_inout)]
  402. if intents.count(True) == 0:
  403. intent = ''
  404. elif intents.count(True) == 1:
  405. intent = ', intent(%s)' % ['in', 'out', 'inout'][intents.index(True)]
  406. else:
  407. raise ValueError("Multiple intents specified for %s" % self)
  408. if isinstance(var, Pointer):
  409. raise NotImplementedError("Pointers are not available by default in Fortran.")
  410. if self._settings["standard"] >= 90:
  411. result = '{t}{vc}{dim}{intent}{alloc} :: {s}'.format(
  412. t=self._print(var.type),
  413. vc=', parameter' if value_const in var.attrs else '',
  414. dim=', dimension(%s)' % ', '.join((self._print(arg) for arg in dim)) if dim else '',
  415. intent=intent,
  416. alloc=', allocatable' if allocatable in var.attrs else '',
  417. s=self._print(var.symbol)
  418. )
  419. if val != None: # Must be "!= None", cannot be "is not None"
  420. result += ' = %s' % self._print(val)
  421. else:
  422. if value_const in var.attrs or val:
  423. raise NotImplementedError("F77 init./parameter statem. req. multiple lines.")
  424. result = ' '.join((self._print(arg) for arg in [var.type, var.symbol]))
  425. return result
  426. def _print_Infinity(self, expr):
  427. return '(huge(%s) + 1)' % self._print(literal_dp(0))
  428. def _print_While(self, expr):
  429. return 'do while ({condition})\n{body}\nend do'.format(**expr.kwargs(
  430. apply=lambda arg: self._print(arg)))
  431. def _print_BooleanTrue(self, expr):
  432. return '.true.'
  433. def _print_BooleanFalse(self, expr):
  434. return '.false.'
  435. def _pad_leading_columns(self, lines):
  436. result = []
  437. for line in lines:
  438. if line.startswith('!'):
  439. result.append(self._lead['comment'] + line[1:].lstrip())
  440. else:
  441. result.append(self._lead['code'] + line)
  442. return result
  443. def _wrap_fortran(self, lines):
  444. """Wrap long Fortran lines
  445. Argument:
  446. lines -- a list of lines (without \\n character)
  447. A comment line is split at white space. Code lines are split with a more
  448. complex rule to give nice results.
  449. """
  450. # routine to find split point in a code line
  451. my_alnum = set("_+-." + string.digits + string.ascii_letters)
  452. my_white = set(" \t()")
  453. def split_pos_code(line, endpos):
  454. if len(line) <= endpos:
  455. return len(line)
  456. pos = endpos
  457. split = lambda pos: \
  458. (line[pos] in my_alnum and line[pos - 1] not in my_alnum) or \
  459. (line[pos] not in my_alnum and line[pos - 1] in my_alnum) or \
  460. (line[pos] in my_white and line[pos - 1] not in my_white) or \
  461. (line[pos] not in my_white and line[pos - 1] in my_white)
  462. while not split(pos):
  463. pos -= 1
  464. if pos == 0:
  465. return endpos
  466. return pos
  467. # split line by line and add the split lines to result
  468. result = []
  469. if self._settings['source_format'] == 'free':
  470. trailing = ' &'
  471. else:
  472. trailing = ''
  473. for line in lines:
  474. if line.startswith(self._lead['comment']):
  475. # comment line
  476. if len(line) > 72:
  477. pos = line.rfind(" ", 6, 72)
  478. if pos == -1:
  479. pos = 72
  480. hunk = line[:pos]
  481. line = line[pos:].lstrip()
  482. result.append(hunk)
  483. while line:
  484. pos = line.rfind(" ", 0, 66)
  485. if pos == -1 or len(line) < 66:
  486. pos = 66
  487. hunk = line[:pos]
  488. line = line[pos:].lstrip()
  489. result.append("%s%s" % (self._lead['comment'], hunk))
  490. else:
  491. result.append(line)
  492. elif line.startswith(self._lead['code']):
  493. # code line
  494. pos = split_pos_code(line, 72)
  495. hunk = line[:pos].rstrip()
  496. line = line[pos:].lstrip()
  497. if line:
  498. hunk += trailing
  499. result.append(hunk)
  500. while line:
  501. pos = split_pos_code(line, 65)
  502. hunk = line[:pos].rstrip()
  503. line = line[pos:].lstrip()
  504. if line:
  505. hunk += trailing
  506. result.append("%s%s" % (self._lead['cont'], hunk))
  507. else:
  508. result.append(line)
  509. return result
  510. def indent_code(self, code):
  511. """Accepts a string of code or a list of code lines"""
  512. if isinstance(code, str):
  513. code_lines = self.indent_code(code.splitlines(True))
  514. return ''.join(code_lines)
  515. free = self._settings['source_format'] == 'free'
  516. code = [ line.lstrip(' \t') for line in code ]
  517. inc_keyword = ('do ', 'if(', 'if ', 'do\n', 'else', 'program', 'interface')
  518. dec_keyword = ('end do', 'enddo', 'end if', 'endif', 'else', 'end program', 'end interface')
  519. increase = [ int(any(map(line.startswith, inc_keyword)))
  520. for line in code ]
  521. decrease = [ int(any(map(line.startswith, dec_keyword)))
  522. for line in code ]
  523. continuation = [ int(any(map(line.endswith, ['&', '&\n'])))
  524. for line in code ]
  525. level = 0
  526. cont_padding = 0
  527. tabwidth = 3
  528. new_code = []
  529. for i, line in enumerate(code):
  530. if line in ('', '\n'):
  531. new_code.append(line)
  532. continue
  533. level -= decrease[i]
  534. if free:
  535. padding = " "*(level*tabwidth + cont_padding)
  536. else:
  537. padding = " "*level*tabwidth
  538. line = "%s%s" % (padding, line)
  539. if not free:
  540. line = self._pad_leading_columns([line])[0]
  541. new_code.append(line)
  542. if continuation[i]:
  543. cont_padding = 2*tabwidth
  544. else:
  545. cont_padding = 0
  546. level += increase[i]
  547. if not free:
  548. return self._wrap_fortran(new_code)
  549. return new_code
  550. def _print_GoTo(self, goto):
  551. if goto.expr: # computed goto
  552. return "go to ({labels}), {expr}".format(
  553. labels=', '.join((self._print(arg) for arg in goto.labels)),
  554. expr=self._print(goto.expr)
  555. )
  556. else:
  557. lbl, = goto.labels
  558. return "go to %s" % self._print(lbl)
  559. def _print_Program(self, prog):
  560. return (
  561. "program {name}\n"
  562. "{body}\n"
  563. "end program\n"
  564. ).format(**prog.kwargs(apply=lambda arg: self._print(arg)))
  565. def _print_Module(self, mod):
  566. return (
  567. "module {name}\n"
  568. "{declarations}\n"
  569. "\ncontains\n\n"
  570. "{definitions}\n"
  571. "end module\n"
  572. ).format(**mod.kwargs(apply=lambda arg: self._print(arg)))
  573. def _print_Stream(self, strm):
  574. if strm.name == 'stdout' and self._settings["standard"] >= 2003:
  575. self.module_uses['iso_c_binding'].add('stdint=>input_unit')
  576. return 'input_unit'
  577. elif strm.name == 'stderr' and self._settings["standard"] >= 2003:
  578. self.module_uses['iso_c_binding'].add('stdint=>error_unit')
  579. return 'error_unit'
  580. else:
  581. if strm.name == 'stdout':
  582. return '*'
  583. else:
  584. return strm.name
  585. def _print_Print(self, ps):
  586. if ps.format_string != None: # Must be '!= None', cannot be 'is not None'
  587. fmt = self._print(ps.format_string)
  588. else:
  589. fmt = "*"
  590. return "print {fmt}, {iolist}".format(fmt=fmt, iolist=', '.join(
  591. (self._print(arg) for arg in ps.print_args)))
  592. def _print_Return(self, rs):
  593. arg, = rs.args
  594. return "{result_name} = {arg}".format(
  595. result_name=self._context.get('result_name', 'sympy_result'),
  596. arg=self._print(arg)
  597. )
  598. def _print_FortranReturn(self, frs):
  599. arg, = frs.args
  600. if arg:
  601. return 'return %s' % self._print(arg)
  602. else:
  603. return 'return'
  604. def _head(self, entity, fp, **kwargs):
  605. bind_C_params = fp.attr_params('bind_C')
  606. if bind_C_params is None:
  607. bind = ''
  608. else:
  609. bind = ' bind(C, name="%s")' % bind_C_params[0] if bind_C_params else ' bind(C)'
  610. result_name = self._settings.get('result_name', None)
  611. return (
  612. "{entity}{name}({arg_names}){result}{bind}\n"
  613. "{arg_declarations}"
  614. ).format(
  615. entity=entity,
  616. name=self._print(fp.name),
  617. arg_names=', '.join([self._print(arg.symbol) for arg in fp.parameters]),
  618. result=(' result(%s)' % result_name) if result_name else '',
  619. bind=bind,
  620. arg_declarations='\n'.join((self._print(Declaration(arg)) for arg in fp.parameters))
  621. )
  622. def _print_FunctionPrototype(self, fp):
  623. entity = "{} function ".format(self._print(fp.return_type))
  624. return (
  625. "interface\n"
  626. "{function_head}\n"
  627. "end function\n"
  628. "end interface"
  629. ).format(function_head=self._head(entity, fp))
  630. def _print_FunctionDefinition(self, fd):
  631. if elemental in fd.attrs:
  632. prefix = 'elemental '
  633. elif pure in fd.attrs:
  634. prefix = 'pure '
  635. else:
  636. prefix = ''
  637. entity = "{} function ".format(self._print(fd.return_type))
  638. with printer_context(self, result_name=fd.name):
  639. return (
  640. "{prefix}{function_head}\n"
  641. "{body}\n"
  642. "end function\n"
  643. ).format(
  644. prefix=prefix,
  645. function_head=self._head(entity, fd),
  646. body=self._print(fd.body)
  647. )
  648. def _print_Subroutine(self, sub):
  649. return (
  650. '{subroutine_head}\n'
  651. '{body}\n'
  652. 'end subroutine\n'
  653. ).format(
  654. subroutine_head=self._head('subroutine ', sub),
  655. body=self._print(sub.body)
  656. )
  657. def _print_SubroutineCall(self, scall):
  658. return 'call {name}({args})'.format(
  659. name=self._print(scall.name),
  660. args=', '.join((self._print(arg) for arg in scall.subroutine_args))
  661. )
  662. def _print_use_rename(self, rnm):
  663. return "%s => %s" % tuple((self._print(arg) for arg in rnm.args))
  664. def _print_use(self, use):
  665. result = 'use %s' % self._print(use.namespace)
  666. if use.rename != None: # Must be '!= None', cannot be 'is not None'
  667. result += ', ' + ', '.join([self._print(rnm) for rnm in use.rename])
  668. if use.only != None: # Must be '!= None', cannot be 'is not None'
  669. result += ', only: ' + ', '.join([self._print(nly) for nly in use.only])
  670. return result
  671. def _print_BreakToken(self, _):
  672. return 'exit'
  673. def _print_ContinueToken(self, _):
  674. return 'cycle'
  675. def _print_ArrayConstructor(self, ac):
  676. fmtstr = "[%s]" if self._settings["standard"] >= 2003 else '(/%s/)'
  677. return fmtstr % ', '.join((self._print(arg) for arg in ac.elements))
  678. def _print_ArrayElement(self, elem):
  679. return '{symbol}({idxs})'.format(
  680. symbol=self._print(elem.name),
  681. idxs=', '.join((self._print(arg) for arg in elem.indices))
  682. )