crackfortran.py 126 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345
  1. #!/usr/bin/env python
  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. from __future__ import division, absolute_import, print_function
  132. import sys
  133. import string
  134. import fileinput
  135. import re
  136. import os
  137. import copy
  138. import platform
  139. from . import __version__
  140. # The eviroment provided by auxfuncs.py is needed for some calls to eval.
  141. # As the needed functions cannot be determined by static inspection of the
  142. # code, it is safest to use import * pending a major refactoring of f2py.
  143. from .auxfuncs import *
  144. f2py_version = __version__.version
  145. # Global flags:
  146. strictf77 = 1 # Ignore `!' comments unless line[0]=='!'
  147. sourcecodeform = 'fix' # 'fix','free'
  148. quiet = 0 # Be verbose if 0 (Obsolete: not used any more)
  149. verbose = 1 # Be quiet if 0, extra verbose if > 1.
  150. tabchar = 4 * ' '
  151. pyffilename = ''
  152. f77modulename = ''
  153. skipemptyends = 0 # for old F77 programs without 'program' statement
  154. ignorecontains = 1
  155. dolowercase = 1
  156. debug = []
  157. # Global variables
  158. beginpattern = ''
  159. currentfilename = ''
  160. expectbegin = 1
  161. f90modulevars = {}
  162. filepositiontext = ''
  163. gotnextfile = 1
  164. groupcache = None
  165. groupcounter = 0
  166. grouplist = {groupcounter: []}
  167. groupname = ''
  168. include_paths = []
  169. neededmodule = -1
  170. onlyfuncs = []
  171. previous_context = None
  172. skipblocksuntil = -1
  173. skipfuncs = []
  174. skipfunctions = []
  175. usermodules = []
  176. def reset_global_f2py_vars():
  177. global groupcounter, grouplist, neededmodule, expectbegin
  178. global skipblocksuntil, usermodules, f90modulevars, gotnextfile
  179. global filepositiontext, currentfilename, skipfunctions, skipfuncs
  180. global onlyfuncs, include_paths, previous_context
  181. global strictf77, sourcecodeform, quiet, verbose, tabchar, pyffilename
  182. global f77modulename, skipemptyends, ignorecontains, dolowercase, debug
  183. # flags
  184. strictf77 = 1
  185. sourcecodeform = 'fix'
  186. quiet = 0
  187. verbose = 1
  188. tabchar = 4 * ' '
  189. pyffilename = ''
  190. f77modulename = ''
  191. skipemptyends = 0
  192. ignorecontains = 1
  193. dolowercase = 1
  194. debug = []
  195. # variables
  196. groupcounter = 0
  197. grouplist = {groupcounter: []}
  198. neededmodule = -1
  199. expectbegin = 1
  200. skipblocksuntil = -1
  201. usermodules = []
  202. f90modulevars = {}
  203. gotnextfile = 1
  204. filepositiontext = ''
  205. currentfilename = ''
  206. skipfunctions = []
  207. skipfuncs = []
  208. onlyfuncs = []
  209. include_paths = []
  210. previous_context = None
  211. def outmess(line, flag=1):
  212. global filepositiontext
  213. if not verbose:
  214. return
  215. if not quiet:
  216. if flag:
  217. sys.stdout.write(filepositiontext)
  218. sys.stdout.write(line)
  219. re._MAXCACHE = 50
  220. defaultimplicitrules = {}
  221. for c in "abcdefghopqrstuvwxyz$_":
  222. defaultimplicitrules[c] = {'typespec': 'real'}
  223. for c in "ijklmn":
  224. defaultimplicitrules[c] = {'typespec': 'integer'}
  225. del c
  226. badnames = {}
  227. invbadnames = {}
  228. for n in ['int', 'double', 'float', 'char', 'short', 'long', 'void', 'case', 'while',
  229. 'return', 'signed', 'unsigned', 'if', 'for', 'typedef', 'sizeof', 'union',
  230. 'struct', 'static', 'register', 'new', 'break', 'do', 'goto', 'switch',
  231. 'continue', 'else', 'inline', 'extern', 'delete', 'const', 'auto',
  232. 'len', 'rank', 'shape', 'index', 'slen', 'size', '_i',
  233. 'max', 'min',
  234. 'flen', 'fshape',
  235. 'string', 'complex_double', 'float_double', 'stdin', 'stderr', 'stdout',
  236. 'type', 'default']:
  237. badnames[n] = n + '_bn'
  238. invbadnames[n + '_bn'] = n
  239. def rmbadname1(name):
  240. if name in badnames:
  241. errmess('rmbadname1: Replacing "%s" with "%s".\n' %
  242. (name, badnames[name]))
  243. return badnames[name]
  244. return name
  245. def rmbadname(names):
  246. return [rmbadname1(_m) for _m in names]
  247. def undo_rmbadname1(name):
  248. if name in invbadnames:
  249. errmess('undo_rmbadname1: Replacing "%s" with "%s".\n'
  250. % (name, invbadnames[name]))
  251. return invbadnames[name]
  252. return name
  253. def undo_rmbadname(names):
  254. return [undo_rmbadname1(_m) for _m in names]
  255. def getextension(name):
  256. i = name.rfind('.')
  257. if i == -1:
  258. return ''
  259. if '\\' in name[i:]:
  260. return ''
  261. if '/' in name[i:]:
  262. return ''
  263. return name[i + 1:]
  264. is_f_file = re.compile(r'.*[.](for|ftn|f77|f)\Z', re.I).match
  265. _has_f_header = re.compile(r'-[*]-\s*fortran\s*-[*]-', re.I).search
  266. _has_f90_header = re.compile(r'-[*]-\s*f90\s*-[*]-', re.I).search
  267. _has_fix_header = re.compile(r'-[*]-\s*fix\s*-[*]-', re.I).search
  268. _free_f90_start = re.compile(r'[^c*]\s*[^\s\d\t]', re.I).match
  269. def is_free_format(file):
  270. """Check if file is in free format Fortran."""
  271. # f90 allows both fixed and free format, assuming fixed unless
  272. # signs of free format are detected.
  273. result = 0
  274. with open(file, 'r') as f:
  275. line = f.readline()
  276. n = 15 # the number of non-comment lines to scan for hints
  277. if _has_f_header(line):
  278. n = 0
  279. elif _has_f90_header(line):
  280. n = 0
  281. result = 1
  282. while n > 0 and line:
  283. if line[0] != '!' and line.strip():
  284. n -= 1
  285. if (line[0] != '\t' and _free_f90_start(line[:5])) or line[-2:-1] == '&':
  286. result = 1
  287. break
  288. line = f.readline()
  289. return result
  290. # Read fortran (77,90) code
  291. def readfortrancode(ffile, dowithline=show, istop=1):
  292. """
  293. Read fortran codes from files and
  294. 1) Get rid of comments, line continuations, and empty lines; lower cases.
  295. 2) Call dowithline(line) on every line.
  296. 3) Recursively call itself when statement \"include '<filename>'\" is met.
  297. """
  298. global gotnextfile, filepositiontext, currentfilename, sourcecodeform, strictf77
  299. global beginpattern, quiet, verbose, dolowercase, include_paths
  300. if not istop:
  301. saveglobals = gotnextfile, filepositiontext, currentfilename, sourcecodeform, strictf77,\
  302. beginpattern, quiet, verbose, dolowercase
  303. if ffile == []:
  304. return
  305. localdolowercase = dolowercase
  306. cont = 0
  307. finalline = ''
  308. ll = ''
  309. includeline = re.compile(
  310. r'\s*include\s*(\'|")(?P<name>[^\'"]*)(\'|")', re.I)
  311. cont1 = re.compile(r'(?P<line>.*)&\s*\Z')
  312. cont2 = re.compile(r'(\s*&|)(?P<line>.*)')
  313. mline_mark = re.compile(r".*?'''")
  314. if istop:
  315. dowithline('', -1)
  316. ll, l1 = '', ''
  317. spacedigits = [' '] + [str(_m) for _m in range(10)]
  318. filepositiontext = ''
  319. fin = fileinput.FileInput(ffile)
  320. while True:
  321. l = fin.readline()
  322. if not l:
  323. break
  324. if fin.isfirstline():
  325. filepositiontext = ''
  326. currentfilename = fin.filename()
  327. gotnextfile = 1
  328. l1 = l
  329. strictf77 = 0
  330. sourcecodeform = 'fix'
  331. ext = os.path.splitext(currentfilename)[1]
  332. if is_f_file(currentfilename) and \
  333. not (_has_f90_header(l) or _has_fix_header(l)):
  334. strictf77 = 1
  335. elif is_free_format(currentfilename) and not _has_fix_header(l):
  336. sourcecodeform = 'free'
  337. if strictf77:
  338. beginpattern = beginpattern77
  339. else:
  340. beginpattern = beginpattern90
  341. outmess('\tReading file %s (format:%s%s)\n'
  342. % (repr(currentfilename), sourcecodeform,
  343. strictf77 and ',strict' or ''))
  344. l = l.expandtabs().replace('\xa0', ' ')
  345. # Get rid of newline characters
  346. while not l == '':
  347. if l[-1] not in "\n\r\f":
  348. break
  349. l = l[:-1]
  350. if not strictf77:
  351. (l, rl) = split_by_unquoted(l, '!')
  352. l += ' '
  353. if rl[:5].lower() == '!f2py': # f2py directive
  354. l, _ = split_by_unquoted(l + 4 * ' ' + rl[5:], '!')
  355. if l.strip() == '': # Skip empty line
  356. cont = 0
  357. continue
  358. if sourcecodeform == 'fix':
  359. if l[0] in ['*', 'c', '!', 'C', '#']:
  360. if l[1:5].lower() == 'f2py': # f2py directive
  361. l = ' ' + l[5:]
  362. else: # Skip comment line
  363. cont = 0
  364. continue
  365. elif strictf77:
  366. if len(l) > 72:
  367. l = l[:72]
  368. if not (l[0] in spacedigits):
  369. raise Exception('readfortrancode: Found non-(space,digit) char '
  370. 'in the first column.\n\tAre you sure that '
  371. 'this code is in fix form?\n\tline=%s' % repr(l))
  372. if (not cont or strictf77) and (len(l) > 5 and not l[5] == ' '):
  373. # Continuation of a previous line
  374. ll = ll + l[6:]
  375. finalline = ''
  376. origfinalline = ''
  377. else:
  378. if not strictf77:
  379. # F90 continuation
  380. r = cont1.match(l)
  381. if r:
  382. l = r.group('line') # Continuation follows ..
  383. if cont:
  384. ll = ll + cont2.match(l).group('line')
  385. finalline = ''
  386. origfinalline = ''
  387. else:
  388. # clean up line beginning from possible digits.
  389. l = ' ' + l[5:]
  390. if localdolowercase:
  391. finalline = ll.lower()
  392. else:
  393. finalline = ll
  394. origfinalline = ll
  395. ll = l
  396. cont = (r is not None)
  397. else:
  398. # clean up line beginning from possible digits.
  399. l = ' ' + l[5:]
  400. if localdolowercase:
  401. finalline = ll.lower()
  402. else:
  403. finalline = ll
  404. origfinalline = ll
  405. ll = l
  406. elif sourcecodeform == 'free':
  407. if not cont and ext == '.pyf' and mline_mark.match(l):
  408. l = l + '\n'
  409. while True:
  410. lc = fin.readline()
  411. if not lc:
  412. errmess(
  413. 'Unexpected end of file when reading multiline\n')
  414. break
  415. l = l + lc
  416. if mline_mark.match(lc):
  417. break
  418. l = l.rstrip()
  419. r = cont1.match(l)
  420. if r:
  421. l = r.group('line') # Continuation follows ..
  422. if cont:
  423. ll = ll + cont2.match(l).group('line')
  424. finalline = ''
  425. origfinalline = ''
  426. else:
  427. if localdolowercase:
  428. finalline = ll.lower()
  429. else:
  430. finalline = ll
  431. origfinalline = ll
  432. ll = l
  433. cont = (r is not None)
  434. else:
  435. raise ValueError(
  436. "Flag sourcecodeform must be either 'fix' or 'free': %s" % repr(sourcecodeform))
  437. filepositiontext = 'Line #%d in %s:"%s"\n\t' % (
  438. fin.filelineno() - 1, currentfilename, l1)
  439. m = includeline.match(origfinalline)
  440. if m:
  441. fn = m.group('name')
  442. if os.path.isfile(fn):
  443. readfortrancode(fn, dowithline=dowithline, istop=0)
  444. else:
  445. include_dirs = [
  446. os.path.dirname(currentfilename)] + include_paths
  447. foundfile = 0
  448. for inc_dir in include_dirs:
  449. fn1 = os.path.join(inc_dir, fn)
  450. if os.path.isfile(fn1):
  451. foundfile = 1
  452. readfortrancode(fn1, dowithline=dowithline, istop=0)
  453. break
  454. if not foundfile:
  455. outmess('readfortrancode: could not find include file %s in %s. Ignoring.\n' % (
  456. repr(fn), os.pathsep.join(include_dirs)))
  457. else:
  458. dowithline(finalline)
  459. l1 = ll
  460. if localdolowercase:
  461. finalline = ll.lower()
  462. else:
  463. finalline = ll
  464. origfinalline = ll
  465. filepositiontext = 'Line #%d in %s:"%s"\n\t' % (
  466. fin.filelineno() - 1, currentfilename, l1)
  467. m = includeline.match(origfinalline)
  468. if m:
  469. fn = m.group('name')
  470. if os.path.isfile(fn):
  471. readfortrancode(fn, dowithline=dowithline, istop=0)
  472. else:
  473. include_dirs = [os.path.dirname(currentfilename)] + include_paths
  474. foundfile = 0
  475. for inc_dir in include_dirs:
  476. fn1 = os.path.join(inc_dir, fn)
  477. if os.path.isfile(fn1):
  478. foundfile = 1
  479. readfortrancode(fn1, dowithline=dowithline, istop=0)
  480. break
  481. if not foundfile:
  482. outmess('readfortrancode: could not find include file %s in %s. Ignoring.\n' % (
  483. repr(fn), os.pathsep.join(include_dirs)))
  484. else:
  485. dowithline(finalline)
  486. filepositiontext = ''
  487. fin.close()
  488. if istop:
  489. dowithline('', 1)
  490. else:
  491. gotnextfile, filepositiontext, currentfilename, sourcecodeform, strictf77,\
  492. beginpattern, quiet, verbose, dolowercase = saveglobals
  493. # Crack line
  494. beforethisafter = r'\s*(?P<before>%s(?=\s*(\b(%s)\b)))' + \
  495. r'\s*(?P<this>(\b(%s)\b))' + \
  496. r'\s*(?P<after>%s)\s*\Z'
  497. ##
  498. fortrantypes = r'character|logical|integer|real|complex|double\s*(precision\s*(complex|)|complex)|type(?=\s*\([\w\s,=(*)]*\))|byte'
  499. typespattern = re.compile(
  500. beforethisafter % ('', fortrantypes, fortrantypes, '.*'), re.I), 'type'
  501. typespattern4implicit = re.compile(beforethisafter % (
  502. '', fortrantypes + '|static|automatic|undefined', fortrantypes + '|static|automatic|undefined', '.*'), re.I)
  503. #
  504. functionpattern = re.compile(beforethisafter % (
  505. r'([a-z]+[\w\s(=*+-/)]*?|)', 'function', 'function', '.*'), re.I), 'begin'
  506. subroutinepattern = re.compile(beforethisafter % (
  507. r'[a-z\s]*?', 'subroutine', 'subroutine', '.*'), re.I), 'begin'
  508. # modulepattern=re.compile(beforethisafter%('[a-z\s]*?','module','module','.*'),re.I),'begin'
  509. #
  510. groupbegins77 = r'program|block\s*data'
  511. beginpattern77 = re.compile(
  512. beforethisafter % ('', groupbegins77, groupbegins77, '.*'), re.I), 'begin'
  513. groupbegins90 = groupbegins77 + \
  514. r'|module(?!\s*procedure)|python\s*module|interface|type(?!\s*\()'
  515. beginpattern90 = re.compile(
  516. beforethisafter % ('', groupbegins90, groupbegins90, '.*'), re.I), 'begin'
  517. groupends = r'end|endprogram|endblockdata|endmodule|endpythonmodule|endinterface'
  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. intrisicpattern = re.compile(
  540. beforethisafter % ('', 'intrisic', 'intrisic', '.*'), re.I), 'intrisic'
  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. intrisicpattern,
  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', 'intrisic']:
  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', 'intrisic']:
  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' and 'private' not in decl['attrspec']:
  1663. decl['attrspec'].append(attr)
  1664. elif attr == 'private' and 'public' not in decl['attrspec']:
  1665. decl['attrspec'].append(attr)
  1666. else:
  1667. decl['attrspec'].append(attr)
  1668. return decl
  1669. def setkindselector(decl, sel, force=0):
  1670. if not decl:
  1671. decl = {}
  1672. if not sel:
  1673. return decl
  1674. if 'kindselector' not in decl:
  1675. decl['kindselector'] = sel
  1676. return decl
  1677. for k in list(sel.keys()):
  1678. if force or k not in decl['kindselector']:
  1679. decl['kindselector'][k] = sel[k]
  1680. return decl
  1681. def setcharselector(decl, sel, force=0):
  1682. if not decl:
  1683. decl = {}
  1684. if not sel:
  1685. return decl
  1686. if 'charselector' not in decl:
  1687. decl['charselector'] = sel
  1688. return decl
  1689. for k in list(sel.keys()):
  1690. if force or k not in decl['charselector']:
  1691. decl['charselector'][k] = sel[k]
  1692. return decl
  1693. def getblockname(block, unknown='unknown'):
  1694. if 'name' in block:
  1695. return block['name']
  1696. return unknown
  1697. # post processing
  1698. def setmesstext(block):
  1699. global filepositiontext
  1700. try:
  1701. filepositiontext = 'In: %s:%s\n' % (block['from'], block['name'])
  1702. except Exception:
  1703. pass
  1704. def get_usedict(block):
  1705. usedict = {}
  1706. if 'parent_block' in block:
  1707. usedict = get_usedict(block['parent_block'])
  1708. if 'use' in block:
  1709. usedict.update(block['use'])
  1710. return usedict
  1711. def get_useparameters(block, param_map=None):
  1712. global f90modulevars
  1713. if param_map is None:
  1714. param_map = {}
  1715. usedict = get_usedict(block)
  1716. if not usedict:
  1717. return param_map
  1718. for usename, mapping in list(usedict.items()):
  1719. usename = usename.lower()
  1720. if usename not in f90modulevars:
  1721. outmess('get_useparameters: no module %s info used by %s\n' %
  1722. (usename, block.get('name')))
  1723. continue
  1724. mvars = f90modulevars[usename]
  1725. params = get_parameters(mvars)
  1726. if not params:
  1727. continue
  1728. # XXX: apply mapping
  1729. if mapping:
  1730. errmess('get_useparameters: mapping for %s not impl.' % (mapping))
  1731. for k, v in list(params.items()):
  1732. if k in param_map:
  1733. outmess('get_useparameters: overriding parameter %s with'
  1734. ' value from module %s' % (repr(k), repr(usename)))
  1735. param_map[k] = v
  1736. return param_map
  1737. def postcrack2(block, tab='', param_map=None):
  1738. global f90modulevars
  1739. if not f90modulevars:
  1740. return block
  1741. if isinstance(block, list):
  1742. ret = [postcrack2(g, tab=tab + '\t', param_map=param_map)
  1743. for g in block]
  1744. return ret
  1745. setmesstext(block)
  1746. outmess('%sBlock: %s\n' % (tab, block['name']), 0)
  1747. if param_map is None:
  1748. param_map = get_useparameters(block)
  1749. if param_map is not None and 'vars' in block:
  1750. vars = block['vars']
  1751. for n in list(vars.keys()):
  1752. var = vars[n]
  1753. if 'kindselector' in var:
  1754. kind = var['kindselector']
  1755. if 'kind' in kind:
  1756. val = kind['kind']
  1757. if val in param_map:
  1758. kind['kind'] = param_map[val]
  1759. new_body = [postcrack2(b, tab=tab + '\t', param_map=param_map)
  1760. for b in block['body']]
  1761. block['body'] = new_body
  1762. return block
  1763. def postcrack(block, args=None, tab=''):
  1764. """
  1765. TODO:
  1766. function return values
  1767. determine expression types if in argument list
  1768. """
  1769. global usermodules, onlyfunctions
  1770. if isinstance(block, list):
  1771. gret = []
  1772. uret = []
  1773. for g in block:
  1774. setmesstext(g)
  1775. g = postcrack(g, tab=tab + '\t')
  1776. # sort user routines to appear first
  1777. if 'name' in g and '__user__' in g['name']:
  1778. uret.append(g)
  1779. else:
  1780. gret.append(g)
  1781. return uret + gret
  1782. setmesstext(block)
  1783. if not isinstance(block, dict) and 'block' not in block:
  1784. raise Exception('postcrack: Expected block dictionary instead of ' +
  1785. str(block))
  1786. if 'name' in block and not block['name'] == 'unknown_interface':
  1787. outmess('%sBlock: %s\n' % (tab, block['name']), 0)
  1788. block = analyzeargs(block)
  1789. block = analyzecommon(block)
  1790. block['vars'] = analyzevars(block)
  1791. block['sortvars'] = sortvarnames(block['vars'])
  1792. if 'args' in block and block['args']:
  1793. args = block['args']
  1794. block['body'] = analyzebody(block, args, tab=tab)
  1795. userisdefined = []
  1796. if 'use' in block:
  1797. useblock = block['use']
  1798. for k in list(useblock.keys()):
  1799. if '__user__' in k:
  1800. userisdefined.append(k)
  1801. else:
  1802. useblock = {}
  1803. name = ''
  1804. if 'name' in block:
  1805. name = block['name']
  1806. # and not userisdefined: # Build a __user__ module
  1807. if 'externals' in block and block['externals']:
  1808. interfaced = []
  1809. if 'interfaced' in block:
  1810. interfaced = block['interfaced']
  1811. mvars = copy.copy(block['vars'])
  1812. if name:
  1813. mname = name + '__user__routines'
  1814. else:
  1815. mname = 'unknown__user__routines'
  1816. if mname in userisdefined:
  1817. i = 1
  1818. while '%s_%i' % (mname, i) in userisdefined:
  1819. i = i + 1
  1820. mname = '%s_%i' % (mname, i)
  1821. interface = {'block': 'interface', 'body': [],
  1822. 'vars': {}, 'name': name + '_user_interface'}
  1823. for e in block['externals']:
  1824. if e in interfaced:
  1825. edef = []
  1826. j = -1
  1827. for b in block['body']:
  1828. j = j + 1
  1829. if b['block'] == 'interface':
  1830. i = -1
  1831. for bb in b['body']:
  1832. i = i + 1
  1833. if 'name' in bb and bb['name'] == e:
  1834. edef = copy.copy(bb)
  1835. del b['body'][i]
  1836. break
  1837. if edef:
  1838. if not b['body']:
  1839. del block['body'][j]
  1840. del interfaced[interfaced.index(e)]
  1841. break
  1842. interface['body'].append(edef)
  1843. else:
  1844. if e in mvars and not isexternal(mvars[e]):
  1845. interface['vars'][e] = mvars[e]
  1846. if interface['vars'] or interface['body']:
  1847. block['interfaced'] = interfaced
  1848. mblock = {'block': 'python module', 'body': [
  1849. interface], 'vars': {}, 'name': mname, 'interfaced': block['externals']}
  1850. useblock[mname] = {}
  1851. usermodules.append(mblock)
  1852. if useblock:
  1853. block['use'] = useblock
  1854. return block
  1855. def sortvarnames(vars):
  1856. indep = []
  1857. dep = []
  1858. for v in list(vars.keys()):
  1859. if 'depend' in vars[v] and vars[v]['depend']:
  1860. dep.append(v)
  1861. else:
  1862. indep.append(v)
  1863. n = len(dep)
  1864. i = 0
  1865. while dep: # XXX: How to catch dependence cycles correctly?
  1866. v = dep[0]
  1867. fl = 0
  1868. for w in dep[1:]:
  1869. if w in vars[v]['depend']:
  1870. fl = 1
  1871. break
  1872. if fl:
  1873. dep = dep[1:] + [v]
  1874. i = i + 1
  1875. if i > n:
  1876. errmess('sortvarnames: failed to compute dependencies because'
  1877. ' of cyclic dependencies between '
  1878. + ', '.join(dep) + '\n')
  1879. indep = indep + dep
  1880. break
  1881. else:
  1882. indep.append(v)
  1883. dep = dep[1:]
  1884. n = len(dep)
  1885. i = 0
  1886. return indep
  1887. def analyzecommon(block):
  1888. if not hascommon(block):
  1889. return block
  1890. commonvars = []
  1891. for k in list(block['common'].keys()):
  1892. comvars = []
  1893. for e in block['common'][k]:
  1894. m = re.match(
  1895. r'\A\s*\b(?P<name>.*?)\b\s*(\((?P<dims>.*?)\)|)\s*\Z', e, re.I)
  1896. if m:
  1897. dims = []
  1898. if m.group('dims'):
  1899. dims = [x.strip()
  1900. for x in markoutercomma(m.group('dims')).split('@,@')]
  1901. n = rmbadname1(m.group('name').strip())
  1902. if n in block['vars']:
  1903. if 'attrspec' in block['vars'][n]:
  1904. block['vars'][n]['attrspec'].append(
  1905. 'dimension(%s)' % (','.join(dims)))
  1906. else:
  1907. block['vars'][n]['attrspec'] = [
  1908. 'dimension(%s)' % (','.join(dims))]
  1909. else:
  1910. if dims:
  1911. block['vars'][n] = {
  1912. 'attrspec': ['dimension(%s)' % (','.join(dims))]}
  1913. else:
  1914. block['vars'][n] = {}
  1915. if n not in commonvars:
  1916. commonvars.append(n)
  1917. else:
  1918. n = e
  1919. errmess(
  1920. 'analyzecommon: failed to extract "<name>[(<dims>)]" from "%s" in common /%s/.\n' % (e, k))
  1921. comvars.append(n)
  1922. block['common'][k] = comvars
  1923. if 'commonvars' not in block:
  1924. block['commonvars'] = commonvars
  1925. else:
  1926. block['commonvars'] = block['commonvars'] + commonvars
  1927. return block
  1928. def analyzebody(block, args, tab=''):
  1929. global usermodules, skipfuncs, onlyfuncs, f90modulevars
  1930. setmesstext(block)
  1931. body = []
  1932. for b in block['body']:
  1933. b['parent_block'] = block
  1934. if b['block'] in ['function', 'subroutine']:
  1935. if args is not None and b['name'] not in args:
  1936. continue
  1937. else:
  1938. as_ = b['args']
  1939. if b['name'] in skipfuncs:
  1940. continue
  1941. if onlyfuncs and b['name'] not in onlyfuncs:
  1942. continue
  1943. b['saved_interface'] = crack2fortrangen(
  1944. b, '\n' + ' ' * 6, as_interface=True)
  1945. else:
  1946. as_ = args
  1947. b = postcrack(b, as_, tab=tab + '\t')
  1948. if b['block'] == 'interface' and not b['body']:
  1949. if 'f2pyenhancements' not in b:
  1950. continue
  1951. if b['block'].replace(' ', '') == 'pythonmodule':
  1952. usermodules.append(b)
  1953. else:
  1954. if b['block'] == 'module':
  1955. f90modulevars[b['name']] = b['vars']
  1956. body.append(b)
  1957. return body
  1958. def buildimplicitrules(block):
  1959. setmesstext(block)
  1960. implicitrules = defaultimplicitrules
  1961. attrrules = {}
  1962. if 'implicit' in block:
  1963. if block['implicit'] is None:
  1964. implicitrules = None
  1965. if verbose > 1:
  1966. outmess(
  1967. 'buildimplicitrules: no implicit rules for routine %s.\n' % repr(block['name']))
  1968. else:
  1969. for k in list(block['implicit'].keys()):
  1970. if block['implicit'][k].get('typespec') not in ['static', 'automatic']:
  1971. implicitrules[k] = block['implicit'][k]
  1972. else:
  1973. attrrules[k] = block['implicit'][k]['typespec']
  1974. return implicitrules, attrrules
  1975. def myeval(e, g=None, l=None):
  1976. r = eval(e, g, l)
  1977. if type(r) in [type(0), type(0.0)]:
  1978. return r
  1979. raise ValueError('r=%r' % (r))
  1980. getlincoef_re_1 = re.compile(r'\A\b\w+\b\Z', re.I)
  1981. def getlincoef(e, xset): # e = a*x+b ; x in xset
  1982. try:
  1983. c = int(myeval(e, {}, {}))
  1984. return 0, c, None
  1985. except Exception:
  1986. pass
  1987. if getlincoef_re_1.match(e):
  1988. return 1, 0, e
  1989. len_e = len(e)
  1990. for x in xset:
  1991. if len(x) > len_e:
  1992. continue
  1993. if re.search(r'\w\s*\([^)]*\b' + x + r'\b', e):
  1994. # skip function calls having x as an argument, e.g max(1, x)
  1995. continue
  1996. re_1 = re.compile(r'(?P<before>.*?)\b' + x + r'\b(?P<after>.*)', re.I)
  1997. m = re_1.match(e)
  1998. if m:
  1999. try:
  2000. m1 = re_1.match(e)
  2001. while m1:
  2002. ee = '%s(%s)%s' % (
  2003. m1.group('before'), 0, m1.group('after'))
  2004. m1 = re_1.match(ee)
  2005. b = myeval(ee, {}, {})
  2006. m1 = re_1.match(e)
  2007. while m1:
  2008. ee = '%s(%s)%s' % (
  2009. m1.group('before'), 1, m1.group('after'))
  2010. m1 = re_1.match(ee)
  2011. a = myeval(ee, {}, {}) - b
  2012. m1 = re_1.match(e)
  2013. while m1:
  2014. ee = '%s(%s)%s' % (
  2015. m1.group('before'), 0.5, m1.group('after'))
  2016. m1 = re_1.match(ee)
  2017. c = myeval(ee, {}, {})
  2018. # computing another point to be sure that expression is linear
  2019. m1 = re_1.match(e)
  2020. while m1:
  2021. ee = '%s(%s)%s' % (
  2022. m1.group('before'), 1.5, m1.group('after'))
  2023. m1 = re_1.match(ee)
  2024. c2 = myeval(ee, {}, {})
  2025. if (a * 0.5 + b == c and a * 1.5 + b == c2):
  2026. return a, b, x
  2027. except Exception:
  2028. pass
  2029. break
  2030. return None, None, None
  2031. _varname_match = re.compile(r'\A[a-z]\w*\Z').match
  2032. def getarrlen(dl, args, star='*'):
  2033. edl = []
  2034. try:
  2035. edl.append(myeval(dl[0], {}, {}))
  2036. except Exception:
  2037. edl.append(dl[0])
  2038. try:
  2039. edl.append(myeval(dl[1], {}, {}))
  2040. except Exception:
  2041. edl.append(dl[1])
  2042. if isinstance(edl[0], int):
  2043. p1 = 1 - edl[0]
  2044. if p1 == 0:
  2045. d = str(dl[1])
  2046. elif p1 < 0:
  2047. d = '%s-%s' % (dl[1], -p1)
  2048. else:
  2049. d = '%s+%s' % (dl[1], p1)
  2050. elif isinstance(edl[1], int):
  2051. p1 = 1 + edl[1]
  2052. if p1 == 0:
  2053. d = '-(%s)' % (dl[0])
  2054. else:
  2055. d = '%s-(%s)' % (p1, dl[0])
  2056. else:
  2057. d = '%s-(%s)+1' % (dl[1], dl[0])
  2058. try:
  2059. return repr(myeval(d, {}, {})), None, None
  2060. except Exception:
  2061. pass
  2062. d1, d2 = getlincoef(dl[0], args), getlincoef(dl[1], args)
  2063. if None not in [d1[0], d2[0]]:
  2064. if (d1[0], d2[0]) == (0, 0):
  2065. return repr(d2[1] - d1[1] + 1), None, None
  2066. b = d2[1] - d1[1] + 1
  2067. d1 = (d1[0], 0, d1[2])
  2068. d2 = (d2[0], b, d2[2])
  2069. if d1[0] == 0 and d2[2] in args:
  2070. if b < 0:
  2071. return '%s * %s - %s' % (d2[0], d2[2], -b), d2[2], '+%s)/(%s)' % (-b, d2[0])
  2072. elif b:
  2073. return '%s * %s + %s' % (d2[0], d2[2], b), d2[2], '-%s)/(%s)' % (b, d2[0])
  2074. else:
  2075. return '%s * %s' % (d2[0], d2[2]), d2[2], ')/(%s)' % (d2[0])
  2076. if d2[0] == 0 and d1[2] in args:
  2077. if b < 0:
  2078. return '%s * %s - %s' % (-d1[0], d1[2], -b), d1[2], '+%s)/(%s)' % (-b, -d1[0])
  2079. elif b:
  2080. return '%s * %s + %s' % (-d1[0], d1[2], b), d1[2], '-%s)/(%s)' % (b, -d1[0])
  2081. else:
  2082. return '%s * %s' % (-d1[0], d1[2]), d1[2], ')/(%s)' % (-d1[0])
  2083. if d1[2] == d2[2] and d1[2] in args:
  2084. a = d2[0] - d1[0]
  2085. if not a:
  2086. return repr(b), None, None
  2087. if b < 0:
  2088. return '%s * %s - %s' % (a, d1[2], -b), d2[2], '+%s)/(%s)' % (-b, a)
  2089. elif b:
  2090. return '%s * %s + %s' % (a, d1[2], b), d2[2], '-%s)/(%s)' % (b, a)
  2091. else:
  2092. return '%s * %s' % (a, d1[2]), d2[2], ')/(%s)' % (a)
  2093. if d1[0] == d2[0] == 1:
  2094. c = str(d1[2])
  2095. if c not in args:
  2096. if _varname_match(c):
  2097. outmess('\tgetarrlen:variable "%s" undefined\n' % (c))
  2098. c = '(%s)' % c
  2099. if b == 0:
  2100. d = '%s-%s' % (d2[2], c)
  2101. elif b < 0:
  2102. d = '%s-%s-%s' % (d2[2], c, -b)
  2103. else:
  2104. d = '%s-%s+%s' % (d2[2], c, b)
  2105. elif d1[0] == 0:
  2106. c2 = str(d2[2])
  2107. if c2 not in args:
  2108. if _varname_match(c2):
  2109. outmess('\tgetarrlen:variable "%s" undefined\n' % (c2))
  2110. c2 = '(%s)' % c2
  2111. if d2[0] == 1:
  2112. pass
  2113. elif d2[0] == -1:
  2114. c2 = '-%s' % c2
  2115. else:
  2116. c2 = '%s*%s' % (d2[0], c2)
  2117. if b == 0:
  2118. d = c2
  2119. elif b < 0:
  2120. d = '%s-%s' % (c2, -b)
  2121. else:
  2122. d = '%s+%s' % (c2, b)
  2123. elif d2[0] == 0:
  2124. c1 = str(d1[2])
  2125. if c1 not in args:
  2126. if _varname_match(c1):
  2127. outmess('\tgetarrlen:variable "%s" undefined\n' % (c1))
  2128. c1 = '(%s)' % c1
  2129. if d1[0] == 1:
  2130. c1 = '-%s' % c1
  2131. elif d1[0] == -1:
  2132. c1 = '+%s' % c1
  2133. elif d1[0] < 0:
  2134. c1 = '+%s*%s' % (-d1[0], c1)
  2135. else:
  2136. c1 = '-%s*%s' % (d1[0], c1)
  2137. if b == 0:
  2138. d = c1
  2139. elif b < 0:
  2140. d = '%s-%s' % (c1, -b)
  2141. else:
  2142. d = '%s+%s' % (c1, b)
  2143. else:
  2144. c1 = str(d1[2])
  2145. if c1 not in args:
  2146. if _varname_match(c1):
  2147. outmess('\tgetarrlen:variable "%s" undefined\n' % (c1))
  2148. c1 = '(%s)' % c1
  2149. if d1[0] == 1:
  2150. c1 = '-%s' % c1
  2151. elif d1[0] == -1:
  2152. c1 = '+%s' % c1
  2153. elif d1[0] < 0:
  2154. c1 = '+%s*%s' % (-d1[0], c1)
  2155. else:
  2156. c1 = '-%s*%s' % (d1[0], c1)
  2157. c2 = str(d2[2])
  2158. if c2 not in args:
  2159. if _varname_match(c2):
  2160. outmess('\tgetarrlen:variable "%s" undefined\n' % (c2))
  2161. c2 = '(%s)' % c2
  2162. if d2[0] == 1:
  2163. pass
  2164. elif d2[0] == -1:
  2165. c2 = '-%s' % c2
  2166. else:
  2167. c2 = '%s*%s' % (d2[0], c2)
  2168. if b == 0:
  2169. d = '%s%s' % (c2, c1)
  2170. elif b < 0:
  2171. d = '%s%s-%s' % (c2, c1, -b)
  2172. else:
  2173. d = '%s%s+%s' % (c2, c1, b)
  2174. return d, None, None
  2175. word_pattern = re.compile(r'\b[a-z][\w$]*\b', re.I)
  2176. def _get_depend_dict(name, vars, deps):
  2177. if name in vars:
  2178. words = vars[name].get('depend', [])
  2179. if '=' in vars[name] and not isstring(vars[name]):
  2180. for word in word_pattern.findall(vars[name]['=']):
  2181. if word not in words and word in vars:
  2182. words.append(word)
  2183. for word in words[:]:
  2184. for w in deps.get(word, []) \
  2185. or _get_depend_dict(word, vars, deps):
  2186. if w not in words:
  2187. words.append(w)
  2188. else:
  2189. outmess('_get_depend_dict: no dependence info for %s\n' % (repr(name)))
  2190. words = []
  2191. deps[name] = words
  2192. return words
  2193. def _calc_depend_dict(vars):
  2194. names = list(vars.keys())
  2195. depend_dict = {}
  2196. for n in names:
  2197. _get_depend_dict(n, vars, depend_dict)
  2198. return depend_dict
  2199. def get_sorted_names(vars):
  2200. """
  2201. """
  2202. depend_dict = _calc_depend_dict(vars)
  2203. names = []
  2204. for name in list(depend_dict.keys()):
  2205. if not depend_dict[name]:
  2206. names.append(name)
  2207. del depend_dict[name]
  2208. while depend_dict:
  2209. for name, lst in list(depend_dict.items()):
  2210. new_lst = [n for n in lst if n in depend_dict]
  2211. if not new_lst:
  2212. names.append(name)
  2213. del depend_dict[name]
  2214. else:
  2215. depend_dict[name] = new_lst
  2216. return [name for name in names if name in vars]
  2217. def _kind_func(string):
  2218. # XXX: return something sensible.
  2219. if string[0] in "'\"":
  2220. string = string[1:-1]
  2221. if real16pattern.match(string):
  2222. return 8
  2223. elif real8pattern.match(string):
  2224. return 4
  2225. return 'kind(' + string + ')'
  2226. def _selected_int_kind_func(r):
  2227. # XXX: This should be processor dependent
  2228. m = 10 ** r
  2229. if m <= 2 ** 8:
  2230. return 1
  2231. if m <= 2 ** 16:
  2232. return 2
  2233. if m <= 2 ** 32:
  2234. return 4
  2235. if m <= 2 ** 63:
  2236. return 8
  2237. if m <= 2 ** 128:
  2238. return 16
  2239. return -1
  2240. def _selected_real_kind_func(p, r=0, radix=0):
  2241. # XXX: This should be processor dependent
  2242. # This is only good for 0 <= p <= 20
  2243. if p < 7:
  2244. return 4
  2245. if p < 16:
  2246. return 8
  2247. machine = platform.machine().lower()
  2248. if machine.startswith(('aarch64', 'power', 'ppc', 'riscv', 's390x', 'sparc')):
  2249. if p <= 20:
  2250. return 16
  2251. else:
  2252. if p < 19:
  2253. return 10
  2254. elif p <= 20:
  2255. return 16
  2256. return -1
  2257. def get_parameters(vars, global_params={}):
  2258. params = copy.copy(global_params)
  2259. g_params = copy.copy(global_params)
  2260. for name, func in [('kind', _kind_func),
  2261. ('selected_int_kind', _selected_int_kind_func),
  2262. ('selected_real_kind', _selected_real_kind_func), ]:
  2263. if name not in g_params:
  2264. g_params[name] = func
  2265. param_names = []
  2266. for n in get_sorted_names(vars):
  2267. if 'attrspec' in vars[n] and 'parameter' in vars[n]['attrspec']:
  2268. param_names.append(n)
  2269. kind_re = re.compile(r'\bkind\s*\(\s*(?P<value>.*)\s*\)', re.I)
  2270. selected_int_kind_re = re.compile(
  2271. r'\bselected_int_kind\s*\(\s*(?P<value>.*)\s*\)', re.I)
  2272. selected_kind_re = re.compile(
  2273. r'\bselected_(int|real)_kind\s*\(\s*(?P<value>.*)\s*\)', re.I)
  2274. for n in param_names:
  2275. if '=' in vars[n]:
  2276. v = vars[n]['=']
  2277. if islogical(vars[n]):
  2278. v = v.lower()
  2279. for repl in [
  2280. ('.false.', 'False'),
  2281. ('.true.', 'True'),
  2282. # TODO: test .eq., .neq., etc replacements.
  2283. ]:
  2284. v = v.replace(*repl)
  2285. v = kind_re.sub(r'kind("\1")', v)
  2286. v = selected_int_kind_re.sub(r'selected_int_kind(\1)', v)
  2287. # We need to act according to the data.
  2288. # The easy case is if the data has a kind-specifier,
  2289. # then we may easily remove those specifiers.
  2290. # However, it may be that the user uses other specifiers...(!)
  2291. is_replaced = False
  2292. if 'kindselector' in vars[n]:
  2293. if 'kind' in vars[n]['kindselector']:
  2294. orig_v_len = len(v)
  2295. v = v.replace('_' + vars[n]['kindselector']['kind'], '')
  2296. # Again, this will be true if even a single specifier
  2297. # has been replaced, see comment above.
  2298. is_replaced = len(v) < orig_v_len
  2299. if not is_replaced:
  2300. if not selected_kind_re.match(v):
  2301. v_ = v.split('_')
  2302. # In case there are additive parameters
  2303. if len(v_) > 1:
  2304. v = ''.join(v_[:-1]).lower().replace(v_[-1].lower(), '')
  2305. # Currently this will not work for complex numbers.
  2306. # There is missing code for extracting a complex number,
  2307. # which may be defined in either of these:
  2308. # a) (Re, Im)
  2309. # b) cmplx(Re, Im)
  2310. # c) dcmplx(Re, Im)
  2311. # d) cmplx(Re, Im, <prec>)
  2312. if isdouble(vars[n]):
  2313. tt = list(v)
  2314. for m in real16pattern.finditer(v):
  2315. tt[m.start():m.end()] = list(
  2316. v[m.start():m.end()].lower().replace('d', 'e'))
  2317. v = ''.join(tt)
  2318. elif iscomplex(vars[n]):
  2319. # FIXME complex numbers may also have exponents
  2320. if v[0] == '(' and v[-1] == ')':
  2321. # FIXME, unused l looks like potential bug
  2322. l = markoutercomma(v[1:-1]).split('@,@')
  2323. try:
  2324. params[n] = eval(v, g_params, params)
  2325. except Exception as msg:
  2326. params[n] = v
  2327. outmess('get_parameters: got "%s" on %s\n' % (msg, repr(v)))
  2328. if isstring(vars[n]) and isinstance(params[n], int):
  2329. params[n] = chr(params[n])
  2330. nl = n.lower()
  2331. if nl != n:
  2332. params[nl] = params[n]
  2333. else:
  2334. print(vars[n])
  2335. outmess(
  2336. 'get_parameters:parameter %s does not have value?!\n' % (repr(n)))
  2337. return params
  2338. def _eval_length(length, params):
  2339. if length in ['(:)', '(*)', '*']:
  2340. return '(*)'
  2341. return _eval_scalar(length, params)
  2342. _is_kind_number = re.compile(r'\d+_').match
  2343. def _eval_scalar(value, params):
  2344. if _is_kind_number(value):
  2345. value = value.split('_')[0]
  2346. try:
  2347. value = str(eval(value, {}, params))
  2348. except (NameError, SyntaxError, TypeError):
  2349. return value
  2350. except Exception as msg:
  2351. errmess('"%s" in evaluating %r '
  2352. '(available names: %s)\n'
  2353. % (msg, value, list(params.keys())))
  2354. return value
  2355. def analyzevars(block):
  2356. global f90modulevars
  2357. setmesstext(block)
  2358. implicitrules, attrrules = buildimplicitrules(block)
  2359. vars = copy.copy(block['vars'])
  2360. if block['block'] == 'function' and block['name'] not in vars:
  2361. vars[block['name']] = {}
  2362. if '' in block['vars']:
  2363. del vars['']
  2364. if 'attrspec' in block['vars']['']:
  2365. gen = block['vars']['']['attrspec']
  2366. for n in list(vars.keys()):
  2367. for k in ['public', 'private']:
  2368. if k in gen:
  2369. vars[n] = setattrspec(vars[n], k)
  2370. svars = []
  2371. args = block['args']
  2372. for a in args:
  2373. try:
  2374. vars[a]
  2375. svars.append(a)
  2376. except KeyError:
  2377. pass
  2378. for n in list(vars.keys()):
  2379. if n not in args:
  2380. svars.append(n)
  2381. params = get_parameters(vars, get_useparameters(block))
  2382. dep_matches = {}
  2383. name_match = re.compile(r'\w[\w\d_$]*').match
  2384. for v in list(vars.keys()):
  2385. m = name_match(v)
  2386. if m:
  2387. n = v[m.start():m.end()]
  2388. try:
  2389. dep_matches[n]
  2390. except KeyError:
  2391. dep_matches[n] = re.compile(r'.*\b%s\b' % (v), re.I).match
  2392. for n in svars:
  2393. if n[0] in list(attrrules.keys()):
  2394. vars[n] = setattrspec(vars[n], attrrules[n[0]])
  2395. if 'typespec' not in vars[n]:
  2396. if not('attrspec' in vars[n] and 'external' in vars[n]['attrspec']):
  2397. if implicitrules:
  2398. ln0 = n[0].lower()
  2399. for k in list(implicitrules[ln0].keys()):
  2400. if k == 'typespec' and implicitrules[ln0][k] == 'undefined':
  2401. continue
  2402. if k not in vars[n]:
  2403. vars[n][k] = implicitrules[ln0][k]
  2404. elif k == 'attrspec':
  2405. for l in implicitrules[ln0][k]:
  2406. vars[n] = setattrspec(vars[n], l)
  2407. elif n in block['args']:
  2408. outmess('analyzevars: typespec of variable %s is not defined in routine %s.\n' % (
  2409. repr(n), block['name']))
  2410. if 'charselector' in vars[n]:
  2411. if 'len' in vars[n]['charselector']:
  2412. l = vars[n]['charselector']['len']
  2413. try:
  2414. l = str(eval(l, {}, params))
  2415. except Exception:
  2416. pass
  2417. vars[n]['charselector']['len'] = l
  2418. if 'kindselector' in vars[n]:
  2419. if 'kind' in vars[n]['kindselector']:
  2420. l = vars[n]['kindselector']['kind']
  2421. try:
  2422. l = str(eval(l, {}, params))
  2423. except Exception:
  2424. pass
  2425. vars[n]['kindselector']['kind'] = l
  2426. savelindims = {}
  2427. if 'attrspec' in vars[n]:
  2428. attr = vars[n]['attrspec']
  2429. attr.reverse()
  2430. vars[n]['attrspec'] = []
  2431. dim, intent, depend, check, note = None, None, None, None, None
  2432. for a in attr:
  2433. if a[:9] == 'dimension':
  2434. dim = (a[9:].strip())[1:-1]
  2435. elif a[:6] == 'intent':
  2436. intent = (a[6:].strip())[1:-1]
  2437. elif a[:6] == 'depend':
  2438. depend = (a[6:].strip())[1:-1]
  2439. elif a[:5] == 'check':
  2440. check = (a[5:].strip())[1:-1]
  2441. elif a[:4] == 'note':
  2442. note = (a[4:].strip())[1:-1]
  2443. else:
  2444. vars[n] = setattrspec(vars[n], a)
  2445. if intent:
  2446. if 'intent' not in vars[n]:
  2447. vars[n]['intent'] = []
  2448. for c in [x.strip() for x in markoutercomma(intent).split('@,@')]:
  2449. # Remove spaces so that 'in out' becomes 'inout'
  2450. tmp = c.replace(' ', '')
  2451. if tmp not in vars[n]['intent']:
  2452. vars[n]['intent'].append(tmp)
  2453. intent = None
  2454. if note:
  2455. note = note.replace('\\n\\n', '\n\n')
  2456. note = note.replace('\\n ', '\n')
  2457. if 'note' not in vars[n]:
  2458. vars[n]['note'] = [note]
  2459. else:
  2460. vars[n]['note'].append(note)
  2461. note = None
  2462. if depend is not None:
  2463. if 'depend' not in vars[n]:
  2464. vars[n]['depend'] = []
  2465. for c in rmbadname([x.strip() for x in markoutercomma(depend).split('@,@')]):
  2466. if c not in vars[n]['depend']:
  2467. vars[n]['depend'].append(c)
  2468. depend = None
  2469. if check is not None:
  2470. if 'check' not in vars[n]:
  2471. vars[n]['check'] = []
  2472. for c in [x.strip() for x in markoutercomma(check).split('@,@')]:
  2473. if c not in vars[n]['check']:
  2474. vars[n]['check'].append(c)
  2475. check = None
  2476. if dim and 'dimension' not in vars[n]:
  2477. vars[n]['dimension'] = []
  2478. for d in rmbadname([x.strip() for x in markoutercomma(dim).split('@,@')]):
  2479. star = '*'
  2480. if d == ':':
  2481. star = ':'
  2482. if d in params:
  2483. d = str(params[d])
  2484. for p in list(params.keys()):
  2485. re_1 = re.compile(r'(?P<before>.*?)\b' + p + r'\b(?P<after>.*)', re.I)
  2486. m = re_1.match(d)
  2487. while m:
  2488. d = m.group('before') + \
  2489. str(params[p]) + m.group('after')
  2490. m = re_1.match(d)
  2491. if d == star:
  2492. dl = [star]
  2493. else:
  2494. dl = markoutercomma(d, ':').split('@:@')
  2495. if len(dl) == 2 and '*' in dl: # e.g. dimension(5:*)
  2496. dl = ['*']
  2497. d = '*'
  2498. if len(dl) == 1 and not dl[0] == star:
  2499. dl = ['1', dl[0]]
  2500. if len(dl) == 2:
  2501. d, v, di = getarrlen(dl, list(block['vars'].keys()))
  2502. if d[:4] == '1 * ':
  2503. d = d[4:]
  2504. if di and di[-4:] == '/(1)':
  2505. di = di[:-4]
  2506. if v:
  2507. savelindims[d] = v, di
  2508. vars[n]['dimension'].append(d)
  2509. if 'dimension' in vars[n]:
  2510. if isintent_c(vars[n]):
  2511. shape_macro = 'shape'
  2512. else:
  2513. shape_macro = 'shape' # 'fshape'
  2514. if isstringarray(vars[n]):
  2515. if 'charselector' in vars[n]:
  2516. d = vars[n]['charselector']
  2517. if '*' in d:
  2518. d = d['*']
  2519. errmess('analyzevars: character array "character*%s %s(%s)" is considered as "character %s(%s)"; "intent(c)" is forced.\n'
  2520. % (d, n,
  2521. ','.join(vars[n]['dimension']),
  2522. n, ','.join(vars[n]['dimension'] + [d])))
  2523. vars[n]['dimension'].append(d)
  2524. del vars[n]['charselector']
  2525. if 'intent' not in vars[n]:
  2526. vars[n]['intent'] = []
  2527. if 'c' not in vars[n]['intent']:
  2528. vars[n]['intent'].append('c')
  2529. else:
  2530. errmess(
  2531. "analyzevars: charselector=%r unhandled." % (d))
  2532. if 'check' not in vars[n] and 'args' in block and n in block['args']:
  2533. flag = 'depend' not in vars[n]
  2534. if flag:
  2535. vars[n]['depend'] = []
  2536. vars[n]['check'] = []
  2537. if 'dimension' in vars[n]:
  2538. #/----< no check
  2539. i = -1
  2540. ni = len(vars[n]['dimension'])
  2541. for d in vars[n]['dimension']:
  2542. ddeps = [] # dependencies of 'd'
  2543. ad = ''
  2544. pd = ''
  2545. if d not in vars:
  2546. if d in savelindims:
  2547. pd, ad = '(', savelindims[d][1]
  2548. d = savelindims[d][0]
  2549. else:
  2550. for r in block['args']:
  2551. if r not in vars:
  2552. continue
  2553. if re.match(r'.*?\b' + r + r'\b', d, re.I):
  2554. ddeps.append(r)
  2555. if d in vars:
  2556. if 'attrspec' in vars[d]:
  2557. for aa in vars[d]['attrspec']:
  2558. if aa[:6] == 'depend':
  2559. ddeps += aa[6:].strip()[1:-1].split(',')
  2560. if 'depend' in vars[d]:
  2561. ddeps = ddeps + vars[d]['depend']
  2562. i = i + 1
  2563. if d in vars and ('depend' not in vars[d]) \
  2564. and ('=' not in vars[d]) and (d not in vars[n]['depend']) \
  2565. and l_or(isintent_in, isintent_inout, isintent_inplace)(vars[n]):
  2566. vars[d]['depend'] = [n]
  2567. if ni > 1:
  2568. vars[d]['='] = '%s%s(%s,%s)%s' % (
  2569. pd, shape_macro, n, i, ad)
  2570. else:
  2571. vars[d]['='] = '%slen(%s)%s' % (pd, n, ad)
  2572. # /---< no check
  2573. if 1 and 'check' not in vars[d]:
  2574. if ni > 1:
  2575. vars[d]['check'] = ['%s%s(%s,%i)%s==%s'
  2576. % (pd, shape_macro, n, i, ad, d)]
  2577. else:
  2578. vars[d]['check'] = [
  2579. '%slen(%s)%s>=%s' % (pd, n, ad, d)]
  2580. if 'attrspec' not in vars[d]:
  2581. vars[d]['attrspec'] = ['optional']
  2582. if ('optional' not in vars[d]['attrspec']) and\
  2583. ('required' not in vars[d]['attrspec']):
  2584. vars[d]['attrspec'].append('optional')
  2585. elif d not in ['*', ':']:
  2586. #/----< no check
  2587. if flag:
  2588. if d in vars:
  2589. if n not in ddeps:
  2590. vars[n]['depend'].append(d)
  2591. else:
  2592. vars[n]['depend'] = vars[n]['depend'] + ddeps
  2593. elif isstring(vars[n]):
  2594. length = '1'
  2595. if 'charselector' in vars[n]:
  2596. if '*' in vars[n]['charselector']:
  2597. length = _eval_length(vars[n]['charselector']['*'],
  2598. params)
  2599. vars[n]['charselector']['*'] = length
  2600. elif 'len' in vars[n]['charselector']:
  2601. length = _eval_length(vars[n]['charselector']['len'],
  2602. params)
  2603. del vars[n]['charselector']['len']
  2604. vars[n]['charselector']['*'] = length
  2605. if not vars[n]['check']:
  2606. del vars[n]['check']
  2607. if flag and not vars[n]['depend']:
  2608. del vars[n]['depend']
  2609. if '=' in vars[n]:
  2610. if 'attrspec' not in vars[n]:
  2611. vars[n]['attrspec'] = []
  2612. if ('optional' not in vars[n]['attrspec']) and \
  2613. ('required' not in vars[n]['attrspec']):
  2614. vars[n]['attrspec'].append('optional')
  2615. if 'depend' not in vars[n]:
  2616. vars[n]['depend'] = []
  2617. for v, m in list(dep_matches.items()):
  2618. if m(vars[n]['=']):
  2619. vars[n]['depend'].append(v)
  2620. if not vars[n]['depend']:
  2621. del vars[n]['depend']
  2622. if isscalar(vars[n]):
  2623. vars[n]['='] = _eval_scalar(vars[n]['='], params)
  2624. for n in list(vars.keys()):
  2625. if n == block['name']: # n is block name
  2626. if 'note' in vars[n]:
  2627. block['note'] = vars[n]['note']
  2628. if block['block'] == 'function':
  2629. if 'result' in block and block['result'] in vars:
  2630. vars[n] = appenddecl(vars[n], vars[block['result']])
  2631. if 'prefix' in block:
  2632. pr = block['prefix']
  2633. ispure = 0
  2634. isrec = 1
  2635. pr1 = pr.replace('pure', '')
  2636. ispure = (not pr == pr1)
  2637. pr = pr1.replace('recursive', '')
  2638. isrec = (not pr == pr1)
  2639. m = typespattern[0].match(pr)
  2640. if m:
  2641. typespec, selector, attr, edecl = cracktypespec0(
  2642. m.group('this'), m.group('after'))
  2643. kindselect, charselect, typename = cracktypespec(
  2644. typespec, selector)
  2645. vars[n]['typespec'] = typespec
  2646. if kindselect:
  2647. if 'kind' in kindselect:
  2648. try:
  2649. kindselect['kind'] = eval(
  2650. kindselect['kind'], {}, params)
  2651. except Exception:
  2652. pass
  2653. vars[n]['kindselector'] = kindselect
  2654. if charselect:
  2655. vars[n]['charselector'] = charselect
  2656. if typename:
  2657. vars[n]['typename'] = typename
  2658. if ispure:
  2659. vars[n] = setattrspec(vars[n], 'pure')
  2660. if isrec:
  2661. vars[n] = setattrspec(vars[n], 'recursive')
  2662. else:
  2663. outmess(
  2664. 'analyzevars: prefix (%s) were not used\n' % repr(block['prefix']))
  2665. if not block['block'] in ['module', 'pythonmodule', 'python module', 'block data']:
  2666. if 'commonvars' in block:
  2667. neededvars = copy.copy(block['args'] + block['commonvars'])
  2668. else:
  2669. neededvars = copy.copy(block['args'])
  2670. for n in list(vars.keys()):
  2671. if l_or(isintent_callback, isintent_aux)(vars[n]):
  2672. neededvars.append(n)
  2673. if 'entry' in block:
  2674. neededvars.extend(list(block['entry'].keys()))
  2675. for k in list(block['entry'].keys()):
  2676. for n in block['entry'][k]:
  2677. if n not in neededvars:
  2678. neededvars.append(n)
  2679. if block['block'] == 'function':
  2680. if 'result' in block:
  2681. neededvars.append(block['result'])
  2682. else:
  2683. neededvars.append(block['name'])
  2684. if block['block'] in ['subroutine', 'function']:
  2685. name = block['name']
  2686. if name in vars and 'intent' in vars[name]:
  2687. block['intent'] = vars[name]['intent']
  2688. if block['block'] == 'type':
  2689. neededvars.extend(list(vars.keys()))
  2690. for n in list(vars.keys()):
  2691. if n not in neededvars:
  2692. del vars[n]
  2693. return vars
  2694. analyzeargs_re_1 = re.compile(r'\A[a-z]+[\w$]*\Z', re.I)
  2695. def expr2name(a, block, args=[]):
  2696. orig_a = a
  2697. a_is_expr = not analyzeargs_re_1.match(a)
  2698. if a_is_expr: # `a` is an expression
  2699. implicitrules, attrrules = buildimplicitrules(block)
  2700. at = determineexprtype(a, block['vars'], implicitrules)
  2701. na = 'e_'
  2702. for c in a:
  2703. c = c.lower()
  2704. if c not in string.ascii_lowercase + string.digits:
  2705. c = '_'
  2706. na = na + c
  2707. if na[-1] == '_':
  2708. na = na + 'e'
  2709. else:
  2710. na = na + '_e'
  2711. a = na
  2712. while a in block['vars'] or a in block['args']:
  2713. a = a + 'r'
  2714. if a in args:
  2715. k = 1
  2716. while a + str(k) in args:
  2717. k = k + 1
  2718. a = a + str(k)
  2719. if a_is_expr:
  2720. block['vars'][a] = at
  2721. else:
  2722. if a not in block['vars']:
  2723. if orig_a in block['vars']:
  2724. block['vars'][a] = block['vars'][orig_a]
  2725. else:
  2726. block['vars'][a] = {}
  2727. if 'externals' in block and orig_a in block['externals'] + block['interfaced']:
  2728. block['vars'][a] = setattrspec(block['vars'][a], 'external')
  2729. return a
  2730. def analyzeargs(block):
  2731. setmesstext(block)
  2732. implicitrules, attrrules = buildimplicitrules(block)
  2733. if 'args' not in block:
  2734. block['args'] = []
  2735. args = []
  2736. for a in block['args']:
  2737. a = expr2name(a, block, args)
  2738. args.append(a)
  2739. block['args'] = args
  2740. if 'entry' in block:
  2741. for k, args1 in list(block['entry'].items()):
  2742. for a in args1:
  2743. if a not in block['vars']:
  2744. block['vars'][a] = {}
  2745. for b in block['body']:
  2746. if b['name'] in args:
  2747. if 'externals' not in block:
  2748. block['externals'] = []
  2749. if b['name'] not in block['externals']:
  2750. block['externals'].append(b['name'])
  2751. if 'result' in block and block['result'] not in block['vars']:
  2752. block['vars'][block['result']] = {}
  2753. return block
  2754. determineexprtype_re_1 = re.compile(r'\A\(.+?[,].+?\)\Z', re.I)
  2755. determineexprtype_re_2 = re.compile(r'\A[+-]?\d+(_(?P<name>[\w]+)|)\Z', re.I)
  2756. determineexprtype_re_3 = re.compile(
  2757. r'\A[+-]?[\d.]+[\d+\-de.]*(_(?P<name>[\w]+)|)\Z', re.I)
  2758. determineexprtype_re_4 = re.compile(r'\A\(.*\)\Z', re.I)
  2759. determineexprtype_re_5 = re.compile(r'\A(?P<name>\w+)\s*\(.*?\)\s*\Z', re.I)
  2760. def _ensure_exprdict(r):
  2761. if isinstance(r, int):
  2762. return {'typespec': 'integer'}
  2763. if isinstance(r, float):
  2764. return {'typespec': 'real'}
  2765. if isinstance(r, complex):
  2766. return {'typespec': 'complex'}
  2767. if isinstance(r, dict):
  2768. return r
  2769. raise AssertionError(repr(r))
  2770. def determineexprtype(expr, vars, rules={}):
  2771. if expr in vars:
  2772. return _ensure_exprdict(vars[expr])
  2773. expr = expr.strip()
  2774. if determineexprtype_re_1.match(expr):
  2775. return {'typespec': 'complex'}
  2776. m = determineexprtype_re_2.match(expr)
  2777. if m:
  2778. if 'name' in m.groupdict() and m.group('name'):
  2779. outmess(
  2780. 'determineexprtype: selected kind types not supported (%s)\n' % repr(expr))
  2781. return {'typespec': 'integer'}
  2782. m = determineexprtype_re_3.match(expr)
  2783. if m:
  2784. if 'name' in m.groupdict() and m.group('name'):
  2785. outmess(
  2786. 'determineexprtype: selected kind types not supported (%s)\n' % repr(expr))
  2787. return {'typespec': 'real'}
  2788. for op in ['+', '-', '*', '/']:
  2789. for e in [x.strip() for x in markoutercomma(expr, comma=op).split('@' + op + '@')]:
  2790. if e in vars:
  2791. return _ensure_exprdict(vars[e])
  2792. t = {}
  2793. if determineexprtype_re_4.match(expr): # in parenthesis
  2794. t = determineexprtype(expr[1:-1], vars, rules)
  2795. else:
  2796. m = determineexprtype_re_5.match(expr)
  2797. if m:
  2798. rn = m.group('name')
  2799. t = determineexprtype(m.group('name'), vars, rules)
  2800. if t and 'attrspec' in t:
  2801. del t['attrspec']
  2802. if not t:
  2803. if rn[0] in rules:
  2804. return _ensure_exprdict(rules[rn[0]])
  2805. if expr[0] in '\'"':
  2806. return {'typespec': 'character', 'charselector': {'*': '*'}}
  2807. if not t:
  2808. outmess(
  2809. 'determineexprtype: could not determine expressions (%s) type.\n' % (repr(expr)))
  2810. return t
  2811. ######
  2812. def crack2fortrangen(block, tab='\n', as_interface=False):
  2813. global skipfuncs, onlyfuncs
  2814. setmesstext(block)
  2815. ret = ''
  2816. if isinstance(block, list):
  2817. for g in block:
  2818. if g and g['block'] in ['function', 'subroutine']:
  2819. if g['name'] in skipfuncs:
  2820. continue
  2821. if onlyfuncs and g['name'] not in onlyfuncs:
  2822. continue
  2823. ret = ret + crack2fortrangen(g, tab, as_interface=as_interface)
  2824. return ret
  2825. prefix = ''
  2826. name = ''
  2827. args = ''
  2828. blocktype = block['block']
  2829. if blocktype == 'program':
  2830. return ''
  2831. argsl = []
  2832. if 'name' in block:
  2833. name = block['name']
  2834. if 'args' in block:
  2835. vars = block['vars']
  2836. for a in block['args']:
  2837. a = expr2name(a, block, argsl)
  2838. if not isintent_callback(vars[a]):
  2839. argsl.append(a)
  2840. if block['block'] == 'function' or argsl:
  2841. args = '(%s)' % ','.join(argsl)
  2842. f2pyenhancements = ''
  2843. if 'f2pyenhancements' in block:
  2844. for k in list(block['f2pyenhancements'].keys()):
  2845. f2pyenhancements = '%s%s%s %s' % (
  2846. f2pyenhancements, tab + tabchar, k, block['f2pyenhancements'][k])
  2847. intent_lst = block.get('intent', [])[:]
  2848. if blocktype == 'function' and 'callback' in intent_lst:
  2849. intent_lst.remove('callback')
  2850. if intent_lst:
  2851. f2pyenhancements = '%s%sintent(%s) %s' %\
  2852. (f2pyenhancements, tab + tabchar,
  2853. ','.join(intent_lst), name)
  2854. use = ''
  2855. if 'use' in block:
  2856. use = use2fortran(block['use'], tab + tabchar)
  2857. common = ''
  2858. if 'common' in block:
  2859. common = common2fortran(block['common'], tab + tabchar)
  2860. if name == 'unknown_interface':
  2861. name = ''
  2862. result = ''
  2863. if 'result' in block:
  2864. result = ' result (%s)' % block['result']
  2865. if block['result'] not in argsl:
  2866. argsl.append(block['result'])
  2867. body = crack2fortrangen(block['body'], tab + tabchar)
  2868. vars = vars2fortran(
  2869. block, block['vars'], argsl, tab + tabchar, as_interface=as_interface)
  2870. mess = ''
  2871. if 'from' in block and not as_interface:
  2872. mess = '! in %s' % block['from']
  2873. if 'entry' in block:
  2874. entry_stmts = ''
  2875. for k, i in list(block['entry'].items()):
  2876. entry_stmts = '%s%sentry %s(%s)' \
  2877. % (entry_stmts, tab + tabchar, k, ','.join(i))
  2878. body = body + entry_stmts
  2879. if blocktype == 'block data' and name == '_BLOCK_DATA_':
  2880. name = ''
  2881. ret = '%s%s%s %s%s%s %s%s%s%s%s%s%send %s %s' % (
  2882. tab, prefix, blocktype, name, args, result, mess, f2pyenhancements, use, vars, common, body, tab, blocktype, name)
  2883. return ret
  2884. def common2fortran(common, tab=''):
  2885. ret = ''
  2886. for k in list(common.keys()):
  2887. if k == '_BLNK_':
  2888. ret = '%s%scommon %s' % (ret, tab, ','.join(common[k]))
  2889. else:
  2890. ret = '%s%scommon /%s/ %s' % (ret, tab, k, ','.join(common[k]))
  2891. return ret
  2892. def use2fortran(use, tab=''):
  2893. ret = ''
  2894. for m in list(use.keys()):
  2895. ret = '%s%suse %s,' % (ret, tab, m)
  2896. if use[m] == {}:
  2897. if ret and ret[-1] == ',':
  2898. ret = ret[:-1]
  2899. continue
  2900. if 'only' in use[m] and use[m]['only']:
  2901. ret = '%s only:' % (ret)
  2902. if 'map' in use[m] and use[m]['map']:
  2903. c = ' '
  2904. for k in list(use[m]['map'].keys()):
  2905. if k == use[m]['map'][k]:
  2906. ret = '%s%s%s' % (ret, c, k)
  2907. c = ','
  2908. else:
  2909. ret = '%s%s%s=>%s' % (ret, c, k, use[m]['map'][k])
  2910. c = ','
  2911. if ret and ret[-1] == ',':
  2912. ret = ret[:-1]
  2913. return ret
  2914. def true_intent_list(var):
  2915. lst = var['intent']
  2916. ret = []
  2917. for intent in lst:
  2918. try:
  2919. c = eval('isintent_%s(var)' % intent)
  2920. except NameError:
  2921. c = 0
  2922. if c:
  2923. ret.append(intent)
  2924. return ret
  2925. def vars2fortran(block, vars, args, tab='', as_interface=False):
  2926. """
  2927. TODO:
  2928. public sub
  2929. ...
  2930. """
  2931. setmesstext(block)
  2932. ret = ''
  2933. nout = []
  2934. for a in args:
  2935. if a in block['vars']:
  2936. nout.append(a)
  2937. if 'commonvars' in block:
  2938. for a in block['commonvars']:
  2939. if a in vars:
  2940. if a not in nout:
  2941. nout.append(a)
  2942. else:
  2943. errmess(
  2944. 'vars2fortran: Confused?!: "%s" is not defined in vars.\n' % a)
  2945. if 'varnames' in block:
  2946. nout.extend(block['varnames'])
  2947. if not as_interface:
  2948. for a in list(vars.keys()):
  2949. if a not in nout:
  2950. nout.append(a)
  2951. for a in nout:
  2952. if 'depend' in vars[a]:
  2953. for d in vars[a]['depend']:
  2954. if d in vars and 'depend' in vars[d] and a in vars[d]['depend']:
  2955. errmess(
  2956. 'vars2fortran: Warning: cross-dependence between variables "%s" and "%s"\n' % (a, d))
  2957. if 'externals' in block and a in block['externals']:
  2958. if isintent_callback(vars[a]):
  2959. ret = '%s%sintent(callback) %s' % (ret, tab, a)
  2960. ret = '%s%sexternal %s' % (ret, tab, a)
  2961. if isoptional(vars[a]):
  2962. ret = '%s%soptional %s' % (ret, tab, a)
  2963. if a in vars and 'typespec' not in vars[a]:
  2964. continue
  2965. cont = 1
  2966. for b in block['body']:
  2967. if a == b['name'] and b['block'] == 'function':
  2968. cont = 0
  2969. break
  2970. if cont:
  2971. continue
  2972. if a not in vars:
  2973. show(vars)
  2974. outmess('vars2fortran: No definition for argument "%s".\n' % a)
  2975. continue
  2976. if a == block['name'] and not block['block'] == 'function':
  2977. continue
  2978. if 'typespec' not in vars[a]:
  2979. if 'attrspec' in vars[a] and 'external' in vars[a]['attrspec']:
  2980. if a in args:
  2981. ret = '%s%sexternal %s' % (ret, tab, a)
  2982. continue
  2983. show(vars[a])
  2984. outmess('vars2fortran: No typespec for argument "%s".\n' % a)
  2985. continue
  2986. vardef = vars[a]['typespec']
  2987. if vardef == 'type' and 'typename' in vars[a]:
  2988. vardef = '%s(%s)' % (vardef, vars[a]['typename'])
  2989. selector = {}
  2990. if 'kindselector' in vars[a]:
  2991. selector = vars[a]['kindselector']
  2992. elif 'charselector' in vars[a]:
  2993. selector = vars[a]['charselector']
  2994. if '*' in selector:
  2995. if selector['*'] in ['*', ':']:
  2996. vardef = '%s*(%s)' % (vardef, selector['*'])
  2997. else:
  2998. vardef = '%s*%s' % (vardef, selector['*'])
  2999. else:
  3000. if 'len' in selector:
  3001. vardef = '%s(len=%s' % (vardef, selector['len'])
  3002. if 'kind' in selector:
  3003. vardef = '%s,kind=%s)' % (vardef, selector['kind'])
  3004. else:
  3005. vardef = '%s)' % (vardef)
  3006. elif 'kind' in selector:
  3007. vardef = '%s(kind=%s)' % (vardef, selector['kind'])
  3008. c = ' '
  3009. if 'attrspec' in vars[a]:
  3010. attr = [l for l in vars[a]['attrspec']
  3011. if l not in ['external']]
  3012. if attr:
  3013. vardef = '%s, %s' % (vardef, ','.join(attr))
  3014. c = ','
  3015. if 'dimension' in vars[a]:
  3016. vardef = '%s%sdimension(%s)' % (
  3017. vardef, c, ','.join(vars[a]['dimension']))
  3018. c = ','
  3019. if 'intent' in vars[a]:
  3020. lst = true_intent_list(vars[a])
  3021. if lst:
  3022. vardef = '%s%sintent(%s)' % (vardef, c, ','.join(lst))
  3023. c = ','
  3024. if 'check' in vars[a]:
  3025. vardef = '%s%scheck(%s)' % (vardef, c, ','.join(vars[a]['check']))
  3026. c = ','
  3027. if 'depend' in vars[a]:
  3028. vardef = '%s%sdepend(%s)' % (
  3029. vardef, c, ','.join(vars[a]['depend']))
  3030. c = ','
  3031. if '=' in vars[a]:
  3032. v = vars[a]['=']
  3033. if vars[a]['typespec'] in ['complex', 'double complex']:
  3034. try:
  3035. v = eval(v)
  3036. v = '(%s,%s)' % (v.real, v.imag)
  3037. except Exception:
  3038. pass
  3039. vardef = '%s :: %s=%s' % (vardef, a, v)
  3040. else:
  3041. vardef = '%s :: %s' % (vardef, a)
  3042. ret = '%s%s%s' % (ret, tab, vardef)
  3043. return ret
  3044. ######
  3045. def crackfortran(files):
  3046. global usermodules
  3047. outmess('Reading fortran codes...\n', 0)
  3048. readfortrancode(files, crackline)
  3049. outmess('Post-processing...\n', 0)
  3050. usermodules = []
  3051. postlist = postcrack(grouplist[0])
  3052. outmess('Post-processing (stage 2)...\n', 0)
  3053. postlist = postcrack2(postlist)
  3054. return usermodules + postlist
  3055. def crack2fortran(block):
  3056. global f2py_version
  3057. pyf = crack2fortrangen(block) + '\n'
  3058. header = """! -*- f90 -*-
  3059. ! Note: the context of this file is case sensitive.
  3060. """
  3061. footer = """
  3062. ! This file was auto-generated with f2py (version:%s).
  3063. ! See http://cens.ioc.ee/projects/f2py2e/
  3064. """ % (f2py_version)
  3065. return header + pyf + footer
  3066. if __name__ == "__main__":
  3067. files = []
  3068. funcs = []
  3069. f = 1
  3070. f2 = 0
  3071. f3 = 0
  3072. showblocklist = 0
  3073. for l in sys.argv[1:]:
  3074. if l == '':
  3075. pass
  3076. elif l[0] == ':':
  3077. f = 0
  3078. elif l == '-quiet':
  3079. quiet = 1
  3080. verbose = 0
  3081. elif l == '-verbose':
  3082. verbose = 2
  3083. quiet = 0
  3084. elif l == '-fix':
  3085. if strictf77:
  3086. outmess(
  3087. 'Use option -f90 before -fix if Fortran 90 code is in fix form.\n', 0)
  3088. skipemptyends = 1
  3089. sourcecodeform = 'fix'
  3090. elif l == '-skipemptyends':
  3091. skipemptyends = 1
  3092. elif l == '--ignore-contains':
  3093. ignorecontains = 1
  3094. elif l == '-f77':
  3095. strictf77 = 1
  3096. sourcecodeform = 'fix'
  3097. elif l == '-f90':
  3098. strictf77 = 0
  3099. sourcecodeform = 'free'
  3100. skipemptyends = 1
  3101. elif l == '-h':
  3102. f2 = 1
  3103. elif l == '-show':
  3104. showblocklist = 1
  3105. elif l == '-m':
  3106. f3 = 1
  3107. elif l[0] == '-':
  3108. errmess('Unknown option %s\n' % repr(l))
  3109. elif f2:
  3110. f2 = 0
  3111. pyffilename = l
  3112. elif f3:
  3113. f3 = 0
  3114. f77modulename = l
  3115. elif f:
  3116. try:
  3117. open(l).close()
  3118. files.append(l)
  3119. except IOError as detail:
  3120. errmess('IOError: %s\n' % str(detail))
  3121. else:
  3122. funcs.append(l)
  3123. if not strictf77 and f77modulename and not skipemptyends:
  3124. outmess("""\
  3125. Warning: You have specified module name for non Fortran 77 code
  3126. that should not need one (expect if you are scanning F90 code
  3127. for non module blocks but then you should use flag -skipemptyends
  3128. and also be sure that the files do not contain programs without program statement).
  3129. """, 0)
  3130. postlist = crackfortran(files)
  3131. if pyffilename:
  3132. outmess('Writing fortran code to file %s\n' % repr(pyffilename), 0)
  3133. pyf = crack2fortran(postlist)
  3134. with open(pyffilename, 'w') as f:
  3135. f.write(pyf)
  3136. if showblocklist:
  3137. show(postlist)