fortran.py 28 KB

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