PageRenderTime 63ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/numpy/f2py/crackfortran.py

http://github.com/numpy/numpy
Python | 3347 lines | 3320 code | 0 blank | 27 comment | 7 complexity | 39c963dad02652ef6ab54954ddeb0ef2 MD5 | raw file
Possible License(s): BSD-3-Clause, JSON, Unlicense
  1. #!/usr/bin/env python3
  2. """
  3. crackfortran --- read fortran (77,90) code and extract declaration information.
  4. Copyright 1999-2004 Pearu Peterson all rights reserved,
  5. Pearu Peterson <pearu@ioc.ee>
  6. Permission to use, modify, and distribute this software is given under the
  7. terms of the NumPy License.
  8. NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
  9. $Date: 2005/09/27 07:13:49 $
  10. Pearu Peterson
  11. Usage of crackfortran:
  12. ======================
  13. Command line keys: -quiet,-verbose,-fix,-f77,-f90,-show,-h <pyffilename>
  14. -m <module name for f77 routines>,--ignore-contains
  15. Functions: crackfortran, crack2fortran
  16. The following Fortran statements/constructions are supported
  17. (or will be if needed):
  18. block data,byte,call,character,common,complex,contains,data,
  19. dimension,double complex,double precision,end,external,function,
  20. implicit,integer,intent,interface,intrinsic,
  21. logical,module,optional,parameter,private,public,
  22. program,real,(sequence?),subroutine,type,use,virtual,
  23. include,pythonmodule
  24. Note: 'virtual' is mapped to 'dimension'.
  25. Note: 'implicit integer (z) static (z)' is 'implicit static (z)' (this is minor bug).
  26. Note: code after 'contains' will be ignored until its scope ends.
  27. Note: 'common' statement is extended: dimensions are moved to variable definitions
  28. Note: f2py directive: <commentchar>f2py<line> is read as <line>
  29. Note: pythonmodule is introduced to represent Python module
  30. Usage:
  31. `postlist=crackfortran(files)`
  32. `postlist` contains declaration information read from the list of files `files`.
  33. `crack2fortran(postlist)` returns a fortran code to be saved to pyf-file
  34. `postlist` has the following structure:
  35. *** it is a list of dictionaries containing `blocks':
  36. B = {'block','body','vars','parent_block'[,'name','prefix','args','result',
  37. 'implicit','externals','interfaced','common','sortvars',
  38. 'commonvars','note']}
  39. B['block'] = 'interface' | 'function' | 'subroutine' | 'module' |
  40. 'program' | 'block data' | 'type' | 'pythonmodule'
  41. B['body'] --- list containing `subblocks' with the same structure as `blocks'
  42. B['parent_block'] --- dictionary of a parent block:
  43. C['body'][<index>]['parent_block'] is C
  44. B['vars'] --- dictionary of variable definitions
  45. B['sortvars'] --- dictionary of variable definitions sorted by dependence (independent first)
  46. B['name'] --- name of the block (not if B['block']=='interface')
  47. B['prefix'] --- prefix string (only if B['block']=='function')
  48. B['args'] --- list of argument names if B['block']== 'function' | 'subroutine'
  49. B['result'] --- name of the return value (only if B['block']=='function')
  50. B['implicit'] --- dictionary {'a':<variable definition>,'b':...} | None
  51. B['externals'] --- list of variables being external
  52. B['interfaced'] --- list of variables being external and defined
  53. B['common'] --- dictionary of common blocks (list of objects)
  54. B['commonvars'] --- list of variables used in common blocks (dimensions are moved to variable definitions)
  55. B['from'] --- string showing the 'parents' of the current block
  56. B['use'] --- dictionary of modules used in current block:
  57. {<modulename>:{['only':<0|1>],['map':{<local_name1>:<use_name1>,...}]}}
  58. B['note'] --- list of LaTeX comments on the block
  59. B['f2pyenhancements'] --- optional dictionary
  60. {'threadsafe':'','fortranname':<name>,
  61. 'callstatement':<C-expr>|<multi-line block>,
  62. 'callprotoargument':<C-expr-list>,
  63. 'usercode':<multi-line block>|<list of multi-line blocks>,
  64. 'pymethoddef:<multi-line block>'
  65. }
  66. B['entry'] --- dictionary {entryname:argslist,..}
  67. B['varnames'] --- list of variable names given in the order of reading the
  68. Fortran code, useful for derived types.
  69. B['saved_interface'] --- a string of scanned routine signature, defines explicit interface
  70. *** Variable definition is a dictionary
  71. D = B['vars'][<variable name>] =
  72. {'typespec'[,'attrspec','kindselector','charselector','=','typename']}
  73. D['typespec'] = 'byte' | 'character' | 'complex' | 'double complex' |
  74. 'double precision' | 'integer' | 'logical' | 'real' | 'type'
  75. D['attrspec'] --- list of attributes (e.g. 'dimension(<arrayspec>)',
  76. 'external','intent(in|out|inout|hide|c|callback|cache|aligned4|aligned8|aligned16)',
  77. 'optional','required', etc)
  78. K = D['kindselector'] = {['*','kind']} (only if D['typespec'] =
  79. 'complex' | 'integer' | 'logical' | 'real' )
  80. C = D['charselector'] = {['*','len','kind']}
  81. (only if D['typespec']=='character')
  82. D['='] --- initialization expression string
  83. D['typename'] --- name of the type if D['typespec']=='type'
  84. D['dimension'] --- list of dimension bounds
  85. D['intent'] --- list of intent specifications
  86. D['depend'] --- list of variable names on which current variable depends on
  87. D['check'] --- list of C-expressions; if C-expr returns zero, exception is raised
  88. D['note'] --- list of LaTeX comments on the variable
  89. *** Meaning of kind/char selectors (few examples):
  90. D['typespec>']*K['*']
  91. D['typespec'](kind=K['kind'])
  92. character*C['*']
  93. character(len=C['len'],kind=C['kind'])
  94. (see also fortran type declaration statement formats below)
  95. Fortran 90 type declaration statement format (F77 is subset of F90)
  96. ====================================================================
  97. (Main source: IBM XL Fortran 5.1 Language Reference Manual)
  98. type declaration = <typespec> [[<attrspec>]::] <entitydecl>
  99. <typespec> = byte |
  100. character[<charselector>] |
  101. complex[<kindselector>] |
  102. double complex |
  103. double precision |
  104. integer[<kindselector>] |
  105. logical[<kindselector>] |
  106. real[<kindselector>] |
  107. type(<typename>)
  108. <charselector> = * <charlen> |
  109. ([len=]<len>[,[kind=]<kind>]) |
  110. (kind=<kind>[,len=<len>])
  111. <kindselector> = * <intlen> |
  112. ([kind=]<kind>)
  113. <attrspec> = comma separated list of attributes.
  114. Only the following attributes are used in
  115. building up the interface:
  116. external
  117. (parameter --- affects '=' key)
  118. optional
  119. intent
  120. Other attributes are ignored.
  121. <intentspec> = in | out | inout
  122. <arrayspec> = comma separated list of dimension bounds.
  123. <entitydecl> = <name> [[*<charlen>][(<arrayspec>)] | [(<arrayspec>)]*<charlen>]
  124. [/<init_expr>/ | =<init_expr>] [,<entitydecl>]
  125. In addition, the following attributes are used: check,depend,note
  126. TODO:
  127. * Apply 'parameter' attribute (e.g. 'integer parameter :: i=2' 'real x(i)'
  128. -> 'real x(2)')
  129. The above may be solved by creating appropriate preprocessor program, for example.
  130. """
  131. import sys
  132. import string
  133. import fileinput
  134. import re
  135. import os
  136. import copy
  137. import platform
  138. from . import __version__
  139. # The environment provided by auxfuncs.py is needed for some calls to eval.
  140. # As the needed functions cannot be determined by static inspection of the
  141. # code, it is safest to use import * pending a major refactoring of f2py.
  142. from .auxfuncs import *
  143. f2py_version = __version__.version
  144. # Global flags:
  145. strictf77 = 1 # Ignore `!' comments unless line[0]=='!'
  146. sourcecodeform = 'fix' # 'fix','free'
  147. quiet = 0 # Be verbose if 0 (Obsolete: not used any more)
  148. verbose = 1 # Be quiet if 0, extra verbose if > 1.
  149. tabchar = 4 * ' '
  150. pyffilename = ''
  151. f77modulename = ''
  152. skipemptyends = 0 # for old F77 programs without 'program' statement
  153. ignorecontains = 1
  154. dolowercase = 1
  155. debug = []
  156. # Global variables
  157. beginpattern = ''
  158. currentfilename = ''
  159. expectbegin = 1
  160. f90modulevars = {}
  161. filepositiontext = ''
  162. gotnextfile = 1
  163. groupcache = None
  164. groupcounter = 0
  165. grouplist = {groupcounter: []}
  166. groupname = ''
  167. include_paths = []
  168. neededmodule = -1
  169. onlyfuncs = []
  170. previous_context = None
  171. skipblocksuntil = -1
  172. skipfuncs = []
  173. skipfunctions = []
  174. usermodules = []
  175. def reset_global_f2py_vars():
  176. global groupcounter, grouplist, neededmodule, expectbegin
  177. global skipblocksuntil, usermodules, f90modulevars, gotnextfile
  178. global filepositiontext, currentfilename, skipfunctions, skipfuncs
  179. global onlyfuncs, include_paths, previous_context
  180. global strictf77, sourcecodeform, quiet, verbose, tabchar, pyffilename
  181. global f77modulename, skipemptyends, ignorecontains, dolowercase, debug
  182. # flags
  183. strictf77 = 1
  184. sourcecodeform = 'fix'
  185. quiet = 0
  186. verbose = 1
  187. tabchar = 4 * ' '
  188. pyffilename = ''
  189. f77modulename = ''
  190. skipemptyends = 0
  191. ignorecontains = 1
  192. dolowercase = 1
  193. debug = []
  194. # variables
  195. groupcounter = 0
  196. grouplist = {groupcounter: []}
  197. neededmodule = -1
  198. expectbegin = 1
  199. skipblocksuntil = -1
  200. usermodules = []
  201. f90modulevars = {}
  202. gotnextfile = 1
  203. filepositiontext = ''
  204. currentfilename = ''
  205. skipfunctions = []
  206. skipfuncs = []
  207. onlyfuncs = []
  208. include_paths = []
  209. previous_context = None
  210. def outmess(line, flag=1):
  211. global filepositiontext
  212. if not verbose:
  213. return
  214. if not quiet:
  215. if flag:
  216. sys.stdout.write(filepositiontext)
  217. sys.stdout.write(line)
  218. re._MAXCACHE = 50
  219. defaultimplicitrules = {}
  220. for c in "abcdefghopqrstuvwxyz$_":
  221. defaultimplicitrules[c] = {'typespec': 'real'}
  222. for c in "ijklmn":
  223. defaultimplicitrules[c] = {'typespec': 'integer'}
  224. del c
  225. badnames = {}
  226. invbadnames = {}
  227. for n in ['int', 'double', 'float', 'char', 'short', 'long', 'void', 'case', 'while',
  228. 'return', 'signed', 'unsigned', 'if', 'for', 'typedef', 'sizeof', 'union',
  229. 'struct', 'static', 'register', 'new', 'break', 'do', 'goto', 'switch',
  230. 'continue', 'else', 'inline', 'extern', 'delete', 'const', 'auto',
  231. 'len', 'rank', 'shape', 'index', 'slen', 'size', '_i',
  232. 'max', 'min',
  233. 'flen', 'fshape',
  234. 'string', 'complex_double', 'float_double', 'stdin', 'stderr', 'stdout',
  235. 'type', 'default']:
  236. badnames[n] = n + '_bn'
  237. invbadnames[n + '_bn'] = n
  238. def rmbadname1(name):
  239. if name in badnames:
  240. errmess('rmbadname1: Replacing "%s" with "%s".\n' %
  241. (name, badnames[name]))
  242. return badnames[name]
  243. return name
  244. def rmbadname(names):
  245. return [rmbadname1(_m) for _m in names]
  246. def undo_rmbadname1(name):
  247. if name in invbadnames:
  248. errmess('undo_rmbadname1: Replacing "%s" with "%s".\n'
  249. % (name, invbadnames[name]))
  250. return invbadnames[name]
  251. return name
  252. def undo_rmbadname(names):
  253. return [undo_rmbadname1(_m) for _m in names]
  254. def getextension(name):
  255. i = name.rfind('.')
  256. if i == -1:
  257. return ''
  258. if '\\' in name[i:]:
  259. return ''
  260. if '/' in name[i:]:
  261. return ''
  262. return name[i + 1:]
  263. is_f_file = re.compile(r'.*[.](for|ftn|f77|f)\Z', re.I).match
  264. _has_f_header = re.compile(r'-[*]-\s*fortran\s*-[*]-', re.I).search
  265. _has_f90_header = re.compile(r'-[*]-\s*f90\s*-[*]-', re.I).search
  266. _has_fix_header = re.compile(r'-[*]-\s*fix\s*-[*]-', re.I).search
  267. _free_f90_start = re.compile(r'[^c*]\s*[^\s\d\t]', re.I).match
  268. def is_free_format(file):
  269. """Check if file is in free format Fortran."""
  270. # f90 allows both fixed and free format, assuming fixed unless
  271. # signs of free format are detected.
  272. result = 0
  273. with open(file, 'r') as f:
  274. line = f.readline()
  275. n = 15 # the number of non-comment lines to scan for hints
  276. if _has_f_header(line):
  277. n = 0
  278. elif _has_f90_header(line):
  279. n = 0
  280. result = 1
  281. while n > 0 and line:
  282. if line[0] != '!' and line.strip():
  283. n -= 1
  284. if (line[0] != '\t' and _free_f90_start(line[:5])) or line[-2:-1] == '&':
  285. result = 1
  286. break
  287. line = f.readline()
  288. return result
  289. # Read fortran (77,90) code
  290. def readfortrancode(ffile, dowithline=show, istop=1):
  291. """
  292. Read fortran codes from files and
  293. 1) Get rid of comments, line continuations, and empty lines; lower cases.
  294. 2) Call dowithline(line) on every line.
  295. 3) Recursively call itself when statement \"include '<filename>'\" is met.
  296. """
  297. global gotnextfile, filepositiontext, currentfilename, sourcecodeform, strictf77
  298. global beginpattern, quiet, verbose, dolowercase, include_paths
  299. if not istop:
  300. saveglobals = gotnextfile, filepositiontext, currentfilename, sourcecodeform, strictf77,\
  301. beginpattern, quiet, verbose, dolowercase
  302. if ffile == []:
  303. return
  304. localdolowercase = dolowercase
  305. cont = 0
  306. finalline = ''
  307. ll = ''
  308. includeline = re.compile(
  309. r'\s*include\s*(\'|")(?P<name>[^\'"]*)(\'|")', re.I)
  310. cont1 = re.compile(r'(?P<line>.*)&\s*\Z')
  311. cont2 = re.compile(r'(\s*&|)(?P<line>.*)')
  312. mline_mark = re.compile(r".*?'''")
  313. if istop:
  314. dowithline('', -1)
  315. ll, l1 = '', ''
  316. spacedigits = [' '] + [str(_m) for _m in range(10)]
  317. filepositiontext = ''
  318. fin = fileinput.FileInput(ffile)
  319. while True:
  320. l = fin.readline()
  321. if not l:
  322. break
  323. if fin.isfirstline():
  324. filepositiontext = ''
  325. currentfilename = fin.filename()
  326. gotnextfile = 1
  327. l1 = l
  328. strictf77 = 0
  329. sourcecodeform = 'fix'
  330. ext = os.path.splitext(currentfilename)[1]
  331. if is_f_file(currentfilename) and \
  332. not (_has_f90_header(l) or _has_fix_header(l)):
  333. strictf77 = 1
  334. elif is_free_format(currentfilename) and not _has_fix_header(l):
  335. sourcecodeform = 'free'
  336. if strictf77:
  337. beginpattern = beginpattern77
  338. else:
  339. beginpattern = beginpattern90
  340. outmess('\tReading file %s (format:%s%s)\n'
  341. % (repr(currentfilename), sourcecodeform,
  342. strictf77 and ',strict' or ''))
  343. l = l.expandtabs().replace('\xa0', ' ')
  344. # Get rid of newline characters
  345. while not l == '':
  346. if l[-1] not in "\n\r\f":
  347. break
  348. l = l[:-1]
  349. if not strictf77:
  350. (l, rl) = split_by_unquoted(l, '!')
  351. l += ' '
  352. if rl[:5].lower() == '!f2py': # f2py directive
  353. l, _ = split_by_unquoted(l + 4 * ' ' + rl[5:], '!')
  354. if l.strip() == '': # Skip empty line
  355. cont = 0
  356. continue
  357. if sourcecodeform == 'fix':
  358. if l[0] in ['*', 'c', '!', 'C', '#']:
  359. if l[1:5].lower() == 'f2py': # f2py directive
  360. l = ' ' + l[5:]
  361. else: # Skip comment line
  362. cont = 0
  363. continue
  364. elif strictf77:
  365. if len(l) > 72:
  366. l = l[:72]
  367. if not (l[0] in spacedigits):
  368. raise Exception('readfortrancode: Found non-(space,digit) char '
  369. 'in the first column.\n\tAre you sure that '
  370. 'this code is in fix form?\n\tline=%s' % repr(l))
  371. if (not cont or strictf77) and (len(l) > 5 and not l[5] == ' '):
  372. # Continuation of a previous line
  373. ll = ll + l[6:]
  374. finalline = ''
  375. origfinalline = ''
  376. else:
  377. if not strictf77:
  378. # F90 continuation
  379. r = cont1.match(l)
  380. if r:
  381. l = r.group('line') # Continuation follows ..
  382. if cont:
  383. ll = ll + cont2.match(l).group('line')
  384. finalline = ''
  385. origfinalline = ''
  386. else:
  387. # clean up line beginning from possible digits.
  388. l = ' ' + l[5:]
  389. if localdolowercase:
  390. finalline = ll.lower()
  391. else:
  392. finalline = ll
  393. origfinalline = ll
  394. ll = l
  395. cont = (r is not None)
  396. else:
  397. # clean up line beginning from possible digits.
  398. l = ' ' + l[5:]
  399. if localdolowercase:
  400. finalline = ll.lower()
  401. else:
  402. finalline = ll
  403. origfinalline = ll
  404. ll = l
  405. elif sourcecodeform == 'free':
  406. if not cont and ext == '.pyf' and mline_mark.match(l):
  407. l = l + '\n'
  408. while True:
  409. lc = fin.readline()
  410. if not lc:
  411. errmess(
  412. 'Unexpected end of file when reading multiline\n')
  413. break
  414. l = l + lc
  415. if mline_mark.match(lc):
  416. break
  417. l = l.rstrip()
  418. r = cont1.match(l)
  419. if r:
  420. l = r.group('line') # Continuation follows ..
  421. if cont:
  422. ll = ll + cont2.match(l).group('line')
  423. finalline = ''
  424. origfinalline = ''
  425. else:
  426. if localdolowercase:
  427. finalline = ll.lower()
  428. else:
  429. finalline = ll
  430. origfinalline = ll
  431. ll = l
  432. cont = (r is not None)
  433. else:
  434. raise ValueError(
  435. "Flag sourcecodeform must be either 'fix' or 'free': %s" % repr(sourcecodeform))
  436. filepositiontext = 'Line #%d in %s:"%s"\n\t' % (
  437. fin.filelineno() - 1, currentfilename, l1)
  438. m = includeline.match(origfinalline)
  439. if m:
  440. fn = m.group('name')
  441. if os.path.isfile(fn):
  442. readfortrancode(fn, dowithline=dowithline, istop=0)
  443. else:
  444. include_dirs = [
  445. os.path.dirname(currentfilename)] + include_paths
  446. foundfile = 0
  447. for inc_dir in include_dirs:
  448. fn1 = os.path.join(inc_dir, fn)
  449. if os.path.isfile(fn1):
  450. foundfile = 1
  451. readfortrancode(fn1, dowithline=dowithline, istop=0)
  452. break
  453. if not foundfile:
  454. outmess('readfortrancode: could not find include file %s in %s. Ignoring.\n' % (
  455. repr(fn), os.pathsep.join(include_dirs)))
  456. else:
  457. dowithline(finalline)
  458. l1 = ll
  459. if localdolowercase:
  460. finalline = ll.lower()
  461. else:
  462. finalline = ll
  463. origfinalline = ll
  464. filepositiontext = 'Line #%d in %s:"%s"\n\t' % (
  465. fin.filelineno() - 1, currentfilename, l1)
  466. m = includeline.match(origfinalline)
  467. if m:
  468. fn = m.group('name')
  469. if os.path.isfile(fn):
  470. readfortrancode(fn, dowithline=dowithline, istop=0)
  471. else:
  472. include_dirs = [os.path.dirname(currentfilename)] + include_paths
  473. foundfile = 0
  474. for inc_dir in include_dirs:
  475. fn1 = os.path.join(inc_dir, fn)
  476. if os.path.isfile(fn1):
  477. foundfile = 1
  478. readfortrancode(fn1, dowithline=dowithline, istop=0)
  479. break
  480. if not foundfile:
  481. outmess('readfortrancode: could not find include file %s in %s. Ignoring.\n' % (
  482. repr(fn), os.pathsep.join(include_dirs)))
  483. else:
  484. dowithline(finalline)
  485. filepositiontext = ''
  486. fin.close()
  487. if istop:
  488. dowithline('', 1)
  489. else:
  490. gotnextfile, filepositiontext, currentfilename, sourcecodeform, strictf77,\
  491. beginpattern, quiet, verbose, dolowercase = saveglobals
  492. # Crack line
  493. beforethisafter = r'\s*(?P<before>%s(?=\s*(\b(%s)\b)))' + \
  494. r'\s*(?P<this>(\b(%s)\b))' + \
  495. r'\s*(?P<after>%s)\s*\Z'
  496. ##
  497. fortrantypes = r'character|logical|integer|real|complex|double\s*(precision\s*(complex|)|complex)|type(?=\s*\([\w\s,=(*)]*\))|byte'
  498. typespattern = re.compile(
  499. beforethisafter % ('', fortrantypes, fortrantypes, '.*'), re.I), 'type'
  500. typespattern4implicit = re.compile(beforethisafter % (
  501. '', fortrantypes + '|static|automatic|undefined', fortrantypes + '|static|automatic|undefined', '.*'), re.I)
  502. #
  503. functionpattern = re.compile(beforethisafter % (
  504. r'([a-z]+[\w\s(=*+-/)]*?|)', 'function', 'function', '.*'), re.I), 'begin'
  505. subroutinepattern = re.compile(beforethisafter % (
  506. r'[a-z\s]*?', 'subroutine', 'subroutine', '.*'), re.I), 'begin'
  507. # modulepattern=re.compile(beforethisafter%('[a-z\s]*?','module','module','.*'),re.I),'begin'
  508. #
  509. groupbegins77 = r'program|block\s*data'
  510. beginpattern77 = re.compile(
  511. beforethisafter % ('', groupbegins77, groupbegins77, '.*'), re.I), 'begin'
  512. groupbegins90 = groupbegins77 + \
  513. r'|module(?!\s*procedure)|python\s*module|interface|type(?!\s*\()'
  514. beginpattern90 = re.compile(
  515. beforethisafter % ('', groupbegins90, groupbegins90, '.*'), re.I), 'begin'
  516. groupends = (r'end|endprogram|endblockdata|endmodule|endpythonmodule|'
  517. r'endinterface|endsubroutine|endfunction')
  518. endpattern = re.compile(
  519. beforethisafter % ('', groupends, groupends, r'[\w\s]*'), re.I), 'end'
  520. # endifs='end\s*(if|do|where|select|while|forall)'
  521. endifs = r'(end\s*(if|do|where|select|while|forall))|(module\s*procedure)'
  522. endifpattern = re.compile(
  523. beforethisafter % (r'[\w]*?', endifs, endifs, r'[\w\s]*'), re.I), 'endif'
  524. #
  525. implicitpattern = re.compile(
  526. beforethisafter % ('', 'implicit', 'implicit', '.*'), re.I), 'implicit'
  527. dimensionpattern = re.compile(beforethisafter % (
  528. '', 'dimension|virtual', 'dimension|virtual', '.*'), re.I), 'dimension'
  529. externalpattern = re.compile(
  530. beforethisafter % ('', 'external', 'external', '.*'), re.I), 'external'
  531. optionalpattern = re.compile(
  532. beforethisafter % ('', 'optional', 'optional', '.*'), re.I), 'optional'
  533. requiredpattern = re.compile(
  534. beforethisafter % ('', 'required', 'required', '.*'), re.I), 'required'
  535. publicpattern = re.compile(
  536. beforethisafter % ('', 'public', 'public', '.*'), re.I), 'public'
  537. privatepattern = re.compile(
  538. beforethisafter % ('', 'private', 'private', '.*'), re.I), 'private'
  539. intrinsicpattern = re.compile(
  540. beforethisafter % ('', 'intrinsic', 'intrinsic', '.*'), re.I), 'intrinsic'
  541. intentpattern = re.compile(beforethisafter % (
  542. '', 'intent|depend|note|check', 'intent|depend|note|check', r'\s*\(.*?\).*'), re.I), 'intent'
  543. parameterpattern = re.compile(
  544. beforethisafter % ('', 'parameter', 'parameter', r'\s*\(.*'), re.I), 'parameter'
  545. datapattern = re.compile(
  546. beforethisafter % ('', 'data', 'data', '.*'), re.I), 'data'
  547. callpattern = re.compile(
  548. beforethisafter % ('', 'call', 'call', '.*'), re.I), 'call'
  549. entrypattern = re.compile(
  550. beforethisafter % ('', 'entry', 'entry', '.*'), re.I), 'entry'
  551. callfunpattern = re.compile(
  552. beforethisafter % ('', 'callfun', 'callfun', '.*'), re.I), 'callfun'
  553. commonpattern = re.compile(
  554. beforethisafter % ('', 'common', 'common', '.*'), re.I), 'common'
  555. usepattern = re.compile(
  556. beforethisafter % ('', 'use', 'use', '.*'), re.I), 'use'
  557. containspattern = re.compile(
  558. beforethisafter % ('', 'contains', 'contains', ''), re.I), 'contains'
  559. formatpattern = re.compile(
  560. beforethisafter % ('', 'format', 'format', '.*'), re.I), 'format'
  561. # Non-fortran and f2py-specific statements
  562. f2pyenhancementspattern = re.compile(beforethisafter % ('', 'threadsafe|fortranname|callstatement|callprotoargument|usercode|pymethoddef',
  563. 'threadsafe|fortranname|callstatement|callprotoargument|usercode|pymethoddef', '.*'), re.I | re.S), 'f2pyenhancements'
  564. multilinepattern = re.compile(
  565. r"\s*(?P<before>''')(?P<this>.*?)(?P<after>''')\s*\Z", re.S), 'multiline'
  566. ##
  567. def split_by_unquoted(line, characters):
  568. """
  569. Splits the line into (line[:i], line[i:]),
  570. where i is the index of first occurrence of one of the characters
  571. not within quotes, or len(line) if no such index exists
  572. """
  573. assert not (set('"\'') & set(characters)), "cannot split by unquoted quotes"
  574. r = re.compile(
  575. r"\A(?P<before>({single_quoted}|{double_quoted}|{not_quoted})*)"
  576. r"(?P<after>{char}.*)\Z".format(
  577. not_quoted="[^\"'{}]".format(re.escape(characters)),
  578. char="[{}]".format(re.escape(characters)),
  579. single_quoted=r"('([^'\\]|(\\.))*')",
  580. double_quoted=r'("([^"\\]|(\\.))*")'))
  581. m = r.match(line)
  582. if m:
  583. d = m.groupdict()
  584. return (d["before"], d["after"])
  585. return (line, "")
  586. def _simplifyargs(argsline):
  587. a = []
  588. for n in markoutercomma(argsline).split('@,@'):
  589. for r in '(),':
  590. n = n.replace(r, '_')
  591. a.append(n)
  592. return ','.join(a)
  593. crackline_re_1 = re.compile(r'\s*(?P<result>\b[a-z]+[\w]*\b)\s*[=].*', re.I)
  594. def crackline(line, reset=0):
  595. """
  596. reset=-1 --- initialize
  597. reset=0 --- crack the line
  598. reset=1 --- final check if mismatch of blocks occurred
  599. Cracked data is saved in grouplist[0].
  600. """
  601. global beginpattern, groupcounter, groupname, groupcache, grouplist
  602. global filepositiontext, currentfilename, neededmodule, expectbegin
  603. global skipblocksuntil, skipemptyends, previous_context, gotnextfile
  604. _, has_semicolon = split_by_unquoted(line, ";")
  605. if has_semicolon and not (f2pyenhancementspattern[0].match(line) or
  606. multilinepattern[0].match(line)):
  607. # XXX: non-zero reset values need testing
  608. assert reset == 0, repr(reset)
  609. # split line on unquoted semicolons
  610. line, semicolon_line = split_by_unquoted(line, ";")
  611. while semicolon_line:
  612. crackline(line, reset)
  613. line, semicolon_line = split_by_unquoted(semicolon_line[1:], ";")
  614. crackline(line, reset)
  615. return
  616. if reset < 0:
  617. groupcounter = 0
  618. groupname = {groupcounter: ''}
  619. groupcache = {groupcounter: {}}
  620. grouplist = {groupcounter: []}
  621. groupcache[groupcounter]['body'] = []
  622. groupcache[groupcounter]['vars'] = {}
  623. groupcache[groupcounter]['block'] = ''
  624. groupcache[groupcounter]['name'] = ''
  625. neededmodule = -1
  626. skipblocksuntil = -1
  627. return
  628. if reset > 0:
  629. fl = 0
  630. if f77modulename and neededmodule == groupcounter:
  631. fl = 2
  632. while groupcounter > fl:
  633. outmess('crackline: groupcounter=%s groupname=%s\n' %
  634. (repr(groupcounter), repr(groupname)))
  635. outmess(
  636. 'crackline: Mismatch of blocks encountered. Trying to fix it by assuming "end" statement.\n')
  637. grouplist[groupcounter - 1].append(groupcache[groupcounter])
  638. grouplist[groupcounter - 1][-1]['body'] = grouplist[groupcounter]
  639. del grouplist[groupcounter]
  640. groupcounter = groupcounter - 1
  641. if f77modulename and neededmodule == groupcounter:
  642. grouplist[groupcounter - 1].append(groupcache[groupcounter])
  643. grouplist[groupcounter - 1][-1]['body'] = grouplist[groupcounter]
  644. del grouplist[groupcounter]
  645. groupcounter = groupcounter - 1 # end interface
  646. grouplist[groupcounter - 1].append(groupcache[groupcounter])
  647. grouplist[groupcounter - 1][-1]['body'] = grouplist[groupcounter]
  648. del grouplist[groupcounter]
  649. groupcounter = groupcounter - 1 # end module
  650. neededmodule = -1
  651. return
  652. if line == '':
  653. return
  654. flag = 0
  655. for pat in [dimensionpattern, externalpattern, intentpattern, optionalpattern,
  656. requiredpattern,
  657. parameterpattern, datapattern, publicpattern, privatepattern,
  658. intrinsicpattern,
  659. endifpattern, endpattern,
  660. formatpattern,
  661. beginpattern, functionpattern, subroutinepattern,
  662. implicitpattern, typespattern, commonpattern,
  663. callpattern, usepattern, containspattern,
  664. entrypattern,
  665. f2pyenhancementspattern,
  666. multilinepattern
  667. ]:
  668. m = pat[0].match(line)
  669. if m:
  670. break
  671. flag = flag + 1
  672. if not m:
  673. re_1 = crackline_re_1
  674. if 0 <= skipblocksuntil <= groupcounter:
  675. return
  676. if 'externals' in groupcache[groupcounter]:
  677. for name in groupcache[groupcounter]['externals']:
  678. if name in invbadnames:
  679. name = invbadnames[name]
  680. if 'interfaced' in groupcache[groupcounter] and name in groupcache[groupcounter]['interfaced']:
  681. continue
  682. m1 = re.match(
  683. r'(?P<before>[^"]*)\b%s\b\s*@\(@(?P<args>[^@]*)@\)@.*\Z' % name, markouterparen(line), re.I)
  684. if m1:
  685. m2 = re_1.match(m1.group('before'))
  686. a = _simplifyargs(m1.group('args'))
  687. if m2:
  688. line = 'callfun %s(%s) result (%s)' % (
  689. name, a, m2.group('result'))
  690. else:
  691. line = 'callfun %s(%s)' % (name, a)
  692. m = callfunpattern[0].match(line)
  693. if not m:
  694. outmess(
  695. 'crackline: could not resolve function call for line=%s.\n' % repr(line))
  696. return
  697. analyzeline(m, 'callfun', line)
  698. return
  699. if verbose > 1 or (verbose == 1 and currentfilename.lower().endswith('.pyf')):
  700. previous_context = None
  701. outmess('crackline:%d: No pattern for line\n' % (groupcounter))
  702. return
  703. elif pat[1] == 'end':
  704. if 0 <= skipblocksuntil < groupcounter:
  705. groupcounter = groupcounter - 1
  706. if skipblocksuntil <= groupcounter:
  707. return
  708. if groupcounter <= 0:
  709. raise Exception('crackline: groupcounter(=%s) is nonpositive. '
  710. 'Check the blocks.'
  711. % (groupcounter))
  712. m1 = beginpattern[0].match((line))
  713. if (m1) and (not m1.group('this') == groupname[groupcounter]):
  714. raise Exception('crackline: End group %s does not match with '
  715. 'previous Begin group %s\n\t%s' %
  716. (repr(m1.group('this')), repr(groupname[groupcounter]),
  717. filepositiontext)
  718. )
  719. if skipblocksuntil == groupcounter:
  720. skipblocksuntil = -1
  721. grouplist[groupcounter - 1].append(groupcache[groupcounter])
  722. grouplist[groupcounter - 1][-1]['body'] = grouplist[groupcounter]
  723. del grouplist[groupcounter]
  724. groupcounter = groupcounter - 1
  725. if not skipemptyends:
  726. expectbegin = 1
  727. elif pat[1] == 'begin':
  728. if 0 <= skipblocksuntil <= groupcounter:
  729. groupcounter = groupcounter + 1
  730. return
  731. gotnextfile = 0
  732. analyzeline(m, pat[1], line)
  733. expectbegin = 0
  734. elif pat[1] == 'endif':
  735. pass
  736. elif pat[1] == 'contains':
  737. if ignorecontains:
  738. return
  739. if 0 <= skipblocksuntil <= groupcounter:
  740. return
  741. skipblocksuntil = groupcounter
  742. else:
  743. if 0 <= skipblocksuntil <= groupcounter:
  744. return
  745. analyzeline(m, pat[1], line)
  746. def markouterparen(line):
  747. l = ''
  748. f = 0
  749. for c in line:
  750. if c == '(':
  751. f = f + 1
  752. if f == 1:
  753. l = l + '@(@'
  754. continue
  755. elif c == ')':
  756. f = f - 1
  757. if f == 0:
  758. l = l + '@)@'
  759. continue
  760. l = l + c
  761. return l
  762. def markoutercomma(line, comma=','):
  763. l = ''
  764. f = 0
  765. before, after = split_by_unquoted(line, comma + '()')
  766. l += before
  767. while after:
  768. if (after[0] == comma) and (f == 0):
  769. l += '@' + comma + '@'
  770. else:
  771. l += after[0]
  772. if after[0] == '(':
  773. f += 1
  774. elif after[0] == ')':
  775. f -= 1
  776. before, after = split_by_unquoted(after[1:], comma + '()')
  777. l += before
  778. assert not f, repr((f, line, l))
  779. return l
  780. def unmarkouterparen(line):
  781. r = line.replace('@(@', '(').replace('@)@', ')')
  782. return r
  783. def appenddecl(decl, decl2, force=1):
  784. if not decl:
  785. decl = {}
  786. if not decl2:
  787. return decl
  788. if decl is decl2:
  789. return decl
  790. for k in list(decl2.keys()):
  791. if k == 'typespec':
  792. if force or k not in decl:
  793. decl[k] = decl2[k]
  794. elif k == 'attrspec':
  795. for l in decl2[k]:
  796. decl = setattrspec(decl, l, force)
  797. elif k == 'kindselector':
  798. decl = setkindselector(decl, decl2[k], force)
  799. elif k == 'charselector':
  800. decl = setcharselector(decl, decl2[k], force)
  801. elif k in ['=', 'typename']:
  802. if force or k not in decl:
  803. decl[k] = decl2[k]
  804. elif k == 'note':
  805. pass
  806. elif k in ['intent', 'check', 'dimension', 'optional', 'required']:
  807. errmess('appenddecl: "%s" not implemented.\n' % k)
  808. else:
  809. raise Exception('appenddecl: Unknown variable definition key:' +
  810. str(k))
  811. return decl
  812. selectpattern = re.compile(
  813. r'\s*(?P<this>(@\(@.*?@\)@|[*][\d*]+|[*]\s*@\(@.*?@\)@|))(?P<after>.*)\Z', re.I)
  814. nameargspattern = re.compile(
  815. r'\s*(?P<name>\b[\w$]+\b)\s*(@\(@\s*(?P<args>[\w\s,]*)\s*@\)@|)\s*((result(\s*@\(@\s*(?P<result>\b[\w$]+\b)\s*@\)@|))|(bind\s*@\(@\s*(?P<bind>.*)\s*@\)@))*\s*\Z', re.I)
  816. callnameargspattern = re.compile(
  817. r'\s*(?P<name>\b[\w$]+\b)\s*@\(@\s*(?P<args>.*)\s*@\)@\s*\Z', re.I)
  818. real16pattern = re.compile(
  819. r'([-+]?(?:\d+(?:\.\d*)?|\d*\.\d+))[dD]((?:[-+]?\d+)?)')
  820. real8pattern = re.compile(
  821. r'([-+]?((?:\d+(?:\.\d*)?|\d*\.\d+))[eE]((?:[-+]?\d+)?)|(\d+\.\d*))')
  822. _intentcallbackpattern = re.compile(r'intent\s*\(.*?\bcallback\b', re.I)
  823. def _is_intent_callback(vdecl):
  824. for a in vdecl.get('attrspec', []):
  825. if _intentcallbackpattern.match(a):
  826. return 1
  827. return 0
  828. def _resolvenameargspattern(line):
  829. line = markouterparen(line)
  830. m1 = nameargspattern.match(line)
  831. if m1:
  832. return m1.group('name'), m1.group('args'), m1.group('result'), m1.group('bind')
  833. m1 = callnameargspattern.match(line)
  834. if m1:
  835. return m1.group('name'), m1.group('args'), None, None
  836. return None, [], None, None
  837. def analyzeline(m, case, line):
  838. global groupcounter, groupname, groupcache, grouplist, filepositiontext
  839. global currentfilename, f77modulename, neededinterface, neededmodule
  840. global expectbegin, gotnextfile, previous_context
  841. block = m.group('this')
  842. if case != 'multiline':
  843. previous_context = None
  844. if expectbegin and case not in ['begin', 'call', 'callfun', 'type'] \
  845. and not skipemptyends and groupcounter < 1:
  846. newname = os.path.basename(currentfilename).split('.')[0]
  847. outmess(
  848. 'analyzeline: no group yet. Creating program group with name "%s".\n' % newname)
  849. gotnextfile = 0
  850. groupcounter = groupcounter + 1
  851. groupname[groupcounter] = 'program'
  852. groupcache[groupcounter] = {}
  853. grouplist[groupcounter] = []
  854. groupcache[groupcounter]['body'] = []
  855. groupcache[groupcounter]['vars'] = {}
  856. groupcache[groupcounter]['block'] = 'program'
  857. groupcache[groupcounter]['name'] = newname
  858. groupcache[groupcounter]['from'] = 'fromsky'
  859. expectbegin = 0
  860. if case in ['begin', 'call', 'callfun']:
  861. # Crack line => block,name,args,result
  862. block = block.lower()
  863. if re.match(r'block\s*data', block, re.I):
  864. block = 'block data'
  865. if re.match(r'python\s*module', block, re.I):
  866. block = 'python module'
  867. name, args, result, bind = _resolvenameargspattern(m.group('after'))
  868. if name is None:
  869. if block == 'block data':
  870. name = '_BLOCK_DATA_'
  871. else:
  872. name = ''
  873. if block not in ['interface', 'block data']:
  874. outmess('analyzeline: No name/args pattern found for line.\n')
  875. previous_context = (block, name, groupcounter)
  876. if args:
  877. args = rmbadname([x.strip()
  878. for x in markoutercomma(args).split('@,@')])
  879. else:
  880. args = []
  881. if '' in args:
  882. while '' in args:
  883. args.remove('')
  884. outmess(
  885. 'analyzeline: argument list is malformed (missing argument).\n')
  886. # end of crack line => block,name,args,result
  887. needmodule = 0
  888. needinterface = 0
  889. if case in ['call', 'callfun']:
  890. needinterface = 1
  891. if 'args' not in groupcache[groupcounter]:
  892. return
  893. if name not in groupcache[groupcounter]['args']:
  894. return
  895. for it in grouplist[groupcounter]:
  896. if it['name'] == name:
  897. return
  898. if name in groupcache[groupcounter]['interfaced']:
  899. return
  900. block = {'call': 'subroutine', 'callfun': 'function'}[case]
  901. if f77modulename and neededmodule == -1 and groupcounter <= 1:
  902. neededmodule = groupcounter + 2
  903. needmodule = 1
  904. if block != 'interface':
  905. needinterface = 1
  906. # Create new block(s)
  907. groupcounter = groupcounter + 1
  908. groupcache[groupcounter] = {}
  909. grouplist[groupcounter] = []
  910. if needmodule:
  911. if verbose > 1:
  912. outmess('analyzeline: Creating module block %s\n' %
  913. repr(f77modulename), 0)
  914. groupname[groupcounter] = 'module'
  915. groupcache[groupcounter]['block'] = 'python module'
  916. groupcache[groupcounter]['name'] = f77modulename
  917. groupcache[groupcounter]['from'] = ''
  918. groupcache[groupcounter]['body'] = []
  919. groupcache[groupcounter]['externals'] = []
  920. groupcache[groupcounter]['interfaced'] = []
  921. groupcache[groupcounter]['vars'] = {}
  922. groupcounter = groupcounter + 1
  923. groupcache[groupcounter] = {}
  924. grouplist[groupcounter] = []
  925. if needinterface:
  926. if verbose > 1:
  927. outmess('analyzeline: Creating additional interface block (groupcounter=%s).\n' % (
  928. groupcounter), 0)
  929. groupname[groupcounter] = 'interface'
  930. groupcache[groupcounter]['block'] = 'interface'
  931. groupcache[groupcounter]['name'] = 'unknown_interface'
  932. groupcache[groupcounter]['from'] = '%s:%s' % (
  933. groupcache[groupcounter - 1]['from'], groupcache[groupcounter - 1]['name'])
  934. groupcache[groupcounter]['body'] = []
  935. groupcache[groupcounter]['externals'] = []
  936. groupcache[groupcounter]['interfaced'] = []
  937. groupcache[groupcounter]['vars'] = {}
  938. groupcounter = groupcounter + 1
  939. groupcache[groupcounter] = {}
  940. grouplist[groupcounter] = []
  941. groupname[groupcounter] = block
  942. groupcache[groupcounter]['block'] = block
  943. if not name:
  944. name = 'unknown_' + block
  945. groupcache[groupcounter]['prefix'] = m.group('before')
  946. groupcache[groupcounter]['name'] = rmbadname1(name)
  947. groupcache[groupcounter]['result'] = result
  948. if groupcounter == 1:
  949. groupcache[groupcounter]['from'] = currentfilename
  950. else:
  951. if f77modulename and groupcounter == 3:
  952. groupcache[groupcounter]['from'] = '%s:%s' % (
  953. groupcache[groupcounter - 1]['from'], currentfilename)
  954. else:
  955. groupcache[groupcounter]['from'] = '%s:%s' % (
  956. groupcache[groupcounter - 1]['from'], groupcache[groupcounter - 1]['name'])
  957. for k in list(groupcache[groupcounter].keys()):
  958. if not groupcache[groupcounter][k]:
  959. del groupcache[groupcounter][k]
  960. groupcache[groupcounter]['args'] = args
  961. groupcache[groupcounter]['body'] = []
  962. groupcache[groupcounter]['externals'] = []
  963. groupcache[groupcounter]['interfaced'] = []
  964. groupcache[groupcounter]['vars'] = {}
  965. groupcache[groupcounter]['entry'] = {}
  966. # end of creation
  967. if block == 'type':
  968. groupcache[groupcounter]['varnames'] = []
  969. if case in ['call', 'callfun']: # set parents variables
  970. if name not in groupcache[groupcounter - 2]['externals']:
  971. groupcache[groupcounter - 2]['externals'].append(name)
  972. groupcache[groupcounter]['vars'] = copy.deepcopy(
  973. groupcache[groupcounter - 2]['vars'])
  974. try:
  975. del groupcache[groupcounter]['vars'][name][
  976. groupcache[groupcounter]['vars'][name]['attrspec'].index('external')]
  977. except Exception:
  978. pass
  979. if block in ['function', 'subroutine']: # set global attributes
  980. try:
  981. groupcache[groupcounter]['vars'][name] = appenddecl(
  982. groupcache[groupcounter]['vars'][name], groupcache[groupcounter - 2]['vars'][''])
  983. except Exception:
  984. pass
  985. if case == 'callfun': # return type
  986. if result and result in groupcache[groupcounter]['vars']:
  987. if not name == result:
  988. groupcache[groupcounter]['vars'][name] = appenddecl(
  989. groupcache[groupcounter]['vars'][name], groupcache[groupcounter]['vars'][result])
  990. # if groupcounter>1: # name is interfaced
  991. try:
  992. groupcache[groupcounter - 2]['interfaced'].append(name)
  993. except Exception:
  994. pass
  995. if block == 'function':
  996. t = typespattern[0].match(m.group('before') + ' ' + name)
  997. if t:
  998. typespec, selector, attr, edecl = cracktypespec0(
  999. t.group('this'), t.group('after'))
  1000. updatevars(typespec, selector, attr, edecl)
  1001. if case in ['call', 'callfun']:
  1002. grouplist[groupcounter - 1].append(groupcache[groupcounter])
  1003. grouplist[groupcounter - 1][-1]['body'] = grouplist[groupcounter]
  1004. del grouplist[groupcounter]
  1005. groupcounter = groupcounter - 1 # end routine
  1006. grouplist[groupcounter - 1].append(groupcache[groupcounter])
  1007. grouplist[groupcounter - 1][-1]['body'] = grouplist[groupcounter]
  1008. del grouplist[groupcounter]
  1009. groupcounter = groupcounter - 1 # end interface
  1010. elif case == 'entry':
  1011. name, args, result, bind = _resolvenameargspattern(m.group('after'))
  1012. if name is not None:
  1013. if args:
  1014. args = rmbadname([x.strip()
  1015. for x in markoutercomma(args).split('@,@')])
  1016. else:
  1017. args = []
  1018. assert result is None, repr(result)
  1019. groupcache[groupcounter]['entry'][name] = args
  1020. previous_context = ('entry', name, groupcounter)
  1021. elif case == 'type':
  1022. typespec, selector, attr, edecl = cracktypespec0(
  1023. block, m.group('after'))
  1024. last_name = updatevars(typespec, selector, attr, edecl)
  1025. if last_name is not None:
  1026. previous_context = ('variable', last_name, groupcounter)
  1027. elif case in ['dimension', 'intent', 'optional', 'required', 'external', 'public', 'private', 'intrinsic']:
  1028. edecl = groupcache[groupcounter]['vars']
  1029. ll = m.group('after').strip()
  1030. i = ll.find('::')
  1031. if i < 0 and case == 'intent':
  1032. i = markouterparen(ll).find('@)@') - 2
  1033. ll = ll[:i + 1] + '::' + ll[i + 1:]
  1034. i = ll.find('::')
  1035. if ll[i:] == '::' and 'args' in groupcache[groupcounter]:
  1036. outmess('All arguments will have attribute %s%s\n' %
  1037. (m.group('this'), ll[:i]))
  1038. ll = ll + ','.join(groupcache[groupcounter]['args'])
  1039. if i < 0:
  1040. i = 0
  1041. pl = ''
  1042. else:
  1043. pl = ll[:i].strip()
  1044. ll = ll[i + 2:]
  1045. ch = markoutercomma(pl).split('@,@')
  1046. if len(ch) > 1:
  1047. pl = ch[0]
  1048. outmess('analyzeline: cannot handle multiple attributes without type specification. Ignoring %r.\n' % (
  1049. ','.join(ch[1:])))
  1050. last_name = None
  1051. for e in [x.strip() for x in markoutercomma(ll).split('@,@')]:
  1052. m1 = namepattern.match(e)
  1053. if not m1:
  1054. if case in ['public', 'private']:
  1055. k = ''
  1056. else:
  1057. print(m.groupdict())
  1058. outmess('analyzeline: no name pattern found in %s statement for %s. Skipping.\n' % (
  1059. case, repr(e)))
  1060. continue
  1061. else:
  1062. k = rmbadname1(m1.group('name'))
  1063. if k not in edecl:
  1064. edecl[k] = {}
  1065. if case == 'dimension':
  1066. ap = case + m1.group('after')
  1067. if case == 'intent':
  1068. ap = m.group('this') + pl
  1069. if _intentcallbackpattern.match(ap):
  1070. if k not in groupcache[groupcounter]['args']:
  1071. if groupcounter > 1:
  1072. if '__user__' not in groupcache[groupcounter - 2]['name']:
  1073. outmess(
  1074. 'analyzeline: missing __user__ module (could be nothing)\n')
  1075. # fixes ticket 1693
  1076. if k != groupcache[groupcounter]['name']:
  1077. outmess('analyzeline: appending intent(callback) %s'
  1078. ' to %s arguments\n' % (k, groupcache[groupcounter]['name']))
  1079. groupcache[groupcounter]['args'].append(k)
  1080. else:
  1081. errmess(
  1082. 'analyzeline: intent(callback) %s is ignored' % (k))
  1083. else:
  1084. errmess('analyzeline: intent(callback) %s is already'
  1085. ' in argument list' % (k))
  1086. if case in ['optional', 'required', 'public', 'external', 'private', 'intrinsic']:
  1087. ap = case
  1088. if 'attrspec' in edecl[k]:
  1089. edecl[k]['attrspec'].append(ap)
  1090. else:
  1091. edecl[k]['attrspec'] = [ap]
  1092. if case == 'external':
  1093. if groupcache[groupcounter]['block'] == 'program':
  1094. outmess('analyzeline: ignoring program arguments\n')
  1095. continue
  1096. if k not in groupcache[groupcounter]['args']:
  1097. continue
  1098. if 'externals' not in groupcache[groupcounter]:
  1099. groupcache[groupcounter]['externals'] = []
  1100. groupcache[groupcounter]['externals'].append(k)
  1101. last_name = k
  1102. groupcache[groupcounter]['vars'] = edecl
  1103. if last_name is not None:
  1104. previous_context = ('variable', last_name, groupcounter)
  1105. elif case == 'parameter':
  1106. edecl = groupcache[groupcounter]['vars']
  1107. ll = m.group('after').strip()[1:-1]
  1108. last_name = None
  1109. for e in markoutercomma(ll).split('@,@'):
  1110. try:
  1111. k, initexpr = [x.strip() for x in e.split('=')]
  1112. except Exception:
  1113. outmess(
  1114. 'analyzeline: could not extract name,expr in parameter statement "%s" of "%s"\n' % (e, ll))
  1115. continue
  1116. params = get_parameters(edecl)
  1117. k = rmbadname1(k)
  1118. if k not in edecl:
  1119. edecl[k] = {}
  1120. if '=' in edecl[k] and (not edecl[k]['='] == initexpr):
  1121. outmess('analyzeline: Overwriting the value of parameter "%s" ("%s") with "%s".\n' % (
  1122. k, edecl[k]['='], initexpr))
  1123. t = determineexprtype(initexpr, params)
  1124. if t:
  1125. if t.get('typespec') == 'real':
  1126. tt = list(initexpr)
  1127. for m in real16pattern.finditer(initexpr):
  1128. tt[m.start():m.end()] = list(
  1129. initexpr[m.start():m.end()].lower().replace('d', 'e'))
  1130. initexpr = ''.join(tt)
  1131. elif t.get('typespec') == 'complex':
  1132. initexpr = initexpr[1:].lower().replace('d', 'e').\
  1133. replace(',', '+1j*(')
  1134. try:
  1135. v = eval(initexpr, {}, params)
  1136. except (SyntaxError, NameError, TypeError) as msg:
  1137. errmess('analyzeline: Failed to evaluate %r. Ignoring: %s\n'
  1138. % (initexpr, msg))
  1139. continue
  1140. edecl[k]['='] = repr(v)
  1141. if 'attrspec' in edecl[k]:
  1142. edecl[k]['attrspec'].append('parameter')
  1143. else:
  1144. edecl[k]['attrspec'] = ['parameter']
  1145. last_name = k
  1146. groupcache[groupcounter]['vars'] = edecl
  1147. if last_name is not None:
  1148. previous_context = ('variable', last_name, groupcounter)
  1149. elif case == 'implicit':
  1150. if m.group('after').strip().lower() == 'none':
  1151. groupcache[groupcounter]['implicit'] = None
  1152. elif m.group('after'):
  1153. if 'implicit' in groupcache[groupcounter]:
  1154. impl = groupcache[groupcounter]['implicit']
  1155. else:
  1156. impl = {}
  1157. if impl is None:
  1158. outmess(
  1159. 'analyzeline: Overwriting earlier "implicit none" statement.\n')
  1160. impl = {}
  1161. for e in markoutercomma(m.group('after')).split('@,@'):
  1162. decl = {}
  1163. m1 = re.match(
  1164. r'\s*(?P<this>.*?)\s*(\(\s*(?P<after>[a-z-, ]+)\s*\)\s*|)\Z', e, re.I)
  1165. if not m1:
  1166. outmess(
  1167. 'analyzeline: could not extract info of implicit statement part "%s"\n' % (e))
  1168. continue
  1169. m2 = typespattern4implicit.match(m1.group('this'))
  1170. if not m2:
  1171. outmess(
  1172. 'analyzeline: could not extract types pattern of implicit statement part "%s"\n' % (e))
  1173. continue
  1174. typespec, selector, attr, edecl = cracktypespec0(
  1175. m2.group('this'), m2.group('after'))
  1176. kindselect, charselect, typename = cracktypespec(
  1177. typespec, selector)
  1178. decl['typespec'] = typespec
  1179. decl['kindselector'] = kindselect
  1180. decl['charselector'] = charselect
  1181. decl['typename'] = typename
  1182. for k in list(decl.keys()):
  1183. if not decl[k]:
  1184. del decl[k]
  1185. for r in markoutercomma(m1.group('after')).split('@,@'):
  1186. if '-' in r:
  1187. try:
  1188. begc, endc = [x.strip() for x in r.split('-')]
  1189. except Exception:
  1190. outmess(
  1191. 'analyzeline: expected "<char>-<char>" instead of "%s" in range list of implicit statement\n' % r)
  1192. continue
  1193. else:
  1194. begc = endc = r.strip()
  1195. if not len(begc) == len(endc) == 1:
  1196. outmess(
  1197. 'analyzeline: expected "<char>-<char>" instead of "%s" in range list of implicit statement (2)\n' % r)
  1198. continue
  1199. for o in range(ord(begc), ord(endc) + 1):
  1200. impl[chr(o)] = decl
  1201. groupcache[groupcounter]['implicit'] = impl
  1202. elif case == 'data':
  1203. ll = []
  1204. dl = ''
  1205. il = ''
  1206. f = 0
  1207. fc = 1
  1208. inp = 0
  1209. for c in m.group('after'):
  1210. if not inp:
  1211. if c == "'":
  1212. fc = not fc
  1213. if c == '/' and fc:
  1214. f = f + 1
  1215. continue
  1216. if c == '(':
  1217. inp = inp + 1
  1218. elif c == ')':
  1219. inp = inp - 1
  1220. if f == 0:
  1221. dl = dl + c
  1222. elif f == 1:
  1223. il = il + c
  1224. elif f == 2:
  1225. dl = dl.strip()
  1226. if dl.startswith(','):
  1227. dl = dl[1:].strip()
  1228. ll.append([dl, il])
  1229. dl = c
  1230. il = ''
  1231. f = 0
  1232. if f == 2:
  1233. dl = dl.strip()
  1234. if dl.startswith(','):
  1235. dl = dl[1:].strip()
  1236. ll.append([dl, il])
  1237. vars = {}
  1238. if 'vars' in groupcache[groupcounter]:
  1239. vars = groupcache[groupcounter]['vars']
  1240. last_name = None
  1241. for l in ll:
  1242. l = [x.strip() for x in l]
  1243. if l[0][0] == ',':
  1244. l[0] = l[0][1:]
  1245. if l[0][0] == '(':
  1246. outmess(
  1247. 'analyzeline: implied-DO list "%s" is not supported. Skipping.\n' % l[0])
  1248. continue
  1249. i = 0
  1250. j = 0
  1251. llen = len(l[1])
  1252. for v in rmbadname([x.strip() for x in markoutercomma(l[0]).split('@,@')]):
  1253. if v[0] == '(':
  1254. outmess(
  1255. 'analyzeline: implied-DO list "%s" is not supported. Skipping.\n' % v)
  1256. # XXX: subsequent init expressions may get wrong values.
  1257. # Ignoring since data statements are irrelevant for
  1258. # wrapping.
  1259. continue
  1260. fc = 0
  1261. while (i < llen) and (fc or not l[1][i] == ','):
  1262. if l[1][i] == "'":
  1263. fc = not fc
  1264. i = i + 1
  1265. i = i + 1
  1266. if v not in vars:
  1267. vars[v] = {}
  1268. if '=' in vars[v] and not vars[v]['='] == l[1][j:i - 1]:
  1269. outmess('analyzeline: changing init expression of "%s" ("%s") to "%s"\n' % (
  1270. v, vars[v]['='], l[1][j:i - 1]))
  1271. vars[v]['='] = l[1][j:i - 1]
  1272. j = i
  1273. last_name = v
  1274. groupcache[groupcounter]['vars'] = vars
  1275. if last_name is not None:
  1276. previous_context = ('variable', last_name, groupcounter)
  1277. elif case == 'common':
  1278. line = m.group('after').strip()
  1279. if not line[0] == '/':
  1280. line = '//' + line
  1281. cl = []
  1282. f = 0
  1283. bn = ''
  1284. ol = ''
  1285. for c in line:
  1286. if c == '/':
  1287. f = f + 1
  1288. continue
  1289. if f >= 3:
  1290. bn = bn.strip()
  1291. if not bn:
  1292. bn = '_BLNK_'
  1293. cl.append([bn, ol])
  1294. f = f - 2
  1295. bn = ''
  1296. ol = ''
  1297. if f % 2:
  1298. bn = bn + c
  1299. else:
  1300. ol = ol + c
  1301. bn = bn.strip()
  1302. if not bn:
  1303. bn = '_BLNK_'
  1304. cl.append([bn, ol])
  1305. commonkey = {}
  1306. if 'common' in groupcache[groupcounter]:
  1307. commonkey = groupcache[groupcounter]['common']
  1308. for c in cl:
  1309. if c[0] not in commonkey:
  1310. commonkey[c[0]] = []
  1311. for i in [x.strip() for x in markoutercomma(c[1]).split('@,@')]:
  1312. if i:
  1313. commonkey[c[0]].append(i)
  1314. groupcache[groupcounter]['common'] = commonkey
  1315. previous_context = ('common', bn, groupcounter)
  1316. elif case == 'use':
  1317. m1 = re.match(
  1318. r'\A\s*(?P<name>\b[\w]+\b)\s*((,(\s*\bonly\b\s*:|(?P<notonly>))\s*(?P<list>.*))|)\s*\Z', m.group('after'), re.I)
  1319. if m1:
  1320. mm = m1.groupdict()
  1321. if 'use' not in groupcache[groupcounter]:
  1322. groupcache[groupcounter]['use'] = {}
  1323. name = m1.group('name')
  1324. groupcache[groupcounter]['use'][name] = {}
  1325. isonly = 0
  1326. if 'list' in mm and mm['list'] is not None:
  1327. if 'notonly' in mm and mm['notonly'] is None:
  1328. isonly = 1
  1329. groupcache[groupcounter]['use'][name]['only'] = isonly
  1330. ll = [x.strip() for x in mm['list'].split(',')]
  1331. rl = {}
  1332. for l in ll:
  1333. if '=' in l:
  1334. m2 = re.match(
  1335. r'\A\s*(?P<local>\b[\w]+\b)\s*=\s*>\s*(?P<use>\b[\w]+\b)\s*\Z', l, re.I)
  1336. if m2:
  1337. rl[m2.group('local').strip()] = m2.group(
  1338. 'use').strip()
  1339. else:
  1340. outmess(
  1341. 'analyzeline: Not local=>use pattern found in %s\n' % repr(l))
  1342. else:
  1343. rl[l] = l
  1344. groupcache[groupcounter]['use'][name]['map'] = rl
  1345. else:
  1346. pass
  1347. else:
  1348. print(m.groupdict())
  1349. outmess('analyzeline: Could not crack the use statement.\n')
  1350. elif case in ['f2pyenhancements']:
  1351. if 'f2pyenhancements' not in groupcache[groupcounter]:
  1352. groupcache[groupcounter]['f2pyenhancements'] = {}
  1353. d = groupcache[groupcounter]['f2pyenhancements']
  1354. if m.group('this') == 'usercode' and 'usercode' in d:
  1355. if isinstance(d['usercode'], str):
  1356. d['usercode'] = [d['usercode']]
  1357. d['usercode'].append(m.group('after'))
  1358. else:
  1359. d[m.group('this')] = m.group('after')
  1360. elif case == 'multiline':
  1361. if previous_context is None:
  1362. if verbose:
  1363. outmess('analyzeline: No context for multiline block.\n')
  1364. return
  1365. gc = groupcounter
  1366. appendmultiline(groupcache[gc],
  1367. previous_context[:2],
  1368. m.group('this'))
  1369. else:
  1370. if verbose > 1:
  1371. print(m.groupdict())
  1372. outmess('analyzeline: No code implemented for line.\n')
  1373. def appendmultiline(group, context_name, ml):
  1374. if 'f2pymultilines' not in group:
  1375. group['f2pymultilines'] = {}
  1376. d = group['f2pymultilines']
  1377. if context_name not in d:
  1378. d[context_name] = []
  1379. d[context_name].append(ml)
  1380. return
  1381. def cracktypespec0(typespec, ll):
  1382. selector = None
  1383. attr = None
  1384. if re.match(r'double\s*complex', typespec, re.I):
  1385. typespec = 'double complex'
  1386. elif re.match(r'double\s*precision', typespec, re.I):
  1387. typespec = 'double precision'
  1388. else:
  1389. typespec = typespec.strip().lower()
  1390. m1 = selectpattern.match(markouterparen(ll))
  1391. if not m1:
  1392. outmess(
  1393. 'cracktypespec0: no kind/char_selector pattern found for line.\n')
  1394. return
  1395. d = m1.groupdict()
  1396. for k in list(d.keys()):
  1397. d[k] = unmarkouterparen(d[k])
  1398. if typespec in ['complex', 'integer', 'logical', 'real', 'character', 'type']:
  1399. selector = d['this']
  1400. ll = d['after']
  1401. i = ll.find('::')
  1402. if i >= 0:
  1403. attr = ll[:i].strip()
  1404. ll = ll[i + 2:]
  1405. return typespec, selector, attr, ll
  1406. #####
  1407. namepattern = re.compile(r'\s*(?P<name>\b[\w]+\b)\s*(?P<after>.*)\s*\Z', re.I)
  1408. kindselector = re.compile(
  1409. r'\s*(\(\s*(kind\s*=)?\s*(?P<kind>.*)\s*\)|[*]\s*(?P<kind2>.*?))\s*\Z', re.I)
  1410. charselector = re.compile(
  1411. r'\s*(\((?P<lenkind>.*)\)|[*]\s*(?P<charlen>.*))\s*\Z', re.I)
  1412. lenkindpattern = re.compile(
  1413. r'\s*(kind\s*=\s*(?P<kind>.*?)\s*(@,@\s*len\s*=\s*(?P<len>.*)|)|(len\s*=\s*|)(?P<len2>.*?)\s*(@,@\s*(kind\s*=\s*|)(?P<kind2>.*)|))\s*\Z', re.I)
  1414. lenarraypattern = re.compile(
  1415. r'\s*(@\(@\s*(?!/)\s*(?P<array>.*?)\s*@\)@\s*[*]\s*(?P<len>.*?)|([*]\s*(?P<len2>.*?)|)\s*(@\(@\s*(?!/)\s*(?P<array2>.*?)\s*@\)@|))\s*(=\s*(?P<init>.*?)|(@\(@|)/\s*(?P<init2>.*?)\s*/(@\)@|)|)\s*\Z', re.I)
  1416. def removespaces(expr):
  1417. expr = expr.strip()
  1418. if len(expr) <= 1:
  1419. return expr
  1420. expr2 = expr[0]
  1421. for i in range(1, len(expr) - 1):
  1422. if (expr[i] == ' ' and
  1423. ((expr[i + 1] in "()[]{}=+-/* ") or
  1424. (expr[i - 1] in "()[]{}=+-/* "))):
  1425. continue
  1426. expr2 = expr2 + expr[i]
  1427. expr2 = expr2 + expr[-1]
  1428. return expr2
  1429. def markinnerspaces(line):
  1430. l = ''
  1431. f = 0
  1432. cc = '\''
  1433. cb = ''
  1434. for c in line:
  1435. if cb == '\\' and c in ['\\', '\'', '"']:
  1436. l = l + c
  1437. cb = c
  1438. continue
  1439. if f == 0 and c in ['\'', '"']:
  1440. cc = c
  1441. if c == cc:
  1442. f = f + 1
  1443. elif c == cc:
  1444. f = f - 1
  1445. elif c == ' ' and f == 1:
  1446. l = l + '@_@'
  1447. continue
  1448. l = l + c
  1449. cb = c
  1450. return l
  1451. def updatevars(typespec, selector, attrspec, entitydecl):
  1452. global groupcache, groupcounter
  1453. last_name = None
  1454. kindselect, charselect, typename = cracktypespec(typespec, selector)
  1455. if attrspec:
  1456. attrspec = [x.strip() for x in markoutercomma(attrspec).split('@,@')]
  1457. l = []
  1458. c = re.compile(r'(?P<start>[a-zA-Z]+)')
  1459. for a in attrspec:
  1460. if not a:
  1461. continue
  1462. m = c.match(a)
  1463. if m:
  1464. s = m.group('start').lower()
  1465. a = s + a[len(s):]
  1466. l.append(a)
  1467. attrspec = l
  1468. el = [x.strip() for x in markoutercomma(entitydecl).split('@,@')]
  1469. el1 = []
  1470. for e in el:
  1471. for e1 in [x.strip() for x in markoutercomma(removespaces(markinnerspaces(e)), comma=' ').split('@ @')]:
  1472. if e1:
  1473. el1.append(e1.replace('@_@', ' '))
  1474. for e in el1:
  1475. m = namepattern.match(e)
  1476. if not m:
  1477. outmess(
  1478. 'updatevars: no name pattern found for entity=%s. Skipping.\n' % (repr(e)))
  1479. continue
  1480. ename = rmbadname1(m.group('name'))
  1481. edecl = {}
  1482. if ename in groupcache[groupcounter]['vars']:
  1483. edecl = groupcache[groupcounter]['vars'][ename].copy()
  1484. not_has_typespec = 'typespec' not in edecl
  1485. if not_has_typespec:
  1486. edecl['typespec'] = typespec
  1487. elif typespec and (not typespec == edecl['typespec']):
  1488. outmess('updatevars: attempt to change the type of "%s" ("%s") to "%s". Ignoring.\n' % (
  1489. ename, edecl['typespec'], typespec))
  1490. if 'kindselector' not in edecl:
  1491. edecl['kindselector'] = copy.copy(kindselect)
  1492. elif kindselect:
  1493. for k in list(kindselect.keys()):
  1494. if k in edecl['kindselector'] and (not kindselect[k] == edecl['kindselector'][k]):
  1495. outmess('updatevars: attempt to change the kindselector "%s" of "%s" ("%s") to "%s". Ignoring.\n' % (
  1496. k, ename, edecl['kindselector'][k], kindselect[k]))
  1497. else:
  1498. edecl['kindselector'][k] = copy.copy(kindselect[k])
  1499. if 'charselector' not in edecl and charselect:
  1500. if not_has_typespec:
  1501. edecl['charselector'] = charselect
  1502. else:
  1503. errmess('updatevars:%s: attempt to change empty charselector to %r. Ignoring.\n'
  1504. % (ename, charselect))
  1505. elif charselect:
  1506. for k in list(charselect.keys()):
  1507. if k in edecl['charselector'] and (not charselect[k] == edecl['charselector'][k]):
  1508. outmess('updatevars: attempt to change the charselector "%s" of "%s" ("%s") to "%s". Ignoring.\n' % (
  1509. k, ename, edecl['charselector'][k], charselect[k]))
  1510. else:
  1511. edecl['charselector'][k] = copy.copy(charselect[k])
  1512. if 'typename' not in edecl:
  1513. edecl['typename'] = typename
  1514. elif typename and (not edecl['typename'] == typename):
  1515. outmess('updatevars: attempt to change the typename of "%s" ("%s") to "%s". Ignoring.\n' % (
  1516. ename, edecl['typename'], typename))
  1517. if 'attrspec' not in edecl:
  1518. edecl['attrspec'] = copy.copy(attrspec)
  1519. elif attrspec:
  1520. for a in attrspec:
  1521. if a not in edecl['attrspec']:
  1522. edecl['attrspec'].append(a)
  1523. else:
  1524. edecl['typespec'] = copy.copy(typespec)
  1525. edecl['kindselector'] = copy.copy(kindselect)
  1526. edecl['charselector'] = copy.copy(charselect)
  1527. edecl['typename'] = typename
  1528. edecl['attrspec'] = copy.copy(attrspec)
  1529. if m.group('after'):
  1530. m1 = lenarraypattern.match(markouterparen(m.group('after')))
  1531. if m1:
  1532. d1 = m1.groupdict()
  1533. for lk in ['len', 'array', 'init']:
  1534. if d1[lk + '2'] is not None:
  1535. d1[lk] = d1[lk + '2']
  1536. del d1[lk + '2']
  1537. for k in list(d1.keys()):
  1538. if d1[k] is not None:
  1539. d1[k] = unmarkouterparen(d1[k])
  1540. else:
  1541. del d1[k]
  1542. if 'len' in d1 and 'array' in d1:
  1543. if d1['len'] == '':
  1544. d1['len'] = d1['array']
  1545. del d1['array']
  1546. else:
  1547. d1['array'] = d1['array'] + ',' + d1['len']
  1548. del d1['len']
  1549. errmess('updatevars: "%s %s" is mapped to "%s %s(%s)"\n' % (
  1550. typespec, e, typespec, ename, d1['array']))
  1551. if 'array' in d1:
  1552. dm = 'dimension(%s)' % d1['array']
  1553. if 'attrspec' not in edecl or (not edecl['attrspec']):
  1554. edecl['attrspec'] = [dm]
  1555. else:
  1556. edecl['attrspec'].append(dm)
  1557. for dm1 in edecl['attrspec']:
  1558. if dm1[:9] == 'dimension' and dm1 != dm:
  1559. del edecl['attrspec'][-1]
  1560. errmess('updatevars:%s: attempt to change %r to %r. Ignoring.\n'
  1561. % (ename, dm1, dm))
  1562. break
  1563. if 'len' in d1:
  1564. if typespec in ['complex', 'integer', 'logical', 'real']:
  1565. if ('kindselector' not in edecl) or (not edecl['kindselector']):
  1566. edecl['kindselector'] = {}
  1567. edecl['kindselector']['*'] = d1['len']
  1568. elif typespec == 'character':
  1569. if ('charselector' not in edecl) or (not edecl['charselector']):
  1570. edecl['charselector'] = {}
  1571. if 'len' in edecl['charselector']:
  1572. del edecl['charselector']['len']
  1573. edecl['charselector']['*'] = d1['len']
  1574. if 'init' in d1:
  1575. if '=' in edecl and (not edecl['='] == d1['init']):
  1576. outmess('updatevars: attempt to change the init expression of "%s" ("%s") to "%s". Ignoring.\n' % (
  1577. ename, edecl['='], d1['init']))
  1578. else:
  1579. edecl['='] = d1['init']
  1580. else:
  1581. outmess('updatevars: could not crack entity declaration "%s". Ignoring.\n' % (
  1582. ename + m.group('after')))
  1583. for k in list(edecl.keys()):
  1584. if not edecl[k]:
  1585. del edecl[k]
  1586. groupcache[groupcounter]['vars'][ename] = edecl
  1587. if 'varnames' in groupcache[groupcounter]:
  1588. groupcache[groupcounter]['varnames'].append(ename)
  1589. last_name = ename
  1590. return last_name
  1591. def cracktypespec(typespec, selector):
  1592. kindselect = None
  1593. charselect = None
  1594. typename = None
  1595. if selector:
  1596. if typespec in ['complex', 'integer', 'logical', 'real']:
  1597. kindselect = kindselector.match(selector)
  1598. if not kindselect:
  1599. outmess(
  1600. 'cracktypespec: no kindselector pattern found for %s\n' % (repr(selector)))
  1601. return
  1602. kindselect = kindselect.groupdict()
  1603. kindselect['*'] = kindselect['kind2']
  1604. del kindselect['kind2']
  1605. for k in list(kindselect.keys()):
  1606. if not kindselect[k]:
  1607. del kindselect[k]
  1608. for k, i in list(kindselect.items()):
  1609. kindselect[k] = rmbadname1(i)
  1610. elif typespec == 'character':
  1611. charselect = charselector.match(selector)
  1612. if not charselect:
  1613. outmess(
  1614. 'cracktypespec: no charselector pattern found for %s\n' % (repr(selector)))
  1615. return
  1616. charselect = charselect.groupdict()
  1617. charselect['*'] = charselect['charlen']
  1618. del charselect['charlen']
  1619. if charselect['lenkind']:
  1620. lenkind = lenkindpattern.match(
  1621. markoutercomma(charselect['lenkind']))
  1622. lenkind = lenkind.groupdict()
  1623. for lk in ['len', 'kind']:
  1624. if lenkind[lk + '2']:
  1625. lenkind[lk] = lenkind[lk + '2']
  1626. charselect[lk] = lenkind[lk]
  1627. del lenkind[lk + '2']
  1628. del charselect['lenkind']
  1629. for k in list(charselect.keys()):
  1630. if not charselect[k]:
  1631. del charselect[k]
  1632. for k, i in list(charselect.items()):
  1633. charselect[k] = rmbadname1(i)
  1634. elif typespec == 'type':
  1635. typename = re.match(r'\s*\(\s*(?P<name>\w+)\s*\)', selector, re.I)
  1636. if typename:
  1637. typename = typename.group('name')
  1638. else:
  1639. outmess('cracktypespec: no typename found in %s\n' %
  1640. (repr(typespec + selector)))
  1641. else:
  1642. outmess('cracktypespec: no selector used for %s\n' %
  1643. (repr(selector)))
  1644. return kindselect, charselect, typename
  1645. ######
  1646. def setattrspec(decl, attr, force=0):
  1647. if not decl:
  1648. decl = {}
  1649. if not attr:
  1650. return decl
  1651. if 'attrspec' not in decl:
  1652. decl['attrspec'] = [attr]
  1653. return decl
  1654. if force:
  1655. decl['attrspec'].append(attr)
  1656. if attr in decl['attrspec']:
  1657. return decl
  1658. if attr == 'static' and 'automatic' not in decl['attrspec']:
  1659. decl['attrspec'].append(attr)
  1660. elif attr == 'automatic' and 'static' not in decl['attrspec']:
  1661. decl['attrspec'].append(attr)
  1662. elif attr == 'public':
  1663. if 'private' not in decl['attrspec']:
  1664. decl['attrspec'].append(attr)
  1665. elif attr == 'private':
  1666. if 'public' not in decl['attrspec']:
  1667. decl['attrspec'].append(attr)
  1668. else:
  1669. decl['attrspec'].append(attr)
  1670. return decl
  1671. def setkindselector(decl, sel, force=0):
  1672. if not decl:
  1673. decl = {}
  1674. if not sel:
  1675. return decl
  1676. if 'kindselector' not in decl:
  1677. decl['kindselector'] = sel
  1678. return decl
  1679. for k in list(sel.keys()):
  1680. if force or k not in decl['kindselector']:
  1681. decl['kindselector'][k] = sel[k]
  1682. return decl
  1683. def setcharselector(decl, sel, force=0):
  1684. if not decl:
  1685. decl = {}
  1686. if not sel:
  1687. return decl
  1688. if 'charselector' not in decl:
  1689. decl['charselector'] = sel
  1690. return decl
  1691. for k in list(sel.keys()):
  1692. if force or k not in decl['charselector']:
  1693. decl['charselector'][k] = sel[k]
  1694. return decl
  1695. def getblockname(block, unknown='unknown'):
  1696. if 'name' in block:
  1697. return block['name']
  1698. return unknown
  1699. # post processing
  1700. def setmesstext(block):
  1701. global filepositiontext
  1702. try:
  1703. filepositiontext = 'In: %s:%s\n' % (block['from'], block['name'])
  1704. except Exception:
  1705. pass
  1706. def get_usedict(block):
  1707. usedict = {}
  1708. if 'parent_block' in block:
  1709. usedict = get_usedict(block['parent_block'])
  1710. if 'use' in block:
  1711. usedict.update(block['use'])
  1712. return usedict
  1713. def get_useparameters(block, param_map=None):
  1714. global f90modulevars
  1715. if param_map is None:
  1716. param_map = {}
  1717. usedict = get_usedict(block)
  1718. if not usedict:
  1719. return param_map
  1720. for usename, mapping in list(usedict.items()):
  1721. usename = usename.lower()
  1722. if usename not in f90modulevars:
  1723. outmess('get_useparameters: no module %s info used by %s\n' %
  1724. (usename, block.get('name')))
  1725. continue
  1726. mvars = f90modulevars[usename]
  1727. params = get_parameters(mvars)
  1728. if not params:
  1729. continue
  1730. # XXX: apply mapping
  1731. if mapping:
  1732. errmess('get_useparameters: mapping for %s not impl.' % (mapping))
  1733. for k, v in list(params.items()):
  1734. if k in param_map:
  1735. outmess('get_useparameters: overriding parameter %s with'
  1736. ' value from module %s' % (repr(k), repr(usename)))
  1737. param_map[k] = v
  1738. return param_map
  1739. def postcrack2(block, tab='', param_map=None):
  1740. global f90modulevars
  1741. if not f90modulevars:
  1742. return block
  1743. if isinstance(block, list):
  1744. ret = [postcrack2(g, tab=tab + '\t', param_map=param_map)
  1745. for g in block]
  1746. return ret
  1747. setmesstext(block)
  1748. outmess('%sBlock: %s\n' % (tab, block['name']), 0)
  1749. if param_map is None:
  1750. param_map = get_useparameters(block)
  1751. if param_map is not None and 'vars' in block:
  1752. vars = block['vars']
  1753. for n in list(vars.keys()):
  1754. var = vars[n]
  1755. if 'kindselector' in var:
  1756. kind = var['kindselector']
  1757. if 'kind' in kind:
  1758. val = kind['kind']
  1759. if val in param_map:
  1760. kind['kind'] = param_map[val]
  1761. new_body = [postcrack2(b, tab=tab + '\t', param_map=param_map)
  1762. for b in block['body']]
  1763. block['body'] = new_body
  1764. return block
  1765. def postcrack(block, args=None, tab=''):
  1766. """
  1767. TODO:
  1768. function return values
  1769. determine expression types if in argument list
  1770. """
  1771. global usermodules, onlyfunctions
  1772. if isinstance(block, list):
  1773. gret = []
  1774. uret = []
  1775. for g in block:
  1776. setmesstext(g)
  1777. g = postcrack(g, tab=tab + '\t')
  1778. # sort user routines to appear first
  1779. if 'name' in g and '__user__' in g['name']:
  1780. uret.append(g)
  1781. else:
  1782. gret.append(g)
  1783. return uret + gret
  1784. setmesstext(block)
  1785. if not isinstance(block, dict) and 'block' not in block:
  1786. raise Exception('postcrack: Expected block dictionary instead of ' +
  1787. str(block))
  1788. if 'name' in block and not block['name'] == 'unknown_interface':
  1789. outmess('%sBlock: %s\n' % (tab, block['name']), 0)
  1790. block = analyzeargs(block)
  1791. block = analyzecommon(block)
  1792. block['vars'] = analyzevars(block)
  1793. block['sortvars'] = sortvarnames(block['vars'])
  1794. if 'args' in block and block['args']:
  1795. args = block['args']
  1796. block['body'] = analyzebody(block, args, tab=tab)
  1797. userisdefined = []
  1798. if 'use' in block:
  1799. useblock = block['use']
  1800. for k in list(useblock.keys()):
  1801. if '__user__' in k:
  1802. userisdefined.append(k)
  1803. else:
  1804. useblock = {}
  1805. name = ''
  1806. if 'name' in block:
  1807. name = block['name']
  1808. # and not userisdefined: # Build a __user__ module
  1809. if 'externals' in block and block['externals']:
  1810. interfaced = []
  1811. if 'interfaced' in block:
  1812. interfaced = block['interfaced']
  1813. mvars = copy.copy(block['vars'])
  1814. if name:
  1815. mname = name + '__user__routines'
  1816. else:
  1817. mname = 'unknown__user__routines'
  1818. if mname in userisdefined:
  1819. i = 1
  1820. while '%s_%i' % (mname, i) in userisdefined:
  1821. i = i + 1
  1822. mname = '%s_%i' % (mname, i)
  1823. interface = {'block': 'interface', 'body': [],
  1824. 'vars': {}, 'name': name + '_user_interface'}
  1825. for e in block['externals']:
  1826. if e in interfaced:
  1827. edef = []
  1828. j = -1
  1829. for b in block['body']:
  1830. j = j + 1
  1831. if b['block'] == 'interface':
  1832. i = -1
  1833. for bb in b['body']:
  1834. i = i + 1
  1835. if 'name' in bb and bb['name'] == e:
  1836. edef = copy.copy(bb)
  1837. del b['body'][i]
  1838. break
  1839. if edef:
  1840. if not b['body']:
  1841. del block['body'][j]
  1842. del interfaced[interfaced.index(e)]
  1843. break
  1844. interface['body'].append(edef)
  1845. else:
  1846. if e in mvars and not isexternal(mvars[e]):
  1847. interface['vars'][e] = mvars[e]
  1848. if interface['vars'] or interface['body']:
  1849. block['interfaced'] = interfaced
  1850. mblock = {'block': 'python module', 'body': [
  1851. interface], 'vars': {}, 'name': mname, 'interfaced': block['externals']}
  1852. useblock[mname] = {}
  1853. usermodules.append(mblock)
  1854. if useblock:
  1855. block['use'] = useblock
  1856. return block
  1857. def sortvarnames(vars):
  1858. indep = []
  1859. dep = []
  1860. for v in list(vars.keys()):
  1861. if 'depend' in vars[v] and vars[v]['depend']:
  1862. dep.append(v)
  1863. else:
  1864. indep.append(v)
  1865. n = len(dep)
  1866. i = 0
  1867. while dep: # XXX: How to catch dependence cycles correctly?
  1868. v = dep[0]
  1869. fl = 0
  1870. for w in dep[1:]:
  1871. if w in vars[v]['depend']:
  1872. fl = 1
  1873. break
  1874. if fl:
  1875. dep = dep[1:] + [v]
  1876. i = i + 1
  1877. if i > n:
  1878. errmess('sortvarnames: failed to compute dependencies because'
  1879. ' of cyclic dependencies between '
  1880. + ', '.join(dep) + '\n')
  1881. indep = indep + dep
  1882. break
  1883. else:
  1884. indep.append(v)
  1885. dep = dep[1:]
  1886. n = len(dep)
  1887. i = 0
  1888. return indep
  1889. def analyzecommon(block):
  1890. if not hascommon(block):
  1891. return block
  1892. commonvars = []
  1893. for k in list(block['common'].keys()):
  1894. comvars = []
  1895. for e in block['common'][k]:
  1896. m = re.match(
  1897. r'\A\s*\b(?P<name>.*?)\b\s*(\((?P<dims>.*?)\)|)\s*\Z', e, re.I)
  1898. if m:
  1899. dims = []
  1900. if m.group('dims'):
  1901. dims = [x.strip()
  1902. for x in markoutercomma(m.group('dims')).split('@,@')]
  1903. n = rmbadname1(m.group('name').strip())
  1904. if n in block['vars']:
  1905. if 'attrspec' in block['vars'][n]:
  1906. block['vars'][n]['attrspec'].append(
  1907. 'dimension(%s)' % (','.join(dims)))
  1908. else:
  1909. block['vars'][n]['attrspec'] = [
  1910. 'dimension(%s)' % (','.join(dims))]
  1911. else:
  1912. if dims:
  1913. block['vars'][n] = {
  1914. 'attrspec': ['dimension(%s)' % (','.join(dims))]}
  1915. else:
  1916. block['vars'][n] = {}
  1917. if n not in commonvars:
  1918. commonvars.append(n)
  1919. else:
  1920. n = e
  1921. errmess(
  1922. 'analyzecommon: failed to extract "<name>[(<dims>)]" from "%s" in common /%s/.\n' % (e, k))
  1923. comvars.append(n)
  1924. block['common'][k] = comvars
  1925. if 'commonvars' not in block:
  1926. block['commonvars'] = commonvars
  1927. else:
  1928. block['commonvars'] = block['commonvars'] + commonvars
  1929. return block
  1930. def analyzebody(block, args, tab=''):
  1931. global usermodules, skipfuncs, onlyfuncs, f90modulevars
  1932. setmesstext(block)
  1933. body = []
  1934. for b in block['body']:
  1935. b['parent_block'] = block
  1936. if b['block'] in ['function', 'subroutine']:
  1937. if args is not None and b['name'] not in args:
  1938. continue
  1939. else:
  1940. as_ = b['args']
  1941. if b['name'] in skipfuncs:
  1942. continue
  1943. if onlyfuncs and b['name'] not in onlyfuncs:
  1944. continue
  1945. b['saved_interface'] = crack2fortrangen(
  1946. b, '\n' + ' ' * 6, as_interface=True)
  1947. else:
  1948. as_ = args
  1949. b = postcrack(b, as_, tab=tab + '\t')
  1950. if b['block'] == 'interface' and not b['body']:
  1951. if 'f2pyenhancements' not in b:
  1952. continue
  1953. if b['block'].replace(' ', '') == 'pythonmodule':
  1954. usermodules.append(b)
  1955. else:
  1956. if b['block'] == 'module':
  1957. f90modulevars[b['name']] = b['vars']
  1958. body.append(b)
  1959. return body
  1960. def buildimplicitrules(block):
  1961. setmesstext(block)
  1962. implicitrules = defaultimplicitrules
  1963. attrrules = {}
  1964. if 'implicit' in block:
  1965. if block['implicit'] is None:
  1966. implicitrules = None
  1967. if verbose > 1:
  1968. outmess(
  1969. 'buildimplicitrules: no implicit rules for routine %s.\n' % repr(block['name']))
  1970. else:
  1971. for k in list(block['implicit'].keys()):
  1972. if block['implicit'][k].get('typespec') not in ['static', 'automatic']:
  1973. implicitrules[k] = block['implicit'][k]
  1974. else:
  1975. attrrules[k] = block['implicit'][k]['typespec']
  1976. return implicitrules, attrrules
  1977. def myeval(e, g=None, l=None):
  1978. r = eval(e, g, l)
  1979. if type(r) in [type(0), type(0.0)]:
  1980. return r
  1981. raise ValueError('r=%r' % (r))
  1982. getlincoef_re_1 = re.compile(r'\A\b\w+\b\Z', re.I)
  1983. def getlincoef(e, xset): # e = a*x+b ; x in xset
  1984. try:
  1985. c = int(myeval(e, {}, {}))
  1986. return 0, c, None
  1987. except Exception:
  1988. pass
  1989. if getlincoef_re_1.match(e):
  1990. return 1, 0, e
  1991. len_e = len(e)
  1992. for x in xset:
  1993. if len(x) > len_e:
  1994. continue
  1995. if re.search(r'\w\s*\([^)]*\b' + x + r'\b', e):
  1996. # skip function calls having x as an argument, e.g max(1, x)
  1997. continue
  1998. re_1 = re.compile(r'(?P<before>.*?)\b' + x + r'\b(?P<after>.*)', re.I)
  1999. m = re_1.match(e)
  2000. if m:
  2001. try:
  2002. m1 = re_1.match(e)
  2003. while m1:
  2004. ee = '%s(%s)%s' % (
  2005. m1.group('before'), 0, m1.group('after'))
  2006. m1 = re_1.match(ee)
  2007. b = myeval(ee, {}, {})
  2008. m1 = re_1.match(e)
  2009. while m1:
  2010. ee = '%s(%s)%s' % (
  2011. m1.group('before'), 1, m1.group('after'))
  2012. m1 = re_1.match(ee)
  2013. a = myeval(ee, {}, {}) - b
  2014. m1 = re_1.match(e)
  2015. while m1:
  2016. ee = '%s(%s)%s' % (
  2017. m1.group('before'), 0.5, m1.group('after'))
  2018. m1 = re_1.match(ee)
  2019. c = myeval(ee, {}, {})
  2020. # computing another point to be sure that expression is linear
  2021. m1 = re_1.match(e)
  2022. while m1:
  2023. ee = '%s(%s)%s' % (
  2024. m1.group('before'), 1.5, m1.group('after'))
  2025. m1 = re_1.match(ee)
  2026. c2 = myeval(ee, {}, {})
  2027. if (a * 0.5 + b == c and a * 1.5 + b == c2):
  2028. return a, b, x
  2029. except Exception:
  2030. pass
  2031. break
  2032. return None, None, None
  2033. _varname_match = re.compile(r'\A[a-z]\w*\Z').match
  2034. def getarrlen(dl, args, star='*'):
  2035. edl = []
  2036. try:
  2037. edl.append(myeval(dl[0], {}, {}))
  2038. except Exception:
  2039. edl.append(dl[0])
  2040. try:
  2041. edl.append(myeval(dl[1], {}, {}))
  2042. except Exception:
  2043. edl.append(dl[1])
  2044. if isinstance(edl[0], int):
  2045. p1 = 1 - edl[0]
  2046. if p1 == 0:
  2047. d = str(dl[1])
  2048. elif p1 < 0:
  2049. d = '%s-%s' % (dl[1], -p1)
  2050. else:
  2051. d = '%s+%s' % (dl[1], p1)
  2052. elif isinstance(edl[1], int):
  2053. p1 = 1 + edl[1]
  2054. if p1 == 0:
  2055. d = '-(%s)' % (dl[0])
  2056. else:
  2057. d = '%s-(%s)' % (p1, dl[0])
  2058. else:
  2059. d = '%s-(%s)+1' % (dl[1], dl[0])
  2060. try:
  2061. return repr(myeval(d, {}, {})), None, None
  2062. except Exception:
  2063. pass
  2064. d1, d2 = getlincoef(dl[0], args), getlincoef(dl[1], args)
  2065. if None not in [d1[0], d2[0]]:
  2066. if (d1[0], d2[0]) == (0, 0):
  2067. return repr(d2[1] - d1[1] + 1), None, None
  2068. b = d2[1] - d1[1] + 1
  2069. d1 = (d1[0], 0, d1[2])
  2070. d2 = (d2[0], b, d2[2])
  2071. if d1[0] == 0 and d2[2] in args:
  2072. if b < 0:
  2073. return '%s * %s - %s' % (d2[0], d2[2], -b), d2[2], '+%s)/(%s)' % (-b, d2[0])
  2074. elif b:
  2075. return '%s * %s + %s' % (d2[0], d2[2], b), d2[2], '-%s)/(%s)' % (b, d2[0])
  2076. else:
  2077. return '%s * %s' % (d2[0], d2[2]), d2[2], ')/(%s)' % (d2[0])
  2078. if d2[0] == 0 and d1[2] in args:
  2079. if b < 0:
  2080. return '%s * %s - %s' % (-d1[0], d1[2], -b), d1[2], '+%s)/(%s)' % (-b, -d1[0])
  2081. elif b:
  2082. return '%s * %s + %s' % (-d1[0], d1[2], b), d1[2], '-%s)/(%s)' % (b, -d1[0])
  2083. else:
  2084. return '%s * %s' % (-d1[0], d1[2]), d1[2], ')/(%s)' % (-d1[0])
  2085. if d1[2] == d2[2] and d1[2] in args:
  2086. a = d2[0] - d1[0]
  2087. if not a:
  2088. return repr(b), None, None
  2089. if b < 0:
  2090. return '%s * %s - %s' % (a, d1[2], -b), d2[2], '+%s)/(%s)' % (-b, a)
  2091. elif b:
  2092. return '%s * %s + %s' % (a, d1[2], b), d2[2], '-%s)/(%s)' % (b, a)
  2093. else:
  2094. return '%s * %s' % (a, d1[2]), d2[2], ')/(%s)' % (a)
  2095. if d1[0] == d2[0] == 1:
  2096. c = str(d1[2])
  2097. if c not in args:
  2098. if _varname_match(c):
  2099. outmess('\tgetarrlen:variable "%s" undefined\n' % (c))
  2100. c = '(%s)' % c
  2101. if b == 0:
  2102. d = '%s-%s' % (d2[2], c)
  2103. elif b < 0:
  2104. d = '%s-%s-%s' % (d2[2], c, -b)
  2105. else:
  2106. d = '%s-%s+%s' % (d2[2], c, b)
  2107. elif d1[0] == 0:
  2108. c2 = str(d2[2])
  2109. if c2 not in args:
  2110. if _varname_match(c2):
  2111. outmess('\tgetarrlen:variable "%s" undefined\n' % (c2))
  2112. c2 = '(%s)' % c2
  2113. if d2[0] == 1:
  2114. pass
  2115. elif d2[0] == -1:
  2116. c2 = '-%s' % c2
  2117. else:
  2118. c2 = '%s*%s' % (d2[0], c2)
  2119. if b == 0:
  2120. d = c2
  2121. elif b < 0:
  2122. d = '%s-%s' % (c2, -b)
  2123. else:
  2124. d = '%s+%s' % (c2, b)
  2125. elif d2[0] == 0:
  2126. c1 = str(d1[2])
  2127. if c1 not in args:
  2128. if _varname_match(c1):
  2129. outmess('\tgetarrlen:variable "%s" undefined\n' % (c1))
  2130. c1 = '(%s)' % c1
  2131. if d1[0] == 1:
  2132. c1 = '-%s' % c1
  2133. elif d1[0] == -1:
  2134. c1 = '+%s' % c1
  2135. elif d1[0] < 0:
  2136. c1 = '+%s*%s' % (-d1[0], c1)
  2137. else:
  2138. c1 = '-%s*%s' % (d1[0], c1)
  2139. if b == 0:
  2140. d = c1
  2141. elif b < 0:
  2142. d = '%s-%s' % (c1, -b)
  2143. else:
  2144. d = '%s+%s' % (c1, b)
  2145. else:
  2146. c1 = str(d1[2])
  2147. if c1 not in args:
  2148. if _varname_match(c1):
  2149. outmess('\tgetarrlen:variable "%s" undefined\n' % (c1))
  2150. c1 = '(%s)' % c1
  2151. if d1[0] == 1:
  2152. c1 = '-%s' % c1
  2153. elif d1[0] == -1:
  2154. c1 = '+%s' % c1
  2155. elif d1[0] < 0:
  2156. c1 = '+%s*%s' % (-d1[0], c1)
  2157. else:
  2158. c1 = '-%s*%s' % (d1[0], c1)
  2159. c2 = str(d2[2])
  2160. if c2 not in args:
  2161. if _varname_match(c2):
  2162. outmess('\tgetarrlen:variable "%s" undefined\n' % (c2))
  2163. c2 = '(%s)' % c2
  2164. if d2[0] == 1:
  2165. pass
  2166. elif d2[0] == -1:
  2167. c2 = '-%s' % c2
  2168. else:
  2169. c2 = '%s*%s' % (d2[0], c2)
  2170. if b == 0:
  2171. d = '%s%s' % (c2, c1)
  2172. elif b < 0:
  2173. d = '%s%s-%s' % (c2, c1, -b)
  2174. else:
  2175. d = '%s%s+%s' % (c2, c1, b)
  2176. return d, None, None
  2177. word_pattern = re.compile(r'\b[a-z][\w$]*\b', re.I)
  2178. def _get_depend_dict(name, vars, deps):
  2179. if name in vars:
  2180. words = vars[name].get('depend', [])
  2181. if '=' in vars[name] and not isstring(vars[name]):
  2182. for word in word_pattern.findall(vars[name]['=']):
  2183. if word not in words and word in vars:
  2184. words.append(word)
  2185. for word in words[:]:
  2186. for w in deps.get(word, []) \
  2187. or _get_depend_dict(word, vars, deps):
  2188. if w not in words:
  2189. words.append(w)
  2190. else:
  2191. outmess('_get_depend_dict: no dependence info for %s\n' % (repr(name)))
  2192. words = []
  2193. deps[name] = words
  2194. return words
  2195. def _calc_depend_dict(vars):
  2196. names = list(vars.keys())
  2197. depend_dict = {}
  2198. for n in names:
  2199. _get_depend_dict(n, vars, depend_dict)
  2200. return depend_dict
  2201. def get_sorted_names(vars):
  2202. """
  2203. """
  2204. depend_dict = _calc_depend_dict(vars)
  2205. names = []
  2206. for name in list(depend_dict.keys()):
  2207. if not depend_dict[name]:
  2208. names.append(name)
  2209. del depend_dict[name]
  2210. while depend_dict:
  2211. for name, lst in list(depend_dict.items()):
  2212. new_lst = [n for n in lst if n in depend_dict]
  2213. if not new_lst:
  2214. names.append(name)
  2215. del depend_dict[name]
  2216. else:
  2217. depend_dict[name] = new_lst
  2218. return [name for name in names if name in vars]
  2219. def _kind_func(string):
  2220. # XXX: return something sensible.
  2221. if string[0] in "'\"":
  2222. string = string[1:-1]
  2223. if real16pattern.match(string):
  2224. return 8
  2225. elif real8pattern.match(string):
  2226. return 4
  2227. return 'kind(' + string + ')'
  2228. def _selected_int_kind_func(r):
  2229. # XXX: This should be processor dependent
  2230. m = 10 ** r
  2231. if m <= 2 ** 8:
  2232. return 1
  2233. if m <= 2 ** 16:
  2234. return 2
  2235. if m <= 2 ** 32:
  2236. return 4
  2237. if m <= 2 ** 63:
  2238. return 8
  2239. if m <= 2 ** 128:
  2240. return 16
  2241. return -1
  2242. def _selected_real_kind_func(p, r=0, radix=0):
  2243. # XXX: This should be processor dependent
  2244. # This is only good for 0 <= p <= 20
  2245. if p < 7:
  2246. return 4
  2247. if p < 16:
  2248. return 8
  2249. machine = platform.machine().lower()
  2250. if machine.startswith(('aarch64', 'power', 'ppc', 'riscv', 's390x', 'sparc')):
  2251. if p <= 20:
  2252. return 16
  2253. else:
  2254. if p < 19:
  2255. return 10
  2256. elif p <= 20:
  2257. return 16
  2258. return -1
  2259. def get_parameters(vars, global_params={}):
  2260. params = copy.copy(global_params)
  2261. g_params = copy.copy(global_params)
  2262. for name, func in [('kind', _kind_func),
  2263. ('selected_int_kind', _selected_int_kind_func),
  2264. ('selected_real_kind', _selected_real_kind_func), ]:
  2265. if name not in g_params:
  2266. g_params[name] = func
  2267. param_names = []
  2268. for n in get_sorted_names(vars):
  2269. if 'attrspec' in vars[n] and 'parameter' in vars[n]['attrspec']:
  2270. param_names.append(n)
  2271. kind_re = re.compile(r'\bkind\s*\(\s*(?P<value>.*)\s*\)', re.I)
  2272. selected_int_kind_re = re.compile(
  2273. r'\bselected_int_kind\s*\(\s*(?P<value>.*)\s*\)', re.I)
  2274. selected_kind_re = re.compile(
  2275. r'\bselected_(int|real)_kind\s*\(\s*(?P<value>.*)\s*\)', re.I)
  2276. for n in param_names:
  2277. if '=' in vars[n]:
  2278. v = vars[n]['=']
  2279. if islogical(vars[n]):
  2280. v = v.lower()
  2281. for repl in [
  2282. ('.false.', 'False'),
  2283. ('.true.', 'True'),
  2284. # TODO: test .eq., .neq., etc replacements.
  2285. ]:
  2286. v = v.replace(*repl)
  2287. v = kind_re.sub(r'kind("\1")', v)
  2288. v = selected_int_kind_re.sub(r'selected_int_kind(\1)', v)
  2289. # We need to act according to the data.
  2290. # The easy case is if the data has a kind-specifier,
  2291. # then we may easily remove those specifiers.
  2292. # However, it may be that the user uses other specifiers...(!)
  2293. is_replaced = False
  2294. if 'kindselector' in vars[n]:
  2295. if 'kind' in vars[n]['kindselector']:
  2296. orig_v_len = len(v)
  2297. v = v.replace('_' + vars[n]['kindselector']['kind'], '')
  2298. # Again, this will be true if even a single specifier
  2299. # has been replaced, see comment above.
  2300. is_replaced = len(v) < orig_v_len
  2301. if not is_replaced:
  2302. if not selected_kind_re.match(v):
  2303. v_ = v.split('_')
  2304. # In case there are additive parameters
  2305. if len(v_) > 1:
  2306. v = ''.join(v_[:-1]).lower().replace(v_[-1].lower(), '')
  2307. # Currently this will not work for complex numbers.
  2308. # There is missing code for extracting a complex number,
  2309. # which may be defined in either of these:
  2310. # a) (Re, Im)
  2311. # b) cmplx(Re, Im)
  2312. # c) dcmplx(Re, Im)
  2313. # d) cmplx(Re, Im, <prec>)
  2314. if isdouble(vars[n]):
  2315. tt = list(v)
  2316. for m in real16pattern.finditer(v):
  2317. tt[m.start():m.end()] = list(
  2318. v[m.start():m.end()].lower().replace('d', 'e'))
  2319. v = ''.join(tt)
  2320. elif iscomplex(vars[n]):
  2321. # FIXME complex numbers may also have exponents
  2322. if v[0] == '(' and v[-1] == ')':
  2323. # FIXME, unused l looks like potential bug
  2324. l = markoutercomma(v[1:-1]).split('@,@')
  2325. try:
  2326. params[n] = eval(v, g_params, params)
  2327. except Exception as msg:
  2328. params[n] = v
  2329. outmess('get_parameters: got "%s" on %s\n' % (msg, repr(v)))
  2330. if isstring(vars[n]) and isinstance(params[n], int):
  2331. params[n] = chr(params[n])
  2332. nl = n.lower()
  2333. if nl != n:
  2334. params[nl] = params[n]
  2335. else:
  2336. print(vars[n])
  2337. outmess(
  2338. 'get_parameters:parameter %s does not have value?!\n' % (repr(n)))
  2339. return params
  2340. def _eval_length(length, params):
  2341. if length in ['(:)', '(*)', '*']:
  2342. return '(*)'
  2343. return _eval_scalar(length, params)
  2344. _is_kind_number = re.compile(r'\d+_').match
  2345. def _eval_scalar(value, params):
  2346. if _is_kind_number(value):
  2347. value = value.split('_')[0]
  2348. try:
  2349. value = str(eval(value, {}, params))
  2350. except (NameError, SyntaxError, TypeError):
  2351. return value
  2352. except Exception as msg:
  2353. errmess('"%s" in evaluating %r '
  2354. '(available names: %s)\n'
  2355. % (msg, value, list(params.keys())))
  2356. return value
  2357. def analyzevars(block):
  2358. global f90modulevars
  2359. setmesstext(block)
  2360. implicitrules, attrrules = buildimplicitrules(block)
  2361. vars = copy.copy(block['vars'])
  2362. if block['block'] == 'function' and block['name'] not in vars:
  2363. vars[block['name']] = {}
  2364. if '' in block['vars']:
  2365. del vars['']
  2366. if 'attrspec' in block['vars']['']:
  2367. gen = block['vars']['']['attrspec']
  2368. for n in list(vars.keys()):
  2369. for k in ['public', 'private']:
  2370. if k in gen:
  2371. vars[n] = setattrspec(vars[n], k)
  2372. svars = []
  2373. args = block['args']
  2374. for a in args:
  2375. try:
  2376. vars[a]
  2377. svars.append(a)
  2378. except KeyError:
  2379. pass
  2380. for n in list(vars.keys()):
  2381. if n not in args:
  2382. svars.append(n)
  2383. params = get_parameters(vars, get_useparameters(block))
  2384. dep_matches = {}
  2385. name_match = re.compile(r'\w[\w\d_$]*').match
  2386. for v in list(vars.keys()):
  2387. m = name_match(v)
  2388. if m:
  2389. n = v[m.start():m.end()]
  2390. try:
  2391. dep_matches[n]
  2392. except KeyError:
  2393. dep_matches[n] = re.compile(r'.*\b%s\b' % (v), re.I).match
  2394. for n in svars:
  2395. if n[0] in list(attrrules.keys()):
  2396. vars[n] = setattrspec(vars[n], attrrules[n[0]])
  2397. if 'typespec' not in vars[n]:
  2398. if not('attrspec' in vars[n] and 'external' in vars[n]['attrspec']):
  2399. if implicitrules:
  2400. ln0 = n[0].lower()
  2401. for k in list(implicitrules[ln0].keys()):
  2402. if k == 'typespec' and implicitrules[ln0][k] == 'undefined':
  2403. continue
  2404. if k not in vars[n]:
  2405. vars[n][k] = implicitrules[ln0][k]
  2406. elif k == 'attrspec':
  2407. for l in implicitrules[ln0][k]:
  2408. vars[n] = setattrspec(vars[n], l)
  2409. elif n in block['args']:
  2410. outmess('analyzevars: typespec of variable %s is not defined in routine %s.\n' % (
  2411. repr(n), block['name']))
  2412. if 'charselector' in vars[n]:
  2413. if 'len' in vars[n]['charselector']:
  2414. l = vars[n]['charselector']['len']
  2415. try:
  2416. l = str(eval(l, {}, params))
  2417. except Exception:
  2418. pass
  2419. vars[n]['charselector']['len'] = l
  2420. if 'kindselector' in vars[n]:
  2421. if 'kind' in vars[n]['kindselector']:
  2422. l = vars[n]['kindselector']['kind']
  2423. try:
  2424. l = str(eval(l, {}, params))
  2425. except Exception:
  2426. pass
  2427. vars[n]['kindselector']['kind'] = l
  2428. savelindims = {}
  2429. if 'attrspec' in vars[n]:
  2430. attr = vars[n]['attrspec']
  2431. attr.reverse()
  2432. vars[n]['attrspec'] = []
  2433. dim, intent, depend, check, note = None, None, None, None, None
  2434. for a in attr:
  2435. if a[:9] == 'dimension':
  2436. dim = (a[9:].strip())[1:-1]
  2437. elif a[:6] == 'intent':
  2438. intent = (a[6:].strip())[1:-1]
  2439. elif a[:6] == 'depend':
  2440. depend = (a[6:].strip())[1:-1]
  2441. elif a[:5] == 'check':
  2442. check = (a[5:].strip())[1:-1]
  2443. elif a[:4] == 'note':
  2444. note = (a[4:].strip())[1:-1]
  2445. else:
  2446. vars[n] = setattrspec(vars[n], a)
  2447. if intent:
  2448. if 'intent' not in vars[n]:
  2449. vars[n]['intent'] = []
  2450. for c in [x.strip() for x in markoutercomma(intent).split('@,@')]:
  2451. # Remove spaces so that 'in out' becomes 'inout'
  2452. tmp = c.replace(' ', '')
  2453. if tmp not in vars[n]['intent']:
  2454. vars[n]['intent'].append(tmp)
  2455. intent = None
  2456. if note:
  2457. note = note.replace('\\n\\n', '\n\n')
  2458. note = note.replace('\\n ', '\n')
  2459. if 'note' not in vars[n]:
  2460. vars[n]['note'] = [note]
  2461. else:
  2462. vars[n]['note'].append(note)
  2463. note = None
  2464. if depend is not None:
  2465. if 'depend' not in vars[n]:
  2466. vars[n]['depend'] = []
  2467. for c in rmbadname([x.strip() for x in markoutercomma(depend).split('@,@')]):
  2468. if c not in vars[n]['depend']:
  2469. vars[n]['depend'].append(c)
  2470. depend = None
  2471. if check is not None:
  2472. if 'check' not in vars[n]:
  2473. vars[n]['check'] = []
  2474. for c in [x.strip() for x in markoutercomma(check).split('@,@')]:
  2475. if c not in vars[n]['check']:
  2476. vars[n]['check'].append(c)
  2477. check = None
  2478. if dim and 'dimension' not in vars[n]:
  2479. vars[n]['dimension'] = []
  2480. for d in rmbadname([x.strip() for x in markoutercomma(dim).split('@,@')]):
  2481. star = '*'
  2482. if d == ':':
  2483. star = ':'
  2484. if d in params:
  2485. d = str(params[d])
  2486. for p in list(params.keys()):
  2487. re_1 = re.compile(r'(?P<before>.*?)\b' + p + r'\b(?P<after>.*)', re.I)
  2488. m = re_1.match(d)
  2489. while m:
  2490. d = m.group('before') + \
  2491. str(params[p]) + m.group('after')
  2492. m = re_1.match(d)
  2493. if d == star:
  2494. dl = [star]
  2495. else:
  2496. dl = markoutercomma(d, ':').split('@:@')
  2497. if len(dl) == 2 and '*' in dl: # e.g. dimension(5:*)
  2498. dl = ['*']
  2499. d = '*'
  2500. if len(dl) == 1 and not dl[0] == star:
  2501. dl = ['1', dl[0]]
  2502. if len(dl) == 2:
  2503. d, v, di = getarrlen(dl, list(block['vars'].keys()))
  2504. if d[:4] == '1 * ':
  2505. d = d[4:]
  2506. if di and di[-4:] == '/(1)':
  2507. di = di[:-4]
  2508. if v:
  2509. savelindims[d] = v, di
  2510. vars[n]['dimension'].append(d)
  2511. if 'dimension' in vars[n]:
  2512. if isintent_c(vars[n]):
  2513. shape_macro = 'shape'
  2514. else:
  2515. shape_macro = 'shape' # 'fshape'
  2516. if isstringarray(vars[n]):
  2517. if 'charselector' in vars[n]:
  2518. d = vars[n]['charselector']
  2519. if '*' in d:
  2520. d = d['*']
  2521. errmess('analyzevars: character array "character*%s %s(%s)" is considered as "character %s(%s)"; "intent(c)" is forced.\n'
  2522. % (d, n,
  2523. ','.join(vars[n]['dimension']),
  2524. n, ','.join(vars[n]['dimension'] + [d])))
  2525. vars[n]['dimension'].append(d)
  2526. del vars[n]['charselector']
  2527. if 'intent' not in vars[n]:
  2528. vars[n]['intent'] = []
  2529. if 'c' not in vars[n]['intent']:
  2530. vars[n]['intent'].append('c')
  2531. else:
  2532. errmess(
  2533. "analyzevars: charselector=%r unhandled." % (d))
  2534. if 'check' not in vars[n] and 'args' in block and n in block['args']:
  2535. flag = 'depend' not in vars[n]
  2536. if flag:
  2537. vars[n]['depend'] = []
  2538. vars[n]['check'] = []
  2539. if 'dimension' in vars[n]:
  2540. #/----< no check
  2541. i = -1
  2542. ni = len(vars[n]['dimension'])
  2543. for d in vars[n]['dimension']:
  2544. ddeps = [] # dependencies of 'd'
  2545. ad = ''
  2546. pd = ''
  2547. if d not in vars:
  2548. if d in savelindims:
  2549. pd, ad = '(', savelindims[d][1]
  2550. d = savelindims[d][0]
  2551. else:
  2552. for r in block['args']:
  2553. if r not in vars:
  2554. continue
  2555. if re.match(r'.*?\b' + r + r'\b', d, re.I):
  2556. ddeps.append(r)
  2557. if d in vars:
  2558. if 'attrspec' in vars[d]:
  2559. for aa in vars[d]['attrspec']:
  2560. if aa[:6] == 'depend':
  2561. ddeps += aa[6:].strip()[1:-1].split(',')
  2562. if 'depend' in vars[d]:
  2563. ddeps = ddeps + vars[d]['depend']
  2564. i = i + 1
  2565. if d in vars and ('depend' not in vars[d]) \
  2566. and ('=' not in vars[d]) and (d not in vars[n]['depend']) \
  2567. and l_or(isintent_in, isintent_inout, isintent_inplace)(vars[n]):
  2568. vars[d]['depend'] = [n]
  2569. if ni > 1:
  2570. vars[d]['='] = '%s%s(%s,%s)%s' % (
  2571. pd, shape_macro, n, i, ad)
  2572. else:
  2573. vars[d]['='] = '%slen(%s)%s' % (pd, n, ad)
  2574. # /---< no check
  2575. if 1 and 'check' not in vars[d]:
  2576. if ni > 1:
  2577. vars[d]['check'] = ['%s%s(%s,%i)%s==%s'
  2578. % (pd, shape_macro, n, i, ad, d)]
  2579. else:
  2580. vars[d]['check'] = [
  2581. '%slen(%s)%s>=%s' % (pd, n, ad, d)]
  2582. if 'attrspec' not in vars[d]:
  2583. vars[d]['attrspec'] = ['optional']
  2584. if ('optional' not in vars[d]['attrspec']) and\
  2585. ('required' not in vars[d]['attrspec']):
  2586. vars[d]['attrspec'].append('optional')
  2587. elif d not in ['*', ':']:
  2588. #/----< no check
  2589. if flag:
  2590. if d in vars:
  2591. if n not in ddeps:
  2592. vars[n]['depend'].append(d)
  2593. else:
  2594. vars[n]['depend'] = vars[n]['depend'] + ddeps
  2595. elif isstring(vars[n]):
  2596. length = '1'
  2597. if 'charselector' in vars[n]:
  2598. if '*' in vars[n]['charselector']:
  2599. length = _eval_length(vars[n]['charselector']['*'],
  2600. params)
  2601. vars[n]['charselector']['*'] = length
  2602. elif 'len' in vars[n]['charselector']:
  2603. length = _eval_length(vars[n]['charselector']['len'],
  2604. params)
  2605. del vars[n]['charselector']['len']
  2606. vars[n]['charselector']['*'] = length
  2607. if not vars[n]['check']:
  2608. del vars[n]['check']
  2609. if flag and not vars[n]['depend']:
  2610. del vars[n]['depend']
  2611. if '=' in vars[n]:
  2612. if 'attrspec' not in vars[n]:
  2613. vars[n]['attrspec'] = []
  2614. if ('optional' not in vars[n]['attrspec']) and \
  2615. ('required' not in vars[n]['attrspec']):
  2616. vars[n]['attrspec'].append('optional')
  2617. if 'depend' not in vars[n]:
  2618. vars[n]['depend'] = []
  2619. for v, m in list(dep_matches.items()):
  2620. if m(vars[n]['=']):
  2621. vars[n]['depend'].append(v)
  2622. if not vars[n]['depend']:
  2623. del vars[n]['depend']
  2624. if isscalar(vars[n]):
  2625. vars[n]['='] = _eval_scalar(vars[n]['='], params)
  2626. for n in list(vars.keys()):
  2627. if n == block['name']: # n is block name
  2628. if 'note' in vars[n]:
  2629. block['note'] = vars[n]['note']
  2630. if block['block'] == 'function':
  2631. if 'result' in block and block['result'] in vars:
  2632. vars[n] = appenddecl(vars[n], vars[block['result']])
  2633. if 'prefix' in block:
  2634. pr = block['prefix']
  2635. ispure = 0
  2636. isrec = 1
  2637. pr1 = pr.replace('pure', '')
  2638. ispure = (not pr == pr1)
  2639. pr = pr1.replace('recursive', '')
  2640. isrec = (not pr == pr1)
  2641. m = typespattern[0].match(pr)
  2642. if m:
  2643. typespec, selector, attr, edecl = cracktypespec0(
  2644. m.group('this'), m.group('after'))
  2645. kindselect, charselect, typename = cracktypespec(
  2646. typespec, selector)
  2647. vars[n]['typespec'] = typespec
  2648. if kindselect:
  2649. if 'kind' in kindselect:
  2650. try:
  2651. kindselect['kind'] = eval(
  2652. kindselect['kind'], {}, params)
  2653. except Exception:
  2654. pass
  2655. vars[n]['kindselector'] = kindselect
  2656. if charselect:
  2657. vars[n]['charselector'] = charselect
  2658. if typename:
  2659. vars[n]['typename'] = typename
  2660. if ispure:
  2661. vars[n] = setattrspec(vars[n], 'pure')
  2662. if isrec:
  2663. vars[n] = setattrspec(vars[n], 'recursive')
  2664. else:
  2665. outmess(
  2666. 'analyzevars: prefix (%s) were not used\n' % repr(block['prefix']))
  2667. if not block['block'] in ['module', 'pythonmodule', 'python module', 'block data']:
  2668. if 'commonvars' in block:
  2669. neededvars = copy.copy(block['args'] + block['commonvars'])
  2670. else:
  2671. neededvars = copy.copy(block['args'])
  2672. for n in list(vars.keys()):
  2673. if l_or(isintent_callback, isintent_aux)(vars[n]):
  2674. neededvars.append(n)
  2675. if 'entry' in block:
  2676. neededvars.extend(list(block['entry'].keys()))
  2677. for k in list(block['entry'].keys()):
  2678. for n in block['entry'][k]:
  2679. if n not in neededvars:
  2680. neededvars.append(n)
  2681. if block['block'] == 'function':
  2682. if 'result' in block:
  2683. neededvars.append(block['result'])
  2684. else:
  2685. neededvars.append(block['name'])
  2686. if block['block'] in ['subroutine', 'function']:
  2687. name = block['name']
  2688. if name in vars and 'intent' in vars[name]:
  2689. block['intent'] = vars[name]['intent']
  2690. if block['block'] == 'type':
  2691. neededvars.extend(list(vars.keys()))
  2692. for n in list(vars.keys()):
  2693. if n not in neededvars:
  2694. del vars[n]
  2695. return vars
  2696. analyzeargs_re_1 = re.compile(r'\A[a-z]+[\w$]*\Z', re.I)
  2697. def expr2name(a, block, args=[]):
  2698. orig_a = a
  2699. a_is_expr = not analyzeargs_re_1.match(a)
  2700. if a_is_expr: # `a` is an expression
  2701. implicitrules, attrrules = buildimplicitrules(block)
  2702. at = determineexprtype(a, block['vars'], implicitrules)
  2703. na = 'e_'
  2704. for c in a:
  2705. c = c.lower()
  2706. if c not in string.ascii_lowercase + string.digits:
  2707. c = '_'
  2708. na = na + c
  2709. if na[-1] == '_':
  2710. na = na + 'e'
  2711. else:
  2712. na = na + '_e'
  2713. a = na
  2714. while a in block['vars'] or a in block['args']:
  2715. a = a + 'r'
  2716. if a in args:
  2717. k = 1
  2718. while a + str(k) in args:
  2719. k = k + 1
  2720. a = a + str(k)
  2721. if a_is_expr:
  2722. block['vars'][a] = at
  2723. else:
  2724. if a not in block['vars']:
  2725. if orig_a in block['vars']:
  2726. block['vars'][a] = block['vars'][orig_a]
  2727. else:
  2728. block['vars'][a] = {}
  2729. if 'externals' in block and orig_a in block['externals'] + block['interfaced']:
  2730. block['vars'][a] = setattrspec(block['vars'][a], 'external')
  2731. return a
  2732. def analyzeargs(block):
  2733. setmesstext(block)
  2734. implicitrules, attrrules = buildimplicitrules(block)
  2735. if 'args' not in block:
  2736. block['args'] = []
  2737. args = []
  2738. for a in block['args']:
  2739. a = expr2name(a, block, args)
  2740. args.append(a)
  2741. block['args'] = args
  2742. if 'entry' in block:
  2743. for k, args1 in list(block['entry'].items()):
  2744. for a in args1:
  2745. if a not in block['vars']:
  2746. block['vars'][a] = {}
  2747. for b in block['body']:
  2748. if b['name'] in args:
  2749. if 'externals' not in block:
  2750. block['externals'] = []
  2751. if b['name'] not in block['externals']:
  2752. block['externals'].append(b['name'])
  2753. if 'result' in block and block['result'] not in block['vars']:
  2754. block['vars'][block['result']] = {}
  2755. return block
  2756. determineexprtype_re_1 = re.compile(r'\A\(.+?[,].+?\)\Z', re.I)
  2757. determineexprtype_re_2 = re.compile(r'\A[+-]?\d+(_(?P<name>[\w]+)|)\Z', re.I)
  2758. determineexprtype_re_3 = re.compile(
  2759. r'\A[+-]?[\d.]+[\d+\-de.]*(_(?P<name>[\w]+)|)\Z', re.I)
  2760. determineexprtype_re_4 = re.compile(r'\A\(.*\)\Z', re.I)
  2761. determineexprtype_re_5 = re.compile(r'\A(?P<name>\w+)\s*\(.*?\)\s*\Z', re.I)
  2762. def _ensure_exprdict(r):
  2763. if isinstance(r, int):
  2764. return {'typespec': 'integer'}
  2765. if isinstance(r, float):
  2766. return {'typespec': 'real'}
  2767. if isinstance(r, complex):
  2768. return {'typespec': 'complex'}
  2769. if isinstance(r, dict):
  2770. return r
  2771. raise AssertionError(repr(r))
  2772. def determineexprtype(expr, vars, rules={}):
  2773. if expr in vars:
  2774. return _ensure_exprdict(vars[expr])
  2775. expr = expr.strip()
  2776. if determineexprtype_re_1.match(expr):
  2777. return {'typespec': 'complex'}
  2778. m = determineexprtype_re_2.match(expr)
  2779. if m:
  2780. if 'name' in m.groupdict() and m.group('name'):
  2781. outmess(
  2782. 'determineexprtype: selected kind types not supported (%s)\n' % repr(expr))
  2783. return {'typespec': 'integer'}
  2784. m = determineexprtype_re_3.match(expr)
  2785. if m:
  2786. if 'name' in m.groupdict() and m.group('name'):
  2787. outmess(
  2788. 'determineexprtype: selected kind types not supported (%s)\n' % repr(expr))
  2789. return {'typespec': 'real'}
  2790. for op in ['+', '-', '*', '/']:
  2791. for e in [x.strip() for x in markoutercomma(expr, comma=op).split('@' + op + '@')]:
  2792. if e in vars:
  2793. return _ensure_exprdict(vars[e])
  2794. t = {}
  2795. if determineexprtype_re_4.match(expr): # in parenthesis
  2796. t = determineexprtype(expr[1:-1], vars, rules)
  2797. else:
  2798. m = determineexprtype_re_5.match(expr)
  2799. if m:
  2800. rn = m.group('name')
  2801. t = determineexprtype(m.group('name'), vars, rules)
  2802. if t and 'attrspec' in t:
  2803. del t['attrspec']
  2804. if not t:
  2805. if rn[0] in rules:
  2806. return _ensure_exprdict(rules[rn[0]])
  2807. if expr[0] in '\'"':
  2808. return {'typespec': 'character', 'charselector': {'*': '*'}}
  2809. if not t:
  2810. outmess(
  2811. 'determineexprtype: could not determine expressions (%s) type.\n' % (repr(expr)))
  2812. return t
  2813. ######
  2814. def crack2fortrangen(block, tab='\n', as_interface=False):
  2815. global skipfuncs, onlyfuncs
  2816. setmesstext(block)
  2817. ret = ''
  2818. if isinstance(block, list):
  2819. for g in block:
  2820. if g and g['block'] in ['function', 'subroutine']:
  2821. if g['name'] in skipfuncs:
  2822. continue
  2823. if onlyfuncs and g['name'] not in onlyfuncs:
  2824. continue
  2825. ret = ret + crack2fortrangen(g, tab, as_interface=as_interface)
  2826. return ret
  2827. prefix = ''
  2828. name = ''
  2829. args = ''
  2830. blocktype = block['block']
  2831. if blocktype == 'program':
  2832. return ''
  2833. argsl = []
  2834. if 'name' in block:
  2835. name = block['name']
  2836. if 'args' in block:
  2837. vars = block['vars']
  2838. for a in block['args']:
  2839. a = expr2name(a, block, argsl)
  2840. if not isintent_callback(vars[a]):
  2841. argsl.append(a)
  2842. if block['block'] == 'function' or argsl:
  2843. args = '(%s)' % ','.join(argsl)
  2844. f2pyenhancements = ''
  2845. if 'f2pyenhancements' in block:
  2846. for k in list(block['f2pyenhancements'].keys()):
  2847. f2pyenhancements = '%s%s%s %s' % (
  2848. f2pyenhancements, tab + tabchar, k, block['f2pyenhancements'][k])
  2849. intent_lst = block.get('intent', [])[:]
  2850. if blocktype == 'function' and 'callback' in intent_lst:
  2851. intent_lst.remove('callback')
  2852. if intent_lst:
  2853. f2pyenhancements = '%s%sintent(%s) %s' %\
  2854. (f2pyenhancements, tab + tabchar,
  2855. ','.join(intent_lst), name)
  2856. use = ''
  2857. if 'use' in block:
  2858. use = use2fortran(block['use'], tab + tabchar)
  2859. common = ''
  2860. if 'common' in block:
  2861. common = common2fortran(block['common'], tab + tabchar)
  2862. if name == 'unknown_interface':
  2863. name = ''
  2864. result = ''
  2865. if 'result' in block:
  2866. result = ' result (%s)' % block['result']
  2867. if block['result'] not in argsl:
  2868. argsl.append(block['result'])
  2869. body = crack2fortrangen(block['body'], tab + tabchar)
  2870. vars = vars2fortran(
  2871. block, block['vars'], argsl, tab + tabchar, as_interface=as_interface)
  2872. mess = ''
  2873. if 'from' in block and not as_interface:
  2874. mess = '! in %s' % block['from']
  2875. if 'entry' in block:
  2876. entry_stmts = ''
  2877. for k, i in list(block['entry'].items()):
  2878. entry_stmts = '%s%sentry %s(%s)' \
  2879. % (entry_stmts, tab + tabchar, k, ','.join(i))
  2880. body = body + entry_stmts
  2881. if blocktype == 'block data' and name == '_BLOCK_DATA_':
  2882. name = ''
  2883. ret = '%s%s%s %s%s%s %s%s%s%s%s%s%send %s %s' % (
  2884. tab, prefix, blocktype, name, args, result, mess, f2pyenhancements, use, vars, common, body, tab, blocktype, name)
  2885. return ret
  2886. def common2fortran(common, tab=''):
  2887. ret = ''
  2888. for k in list(common.keys()):
  2889. if k == '_BLNK_':
  2890. ret = '%s%scommon %s' % (ret, tab, ','.join(common[k]))
  2891. else:
  2892. ret = '%s%scommon /%s/ %s' % (ret, tab, k, ','.join(common[k]))
  2893. return ret
  2894. def use2fortran(use, tab=''):
  2895. ret = ''
  2896. for m in list(use.keys()):
  2897. ret = '%s%suse %s,' % (ret, tab, m)
  2898. if use[m] == {}:
  2899. if ret and ret[-1] == ',':
  2900. ret = ret[:-1]
  2901. continue
  2902. if 'only' in use[m] and use[m]['only']:
  2903. ret = '%s only:' % (ret)
  2904. if 'map' in use[m] and use[m]['map']:
  2905. c = ' '
  2906. for k in list(use[m]['map'].keys()):
  2907. if k == use[m]['map'][k]:
  2908. ret = '%s%s%s' % (ret, c, k)
  2909. c = ','
  2910. else:
  2911. ret = '%s%s%s=>%s' % (ret, c, k, use[m]['map'][k])
  2912. c = ','
  2913. if ret and ret[-1] == ',':
  2914. ret = ret[:-1]
  2915. return ret
  2916. def true_intent_list(var):
  2917. lst = var['intent']
  2918. ret = []
  2919. for intent in lst:
  2920. try:
  2921. f = globals()['isintent_%s' % intent]
  2922. except KeyError:
  2923. pass
  2924. else:
  2925. if f(var):
  2926. ret.append(intent)
  2927. return ret
  2928. def vars2fortran(block, vars, args, tab='', as_interface=False):
  2929. """
  2930. TODO:
  2931. public sub
  2932. ...
  2933. """
  2934. setmesstext(block)
  2935. ret = ''
  2936. nout = []
  2937. for a in args:
  2938. if a in block['vars']:
  2939. nout.append(a)
  2940. if 'commonvars' in block:
  2941. for a in block['commonvars']:
  2942. if a in vars:
  2943. if a not in nout:
  2944. nout.append(a)
  2945. else:
  2946. errmess(
  2947. 'vars2fortran: Confused?!: "%s" is not defined in vars.\n' % a)
  2948. if 'varnames' in block:
  2949. nout.extend(block['varnames'])
  2950. if not as_interface:
  2951. for a in list(vars.keys()):
  2952. if a not in nout:
  2953. nout.append(a)
  2954. for a in nout:
  2955. if 'depend' in vars[a]:
  2956. for d in vars[a]['depend']:
  2957. if d in vars and 'depend' in vars[d] and a in vars[d]['depend']:
  2958. errmess(
  2959. 'vars2fortran: Warning: cross-dependence between variables "%s" and "%s"\n' % (a, d))
  2960. if 'externals' in block and a in block['externals']:
  2961. if isintent_callback(vars[a]):
  2962. ret = '%s%sintent(callback) %s' % (ret, tab, a)
  2963. ret = '%s%sexternal %s' % (ret, tab, a)
  2964. if isoptional(vars[a]):
  2965. ret = '%s%soptional %s' % (ret, tab, a)
  2966. if a in vars and 'typespec' not in vars[a]:
  2967. continue
  2968. cont = 1
  2969. for b in block['body']:
  2970. if a == b['name'] and b['block'] == 'function':
  2971. cont = 0
  2972. break
  2973. if cont:
  2974. continue
  2975. if a not in vars:
  2976. show(vars)
  2977. outmess('vars2fortran: No definition for argument "%s".\n' % a)
  2978. continue
  2979. if a == block['name'] and not block['block'] == 'function':
  2980. continue
  2981. if 'typespec' not in vars[a]:
  2982. if 'attrspec' in vars[a] and 'external' in vars[a]['attrspec']:
  2983. if a in args:
  2984. ret = '%s%sexternal %s' % (ret, tab, a)
  2985. continue
  2986. show(vars[a])
  2987. outmess('vars2fortran: No typespec for argument "%s".\n' % a)
  2988. continue
  2989. vardef = vars[a]['typespec']
  2990. if vardef == 'type' and 'typename' in vars[a]:
  2991. vardef = '%s(%s)' % (vardef, vars[a]['typename'])
  2992. selector = {}
  2993. if 'kindselector' in vars[a]:
  2994. selector = vars[a]['kindselector']
  2995. elif 'charselector' in vars[a]:
  2996. selector = vars[a]['charselector']
  2997. if '*' in selector:
  2998. if selector['*'] in ['*', ':']:
  2999. vardef = '%s*(%s)' % (vardef, selector['*'])
  3000. else:
  3001. vardef = '%s*%s' % (vardef, selector['*'])
  3002. else:
  3003. if 'len' in selector:
  3004. vardef = '%s(len=%s' % (vardef, selector['len'])
  3005. if 'kind' in selector:
  3006. vardef = '%s,kind=%s)' % (vardef, selector['kind'])
  3007. else:
  3008. vardef = '%s)' % (vardef)
  3009. elif 'kind' in selector:
  3010. vardef = '%s(kind=%s)' % (vardef, selector['kind'])
  3011. c = ' '
  3012. if 'attrspec' in vars[a]:
  3013. attr = [l for l in vars[a]['attrspec']
  3014. if l not in ['external']]
  3015. if attr:
  3016. vardef = '%s, %s' % (vardef, ','.join(attr))
  3017. c = ','
  3018. if 'dimension' in vars[a]:
  3019. vardef = '%s%sdimension(%s)' % (
  3020. vardef, c, ','.join(vars[a]['dimension']))
  3021. c = ','
  3022. if 'intent' in vars[a]:
  3023. lst = true_intent_list(vars[a])
  3024. if lst:
  3025. vardef = '%s%sintent(%s)' % (vardef, c, ','.join(lst))
  3026. c = ','
  3027. if 'check' in vars[a]:
  3028. vardef = '%s%scheck(%s)' % (vardef, c, ','.join(vars[a]['check']))
  3029. c = ','
  3030. if 'depend' in vars[a]:
  3031. vardef = '%s%sdepend(%s)' % (
  3032. vardef, c, ','.join(vars[a]['depend']))
  3033. c = ','
  3034. if '=' in vars[a]:
  3035. v = vars[a]['=']
  3036. if vars[a]['typespec'] in ['complex', 'double complex']:
  3037. try:
  3038. v = eval(v)
  3039. v = '(%s,%s)' % (v.real, v.imag)
  3040. except Exception:
  3041. pass
  3042. vardef = '%s :: %s=%s' % (vardef, a, v)
  3043. else:
  3044. vardef = '%s :: %s' % (vardef, a)
  3045. ret = '%s%s%s' % (ret, tab, vardef)
  3046. return ret
  3047. ######
  3048. def crackfortran(files):
  3049. global usermodules
  3050. outmess('Reading fortran codes...\n', 0)
  3051. readfortrancode(files, crackline)
  3052. outmess('Post-processing...\n', 0)
  3053. usermodules = []
  3054. postlist = postcrack(grouplist[0])
  3055. outmess('Post-processing (stage 2)...\n', 0)
  3056. postlist = postcrack2(postlist)
  3057. return usermodules + postlist
  3058. def crack2fortran(block):
  3059. global f2py_version
  3060. pyf = crack2fortrangen(block) + '\n'
  3061. header = """! -*- f90 -*-
  3062. ! Note: the context of this file is case sensitive.
  3063. """
  3064. footer = """
  3065. ! This file was auto-generated with f2py (version:%s).
  3066. ! See http://cens.ioc.ee/projects/f2py2e/
  3067. """ % (f2py_version)
  3068. return header + pyf + footer
  3069. if __name__ == "__main__":
  3070. files = []
  3071. funcs = []
  3072. f = 1
  3073. f2 = 0
  3074. f3 = 0
  3075. showblocklist = 0
  3076. for l in sys.argv[1:]:
  3077. if l == '':
  3078. pass
  3079. elif l[0] == ':':
  3080. f = 0
  3081. elif l == '-quiet':
  3082. quiet = 1
  3083. verbose = 0
  3084. elif l == '-verbose':
  3085. verbose = 2
  3086. quiet = 0
  3087. elif l == '-fix':
  3088. if strictf77:
  3089. outmess(
  3090. 'Use option -f90 before -fix if Fortran 90 code is in fix form.\n', 0)
  3091. skipemptyends = 1
  3092. sourcecodeform = 'fix'
  3093. elif l == '-skipemptyends':
  3094. skipemptyends = 1
  3095. elif l == '--ignore-contains':
  3096. ignorecontains = 1
  3097. elif l == '-f77':
  3098. strictf77 = 1
  3099. sourcecodeform = 'fix'
  3100. elif l == '-f90':
  3101. strictf77 = 0
  3102. sourcecodeform = 'free'
  3103. skipemptyends = 1
  3104. elif l == '-h':
  3105. f2 = 1
  3106. elif l == '-show':
  3107. showblocklist = 1
  3108. elif l == '-m':
  3109. f3 = 1
  3110. elif l[0] == '-':
  3111. errmess('Unknown option %s\n' % repr(l))
  3112. elif f2:
  3113. f2 = 0
  3114. pyffilename = l
  3115. elif f3:
  3116. f3 = 0
  3117. f77modulename = l
  3118. elif f:
  3119. try:
  3120. open(l).close()
  3121. files.append(l)
  3122. except IOError as detail:
  3123. errmess('IOError: %s\n' % str(detail))
  3124. else:
  3125. funcs.append(l)
  3126. if not strictf77 and f77modulename and not skipemptyends:
  3127. outmess("""\
  3128. Warning: You have specified module name for non Fortran 77 code
  3129. that should not need one (expect if you are scanning F90 code
  3130. for non module blocks but then you should use flag -skipemptyends
  3131. and also be sure that the files do not contain programs without program statement).
  3132. """, 0)
  3133. postlist = crackfortran(files)
  3134. if pyffilename:
  3135. outmess('Writing fortran code to file %s\n' % repr(pyffilename), 0)
  3136. pyf = crack2fortran(postlist)
  3137. with open(pyffilename, 'w') as f:
  3138. f.write(pyf)
  3139. if showblocklist:
  3140. show(postlist)