o
    "gD                    @   s  d Z ddlZddlZddlZddlZddlZddlZddlZddlZddl	m
Z
 zddlZW n ey9   dZY nw ddlmZ ddlT ddlmZ ejadadadadad	ad
ad
adadadag ad
ad
ada i a!d
a"da#da$da%t%g ia&d
a'g a(da)g a*da+da,g a-g a.g a/dd Z0dddZ1de_2i Z3dD ]Z4ddie3e4< qdD ]Z4ddie3e4< qi Z5i Z6dD ]Z7e7d e5e7< e7e6e7d < qdd Z8dd Z9dd Z:dd Z;e<d ej=j>Z?e<d!ej=j>Z@e<d"ej=j>ZAe<d#ej=jBZCg d$ZDg d%ZEd&d' ZFd(d) ZGeHdfd*d+ZId,ZJd-ZKe<eJd
eKeKd.f ej=d/fZLe<eJd
eKd0 eKd0 d.f ej=ZMe<eJd1 ej=d2fZNe<eJd3 ej=d2fZOd4ZPe<eJd
ePePd.f ej=d2fZQePd5 d6 ZRe<eJd
eReRd.f ej=d2fZSd7ZTe<eJd
eTeTd.f ej=d8fZUd9ZVe<eJd:eVeVd.f ej=d;fZWd<ZXe<eJd
eXeXd.f ej=d=fZYe<eJd> ej=d?fZZe<eJd@ ej=dAfZ[e<eJdB ej=dCfZ\e<eJdD ej=dEfZ]e<eJdF ej=dGfZ^e<eJdH ej=dIfZ_e<eJdJ ej=dKfZ`e<eJdL ej=dMfZae<eJdN ej=dOfZbe<eJdP ej=dQfZce<eJdR ej=dSfZde<eJdT ej=dUfZee<eJdV ej=dWfZfe<eJdX ej=dYfZge<eJdZ ej=d[fZhe<eJd\ ej=d]fZie<eJd^ ej=d_fZje<eJd` ej=dafZke<eJdb ej=ejlB dcfZme<ddejldefZndfdg Zodhdi Zpe<djej=Zqe<dkej=Zre<dlej=ZsddmdnZtdodp ZuddrdsZvdtdu ZwddvdwZxe<dxej=Zye<dyej=Zze<dzej=Z{e<d{ej=Z|e<d|ej=Z}e<d}Z~e<d~Ze<dej=Zdd Zdd Zdd Zdd Zdd Zdd Zdd Ze<dej=Ze<dej=Ze<dej=Ze<dej=Ze<dej=Zdd Zdd Zdd Zdd ZdddZdddZdddZdddZdd Zdd ZdddZdddZdddZdd Zdd ZdddZdd ZdddZe<dej=Zdd Ze<dej=Zdd Zdd Zdd ZddÄ Zddń ZdddǄZi fddɄZdd˄ Ze<d̡jBZdd΄ ZddЄ Ze<dej=ZdddӄZddՄ Zg fddׄZddل Ze<dej=Ze<dej=Ze<dej=Ze<dej=Ze<dej=Zdd Zi fddZdddZdddZdddZdd ZdddZg add Zdd Zdd Zg dfddZdd Zteá edkrg Zg ZdZdZdZdZejdd D ]Zed
kreq\ed dkrpdZȐq\edkr{dadaq\edkrdadaq\edkrtre1dd dadaq\e͐d krdaq\e͐dkrdaq\e͐dkrdadaq\e͐dkrdadadaq\e͐dkrdZɐq\e͐dkrdZːq\e͐dkrdZʐq\ed dkreΐd	ee̓  q\eɐrdZeaq\eʐrdZeaq\eȐr:zee̓ѡ  eƠe͡ W q\ eҐy9 Z zeΐd
eӛd W Y dZ[Ӑq\dZ[ww eǠe͡ q\tsPtrPtsPe1dd eeƃZtre1det d eeԃZetdZeȠeա W d   n	1 s|w   Y  eːreHeԃ dS dS dS (  a  
crackfortran --- read fortran (77,90) code and extract declaration information.

Copyright 1999 -- 2011 Pearu Peterson all rights reserved.
Copyright 2011 -- present NumPy Developers.
Permission to use, modify, and distribute this software is given under the
terms of the NumPy License.

NO WARRANTY IS EXPRESSED OR IMPLIED.  USE AT YOUR OWN RISK.


Usage of crackfortran:
======================
Command line keys: -quiet,-verbose,-fix,-f77,-f90,-show,-h <pyffilename>
                   -m <module name for f77 routines>,--ignore-contains
Functions: crackfortran, crack2fortran
The following Fortran statements/constructions are supported
(or will be if needed):
   block data,byte,call,character,common,complex,contains,data,
   dimension,double complex,double precision,end,external,function,
   implicit,integer,intent,interface,intrinsic,
   logical,module,optional,parameter,private,public,
   program,real,(sequence?),subroutine,type,use,virtual,
   include,pythonmodule
Note: 'virtual' is mapped to 'dimension'.
Note: 'implicit integer (z) static (z)' is 'implicit static (z)' (this is minor bug).
Note: code after 'contains' will be ignored until its scope ends.
Note: 'common' statement is extended: dimensions are moved to variable definitions
Note: f2py directive: <commentchar>f2py<line> is read as <line>
Note: pythonmodule is introduced to represent Python module

Usage:
  `postlist=crackfortran(files)`
  `postlist` contains declaration information read from the list of files `files`.
  `crack2fortran(postlist)` returns a fortran code to be saved to pyf-file

  `postlist` has the following structure:
 *** it is a list of dictionaries containing `blocks':
     B = {'block','body','vars','parent_block'[,'name','prefix','args','result',
          'implicit','externals','interfaced','common','sortvars',
          'commonvars','note']}
     B['block'] = 'interface' | 'function' | 'subroutine' | 'module' |
                  'program' | 'block data' | 'type' | 'pythonmodule' |
                  'abstract interface'
     B['body'] --- list containing `subblocks' with the same structure as `blocks'
     B['parent_block'] --- dictionary of a parent block:
                             C['body'][<index>]['parent_block'] is C
     B['vars'] --- dictionary of variable definitions
     B['sortvars'] --- dictionary of variable definitions sorted by dependence (independent first)
     B['name'] --- name of the block (not if B['block']=='interface')
     B['prefix'] --- prefix string (only if B['block']=='function')
     B['args'] --- list of argument names if B['block']== 'function' | 'subroutine'
     B['result'] --- name of the return value (only if B['block']=='function')
     B['implicit'] --- dictionary {'a':<variable definition>,'b':...} | None
     B['externals'] --- list of variables being external
     B['interfaced'] --- list of variables being external and defined
     B['common'] --- dictionary of common blocks (list of objects)
     B['commonvars'] --- list of variables used in common blocks (dimensions are moved to variable definitions)
     B['from'] --- string showing the 'parents' of the current block
     B['use'] --- dictionary of modules used in current block:
         {<modulename>:{['only':<0|1>],['map':{<local_name1>:<use_name1>,...}]}}
     B['note'] --- list of LaTeX comments on the block
     B['f2pyenhancements'] --- optional dictionary
          {'threadsafe':'','fortranname':<name>,
           'callstatement':<C-expr>|<multi-line block>,
           'callprotoargument':<C-expr-list>,
           'usercode':<multi-line block>|<list of multi-line blocks>,
           'pymethoddef:<multi-line block>'
           }
     B['entry'] --- dictionary {entryname:argslist,..}
     B['varnames'] --- list of variable names given in the order of reading the
                       Fortran code, useful for derived types.
     B['saved_interface'] --- a string of scanned routine signature, defines explicit interface
 *** Variable definition is a dictionary
     D = B['vars'][<variable name>] =
     {'typespec'[,'attrspec','kindselector','charselector','=','typename']}
     D['typespec'] = 'byte' | 'character' | 'complex' | 'double complex' |
                     'double precision' | 'integer' | 'logical' | 'real' | 'type'
     D['attrspec'] --- list of attributes (e.g. 'dimension(<arrayspec>)',
                       'external','intent(in|out|inout|hide|c|callback|cache|aligned4|aligned8|aligned16)',
                       'optional','required', etc)
     K = D['kindselector'] = {['*','kind']} (only if D['typespec'] =
                         'complex' | 'integer' | 'logical' | 'real' )
     C = D['charselector'] = {['*','len','kind','f2py_len']}
                             (only if D['typespec']=='character')
     D['='] --- initialization expression string
     D['typename'] --- name of the type if D['typespec']=='type'
     D['dimension'] --- list of dimension bounds
     D['intent'] --- list of intent specifications
     D['depend'] --- list of variable names on which current variable depends on
     D['check'] --- list of C-expressions; if C-expr returns zero, exception is raised
     D['note'] --- list of LaTeX comments on the variable
 *** Meaning of kind/char selectors (few examples):
     D['typespec>']*K['*']
     D['typespec'](kind=K['kind'])
     character*C['*']
     character(len=C['len'],kind=C['kind'], f2py_len=C['f2py_len'])
     (see also fortran type declaration statement formats below)

Fortran 90 type declaration statement format (F77 is subset of F90)
====================================================================
(Main source: IBM XL Fortran 5.1 Language Reference Manual)
type declaration = <typespec> [[<attrspec>]::] <entitydecl>
<typespec> = byte                          |
             character[<charselector>]     |
             complex[<kindselector>]       |
             double complex                |
             double precision              |
             integer[<kindselector>]       |
             logical[<kindselector>]       |
             real[<kindselector>]          |
             type(<typename>)
<charselector> = * <charlen>               |
             ([len=]<len>[,[kind=]<kind>]) |
             (kind=<kind>[,len=<len>])
<kindselector> = * <intlen>                |
             ([kind=]<kind>)
<attrspec> = comma separated list of attributes.
             Only the following attributes are used in
             building up the interface:
                external
                (parameter --- affects '=' key)
                optional
                intent
             Other attributes are ignored.
<intentspec> = in | out | inout
<arrayspec> = comma separated list of dimension bounds.
<entitydecl> = <name> [[*<charlen>][(<arrayspec>)] | [(<arrayspec>)]*<charlen>]
                      [/<init_expr>/ | =<init_expr>] [,<entitydecl>]

In addition, the following attributes are used: check,depend,note

TODO:
    * Apply 'parameter' attribute (e.g. 'integer parameter :: i=2' 'real x(i)'
                                   -> 'real x(2)')
    The above may be solved by creating appropriate preprocessor program, for example.

    N)Path   )__version__)*)symbolicfix     c                   C   sp   da dadadadadadadadada	g a
datg iadadadag ai adadadag ag ag ag ad ad S )Nr   r   r   r   r	   r
   )	strictf77sourcecodeformquietverbosetabcharpyffilenamef77modulenameskipemptyendsignorecontainsdolowercasedebuggroupcounter	grouplistneededmoduleexpectbeginskipblocksuntilusermodulesf90modulevarsgotnextfilefilepositiontextcurrentfilenameskipfunctions	skipfuncs	onlyfuncsinclude_pathsprevious_context r%   r%   Y/var/www/html/ecg_monitoring/venv/lib/python3.10/site-packages/numpy/f2py/crackfortran.pyreset_global_f2py_vars   s4   	r'   c                 C   s0   t sd S ts|rtjt tj|  d S d S N)r   r   sysstdoutwriter   )lineflagr%   r%   r&   outmess   s   r.   2   zabcdefghopqrstuvwxyz$_typespecrealijklmninteger)3intdoublefloatcharshortlongvoidcasewhilereturnsignedunsignediffortypedefsizeofunionstructstaticregisternewbreakdogotoswitchcontinueelseinlineexterndeleteconstautolenrankshapeindexslensize_imaxminflenfshapestringcomplex_doublefloat_doublestdinstderrr*   typedefault_bnc                 C   (   | t v rtd| t |  f  t |  S | S )Nz&rmbadname1: Replacing "%s" with "%s".
)badnameserrmessnamer%   r%   r&   
rmbadname1
     
rl   c                 C      dd | D S )Nc                 S      g | ]}t |qS r%   )rl   .0_mr%   r%   r&   
<listcomp>      zrmbadname.<locals>.<listcomp>r%   namesr%   r%   r&   	rmbadname     rw   c                 C   rg   )Nz+undo_rmbadname1: Replacing "%s" with "%s".
)invbadnamesri   rj   r%   r%   r&   undo_rmbadname1  rm   rz   c                 C   rn   )Nc                 S   ro   r%   )rz   rp   r%   r%   r&   rs     rt   z"undo_rmbadname.<locals>.<listcomp>r%   ru   r%   r%   r&   undo_rmbadname  rx   r{   z-\*-\s*fortran\s*-\*-z-\*-\s*f90\s*-\*-z-\*-\s*fix\s*-\*-z[^c*]\s*[^\s\d\t])z.f90z.f95z.f03z.f08)z.forz.ftnz.f77z.fc                 C   s   t durt |  j}nFtdtj| }t| d0}|	|}|
tjr*d}n|
tjtjfr6d}n|
tjtjfrBd}nd}W d   n1 sNw   Y  t| ||dS )	aN  Ensures that filename is opened with correct encoding parameter.

    This function uses charset_normalizer package, when available, for
    determining the encoding of the file to be opened. When charset_normalizer
    is not available, the function detects only UTF encodings, otherwise, ASCII
    encoding is used as fallback.
    N    rbz	UTF-8-SIGzUTF-32zUTF-16ascii)encoding)charset_normalizer	from_pathbestr   r\   ospathgetsizeopenread
startswithcodecsBOM_UTF8BOM_UTF32_LEBOM_UTF32_BEBOM_LEBOM_BE)filenamemoder   nbytesfhandlerawr%   r%   r&   openhook,  s   
r   c                 C   s"  d}t | j tv rd}t| du}| }d}t|r d}nt|r(d}d}|dkrg|ro|d dkrU| rU|d8 }|d dkrJt	|d	d
 sR|dd dkrUd}n*| }|dkrw|s.W d	   |S W d	   |S W d	   |S W d	   |S W d	   |S 1 sw   Y  |S )z(Check if file is in free format Fortran.FTr   r   !r   	N   r
   &)
r   suffixlowerCOMMON_FREE_EXTENSIONSr   readline_has_f_header_has_f90_headerstrip_free_f90_start)fnameresultr   r,   nr%   r%   r&   is_free_formatK  sF   ,




r   c                 C   s^  |st ttttttttf	}| g krdS t}d}d}d}t	
dt	j}t	
d}	t	
d}
t	
d}|r8|dd d	\}}d
gdd tdD  }datj| td}	 z| }W n tyv } ztd|  d|  d| dd}~ww |s{n$| rda| ada |}dadatjtd }ttj tv rt|st|sdan
ttrt|sdatrt ant!at"dt#tttrdpdf  |$ %dd
}|dks|d dvrn
|dd }|dkrd}t&|d\}}|d
7 }|dd  dkrt&|d |dd  d\}}d}|' dkrtdkrnd}qQtdkr|d d v rF|dd  d!krAd"|dd  }d}nd}d}qQtrVt(|d#krV|dd# }|d |vretd$t#| |rktrt(|dkr|d d
ks||d%d  }d}d}n|	)|}|r|*d&}|r||
)|*d& }d}d}nd"|dd  }|r| }n|}|}|}nytdkr-|s|d'kr|)|r|d( }	 | }|st+d) n|| }|)|rnq|, }|	)|}|r|*d&}|r||
)|*d& }d}d}n|r"|rt-|s| n|}n|}|}|}|du}nt.d*t#t d+|/ d t|f a|)|}|r|*d,}tj0|r\t1||dd- n@tj2tgt3 }d}|D ]}tj4||}tj0|rd}t1||dd-  nqi|st"d.t#|tj54|f  n|| |}qR|r| }n|}|}d+|/ d t|f a|)|}|r|*d,}tj0|rt1||dd- n@tj2tgt3 }d}|D ]}tj4||}tj0|rd}t1||dd-  nq|st"d.t#|tj54|f  n|| da|6  |r"|dd dS |\	a aaaaaaaadS )/z
    Read fortran codes from files and
     1) Get rid of comments, line continuations, and empty lines; lower cases.
     2) Call dowithline(line) on every line.
     3) Recursively call itself when statement "include '<filename>'" is met.
    NFr	   z*\s*include\s*(\'|")(?P<name>[^\'"]*)(\'|")z(?P<line>.*)&\s*\Zz(\s*&|)(?P<line>.*)z.*?'''r
   )r	   r	    c                 S   ro   r%   )strrp   r%   r%   r&   rs     rt   z#readfortrancode.<locals>.<listcomp>
   )r   Tzreadfortrancode: reading #z failed with
zu.
It is likely that installing charset_normalizer package will help f2py determine the input file encoding correctly.r   r   r   freez	Reading file %s (format:%s%s)
z,strict    z
r   r   z!f2pyr   )r   cr   Cr   f2pyz     H   zxreadfortrancode: Found non-(space,digit) char in the first column.
	Are you sure that this code is in fix form?
	line=%s   r,   .pyf
z.Unexpected end of file when reading multiline
z6Flag sourcecodeform must be either 'fix' or 'free': %szLine #%d in %s:"%s"
	rk   )
dowithlineistopzAreadfortrancode: could not find include file %s in %s. Ignoring.
)7r   r   r   r   r   beginpatternr   r   r   recompileIrange	fileinput	FileInputr   r   UnicodeDecodeError	Exceptionr   linenoisfirstliner   r   splitextr   r   r   COMMON_FIXED_EXTENSIONSr   _has_fix_headerr   beginpattern77beginpattern90r.   repr
expandtabsreplacesplit_by_unquotedr   rT   matchgroupri   rstripiscstyledirective
ValueError
filelinenoisfilereadfortrancodedirnamer#   joinpathsepclose)ffiler   r   saveglobalslocaldolowercasecont	finallinellincludelinecont1cont2
mline_markl1spacedigitsfinlmsgextis_f2py_directiverl_origfinalliner   lcmfninclude_dirs	foundfileinc_dirfn1r%   r%   r&   r   e  s  








(



	






   


r   zN\s*(?P<before>%s(?=\s*(\b(%s)\b)))\s*(?P<this>(\b(%s)\b))\s*(?P<after>%s)\s*\Zzqcharacter|logical|integer|real|complex|double\s*(precision\s*(complex|)|complex)|type(?=\s*\([\w\s,=(*)]*\))|byte.*rd   z|static|automatic|undefined)z([a-z]+[\w\s(=*+-/)]*?|)functionr   r   begin)z	[a-z\s]*?
subroutiner   r   zprogram|block\s*dataz@|module(?!\s*procedure)|python\s*module|(abstract|)\s*interface|ztype(?!\s*\()z\end|endprogram|endblockdata|endmodule|endpythonmodule|endinterface|endsubroutine|endfunctionendzDend\s*(if|do|where|select|while|forall|associate|critical|enum|team)z[\w]*?endifzmodule\s*proceduremoduleprocedure)r	   implicitr   r   r   )r	   dimension|virtualr   r   	dimension)r	   externalr   r   r   )r	   optionalr   r   r   )r	   requiredr   r   r   )r	   publicr   r   r   )r	   privater   r   r   )r	   	intrinsicr  r   r  )r	   intent|depend|note|checkr  z\s*\(.*?\).*intent)r	   	parameterr  z\s*\(.*r  )r	   datar  r   r  )r	   callr  r   r  )r	   entryr  r   r  )r	   callfunr  r   r  )r	   commonr	  r   r	  )r	   user
  r   r
  )r	   containsr  r	   r  )r	   formatr  r   r  )r	   Kthreadsafe|fortranname|callstatement|callprotoargument|usercode|pymethoddefr  r   f2pyenhancementsz2\s*(?P<before>''')(?P<this>.*?)(?P<after>''')\s*\Z	multilinec              	   C   sv   t dt |@ rJ dtdjdt|dt|ddd}|| }|r7| }|d	 |d
 fS | dfS )z
    Splits the line into (line[:i], line[i:]),
    where i is the index of first occurrence of one of the characters
    not within quotes, or len(line) if no such index exists
    z"'zcannot split by unquoted quoteszR\A(?P<before>({single_quoted}|{double_quoted}|{not_quoted})*)(?P<after>{char}.*)\Zz[^"'{}]z[{}]z('([^'\\]|(\\.))*')z("([^"\\]|(\\.))*"))
not_quotedr7   single_quoteddouble_quotedbeforeafterr	   )setr   r   r  escaper   	groupdict)r,   
charactersr   r   dr%   r%   r&   r     s   
r   c                 C   sB   g }t | dD ]}dD ]}||d}q|| q	d|S )N@,@z(),r   ,)markoutercommasplitr   appendr   )argslinear   r   r%   r%   r&   _simplifyargs  s   
r!  z"\s*(?P<result>\b[a-z]+\w*\b)\s*=.*z \s*(?P<bind>\b[a-z]+\w*\b)\s*=.*zH\s*bind\(\s*(?P<lang>[^,]+)\s*,\s*name\s*=\s*"(?P<lang_name>[^"]+)"\s*\)c                 C   s  t | d\}}|rCtd | sCtd | sC|dks!J t|t | d\} }|r<t| | t |dd d\} }|s*t| | dS |dk rsdatdiati iatg ia	g tt d< i tt d< dtt d< dtt d	< d
a
d
adS |dkrd}trt
tkrd}t|krtdttttf  td t	td  tt  t	t t	td  d
 d< t	t= td at|kstrt
tkrt	td  tt  t	t t	td  d
 d< t	t= td at	td  tt  t	t t	td  d
 d< t	t= td ad
a
dS | dkrdS d}tttttttttttttttttt t!t"t#t$t%ttt&fD ]}|d | }|r0 n|d }q"|st'}	dt  krHtkrIdS  dtt v rtt d D ]n}
|
t(v rat(|
 }
dtt v rs|
tt d v rsqVt)d|
 t*| t)j+}|r|	|,d}t-|,d}|rd|
||,df } nd|
|f } t.d | }|stdt|    dS t/|d|   dS qVt0dkst0dkrt12 3drda4tdt  dS |d dkr`dt  krtk rn ntd attkrdS tdkrt5dt td | }|r2|,dtt ks2t5dt|,dttt t6f ttkr9d
at	td  tt  t	t t	td  d
 d< t	t= td at7s^da8dS dS |d dkrdt  krstkr{n ntd adS da9t/||d |  da8dS |d dkrdS |d d krt/||d |  dS |d d!krt:rdS dt  krtkrdS  tadS tadS dt  krtkrdS  t/||d |  dS )"z
    reset=-1  --- initialize
    reset=0   --- crack the line
    reset=1   --- final check if mismatch of blocks occurred

    Cracked data is saved in grouplist[0].
    ;r   r   Nr	   bodyvarsblockrk   r
      z(crackline: groupcounter=%s groupname=%s
zYcrackline: Mismatch of blocks encountered. Trying to fix it by assuming "end" statement.
	externals
interfacedz5(?P<before>[^"]*)\b%s\b\s*@\(@(?P<args>[^@]*)@\)@.*\Zr  argszcallfun %s(%s) result (%s)r   zcallfun %s(%s)z8crackline: could not resolve function call for line=%s.
r  r   z"crackline:%d: No pattern for line
r   z>crackline: groupcounter(=%s) is nonpositive. Check the blocks.thiszGcrackline: End group %s does not match with previous Begin group %s
	%sr   r   r   r  );r   f2pyenhancementspatternr   multilinepatternr   	crackliner   	groupname
groupcacher   r   r   r   r.   r  dimensionpatternexternalpatternintentpatternoptionalpatternrequiredpatternparameterpatterndatapatternpublicpatternprivatepatternintrinsicpatternendifpattern
endpatternformatpatternr   functionpatternsubroutinepatternimplicitpatterntypespatterncommonpatterncallpattern
usepatterncontainspatternentrypatternmoduleprocedurepatterncrackline_re_1ry   r   markouterparenr   r   r!  callfunpatternanalyzeliner   r   r   endswithr$   r   r   r   r   r   r   )r,   resetr   has_semicolonsemicolon_lineflr-   patr   re_1rk   m1m2r   r%   r%   r&   r-    s4  

	

 
$


r-  c                 C   sd   d}d}| D ])}|dkr|d }|dkr|d }qn|dkr+|d }|dkr+|d }q|| }q|S )Nr	   r   (r   @(@)@)@r%   )r,   r   fr   r%   r%   r&   rH  W  s    
rH  r  c                 C   s   d}d}t | |d \}}||7 }|rT|d |kr&|dkr&|d| d 7 }n||d 7 }|d dkr7|d7 }n
|d dkrA|d8 }t |dd  |d \}}||7 }|s|r_J t|| |f|S )Nr	   r   ()@rT  r   rV  )r   r   )r,   commar   rX  r  r  r%   r%   r&   r  i  s"   
r  c                 C   s   |  dd dd}|S )NrU  rT  rW  rV  )r   )r,   r   r%   r%   r&   unmarkouterparen|  s   r\  c                 C   s   | si } |s| S | |u r| S t | D ]g}|dkr'|s || vr&|| | |< q|dkr9|| D ]}t| ||} q/q|dkrFt| || |} q|dkrSt| || |} q|dv rd|s]|| vrc|| | |< q|dkriq|dv rttd|  qtd	t| | S )
Nr0   attrspeckindselectorcharselector)=typenamenote)r  checkr   r   r   dependz"appenddecl: "%s" not implemented.
z-appenddecl: Unknown variable definition key: )listkeyssetattrspecsetkindselectorsetcharselectorri   r   r   )decldecl2forcekr   r%   r%   r&   
appenddecl  s>   rn  zD\s*(?P<this>(@\(@.*?@\)@|\*[\d*]+|\*\s*@\(@.*?@\)@|))(?P<after>.*)\Zz[(?:,(?P<attributes>[\w(),]+))?(::)?(?P<name>\b[a-z$_][\w$]*\b)(?:\((?P<params>[\w,]*)\))?\Zz\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*\ZzF\s*(?P<scheme>(operator|assignment))@\(@\s*(?P<name>[^)]+)\s*@\)@\s*\Zz9\s*(?P<name>\b[\w$]+\b)\s*@\(@\s*(?P<args>.*)\s*@\)@\s*\Zz4([-+]?(?:\d+(?:\.\d*)?|\d*\.\d+))[dD]((?:[-+]?\d+)?)zA([-+]?((?:\d+(?:\.\d*)?|\d*\.\d+))[eE]((?:[-+]?\d+)?)|(\d+\.\d*))zintent\s*\(.*?\bcallback\bc                 C   s&   |  dg D ]
}t|r dS qdS )Nr]  r   r   )get_intentcallbackpatternr   )vdeclr   r%   r%   r&   _is_intent_callback  s
   
rr  c                 C   sl   d |  } t| }t| | |r1|d}|r$dd |dD ng }|d||dfS d g d fS )Nr	   
attributesc                 S      g | ]}|  qS r%   )r   )rq   r   r%   r%   r&   rs     rt   z*_resolvetypedefpattern.<locals>.<listcomp>r  rk   params)r   r  typedefpatternr   printr   )r,   rR  attrsr%   r%   r&   _resolvetypedefpattern  s   



ry  c                 C   sR   t dt j}|| }d }|r%|d}| d |  | | d   } | |fS )NzObind\(\s*(?P<lang>[^,]+)(?:\s*,\s*name\s*=\s*["\'](?P<name>[^"\']+)["\']\s*)?\)r   )r   r   r   searchr   startr   )r,   patternr   bind_statementr%   r%   r&   parse_name_for_bind  s   

 r~  c                 C   s   t | \} }t| } t| }|r |d|d|d|fS t| }|r;|dd |d d }|g d d fS t| }|rN|d|dd d fS d g d d fS )Nrk   r)  r   schemerT  rV  )r~  rH  nameargspatternr   r   operatorpatterncallnameargspattern)r,   
bind_cnamerR  rk   r%   r%   r&   _resolvenameargspattern  s   


r  c           G      C   s  |  d}|dkrdatrZ|dvrZtsZtdk rZtjt	dd }t
d|  datd ad	tt< i tt< g tt< g tt d
< i tt d< d	tt d< |tt d< dtt d< da|dv r	| }td|tjrnd}ntd|tjryd}n
td|tjrd}|dkrt|  d\}}}t|dtt d |< g }d}	nt|  d\}}}	}
|du r|dkrd}nd}|dvrt
d ||tfa|rtdd t|	d D }ng }d|v rd|v r|d d|v st
d! d}d}|d"v r1d}d#tt vrdS |tt d# vrdS tt D ]}|d |kr dS q|tt d$ v r*dS d%d&d"| }trKtd'krKtdkrKtd( ad}|d)vrKd}td ai tt< g tt< |rtdkrht
d*tt d d+tt< dtt d< ttt d< dtt d< g tt d
< g tt d,< g tt d$< i tt d< td ai tt< g tt< |rtdkrt
d-t d d.tt< d.tt d< d/tt d< d0ttd  d ttd  d f tt d< g tt d
< g tt d,< g tt d$< i tt d< td ai tt< g tt< |tt< |tt d< |sd1|d2d3 }|  d4tt d5< t|tt d< |	tt d6< tdkr3ttt d< n/trLtd7krLd0ttd  d tf tt d< nd0ttd  d ttd  d f tt d< ttt   D ]}tt | sxtt |= qj|tt d#< g tt d
< g tt d,< g tt d$< i tt d< i tt d8< |dkrg tt d9< |d"v r|ttd(  d, vrttd(  d, !| t"#ttd(  d tt d< ztt d | tt d | d: $d;= W n
 t%y   Y nw |d<v r|
r-t&t'|
}|r-|i itt d=< | d>tt d= | d>< | d?r-| d?tt d= | d< zt(tt d | ttd(  d d tt d |< W n
 t%yR   Y nw |d@kr|	r|	tt d v r||	kst(tt d | tt d |	 tt d |< zttd(  d$ !| W n
 t%y   Y nw |d&krt)d |  d4d2 | }|rt*| d| d\}}}}t+|||| |d"v rttd  !tt  tt ttd  d' d
< tt= td attd  !tt  tt ttd  d' d
< tt= td adS dS |d8krNt|  d\}}}	}|durL|r0tdAd t|	d D }ng }|	du s=J t|	|tt d8 |< d8|tfadS dS |dkrtt*||  d\}}}}t+||||}|durrdB|tfadS dS |dCv rDtt d }|  d, }|-dD}|dk r|dEkrt.|-dFd( }|d|d  dD ||d d  }|-dD}||d dDkrd#tt v rt
dG|  d|d| f  |dH/tt d#  }|dk rd}d}n|d| , }||d( d }t|	d }t0|dkr|d }t
dIdH/|dd   d}dJd t|	d D D ]}t1|}|sK|dKv r9d}nt2| 3  t
dL|t|f  q&t| d}|dKv rh|dMksa|dNkrh|| d7 }||vrqi ||< |dOkr}|| d }|dEkr|  d| }t4|r|tt d# vrtdkrdPttd(  d vrt
dQ |tt d krt
dR|tt d f  tt d# !| nt5dS|  nt5dT|  |dUv r|}d:|| v r|| d: !| n|g|| d:< |d;kr,tt d d	krt
dV q&|tt d# vrq&d,tt vr#g tt d,< tt d, !| |}q&|tt d< |durBdB|tfadS dS |dWkr\dXd |  d	dHD tt dY< dS |dZkrtt d }|  d, dd' }d}t|	d D ]}zd[d |	d\D \}}W n t%y   t
d]||f  Y q{w t6|}t|}||vri ||< d\|| v r|| d\ |kst
d^||| d\ |f  t7||}|r"|8d_d`kr
t|}t9:|D ]} t|| ; | <   dadb|| ; | < < qd/|}n|8d_dckr"|dd  dadbdHdd}zt=|i |} W n t>t?t@fyI }! zt5de||!f  W Y d}!~!q{d}!~!ww t| || d\< d:|| v rc|| d: !dZ ndZg|| d:< |}q{|tt d< |durdB|tfadS dS |dfkr|  d,  dgkrdtt df< dS |  drdftt v rtt df }"ni }"|"du rt
dh i }"t|  d	d D ]}i }#tdi|tj}|st
dj|  qtA| d}$|$st
dk|  qt*|$ d|$ d\}}}}tB||\}%}&}'||#d_< |%|#dl< |&|#dm< |'|#dn< t|#  D ]}|#| s'|#|= qt| d	d D ]\}(do|(v rZzdpd |(	doD \})}*W n t%yY   t
dq|(  Y q3w |(,  })}*t0|)t0|*  krpdksyn t
dr|(  q3tCtD|)tD|*d D ]	}+|#|"tE|+< qq3q|"tt df< dS dS |dsk
rg }d},d}-d}.d}/d}0|  dD ]i}1|0s|1dtkr|/ }/|1dukr|/r|.d }.q|1dvkr|0d }0n	|1dwkr|0d }0|.dkr|,|1 },q|.dkr|-|1 }-q|.d(k	r|,, },|,FdH	r|,dd , },|!|,|-g |1},d}-d}.q|.d(k	r:|,, },|,FdH	r3|,dd , },|!|,|-g tt 8di }2d}|D ]*}3|3d , |3d , |3d< |3d< |3d FdH	rl|3d dd |3d< |3d Fdv	r~t
dx|3d   	qFtGtdyd t|3d 	d D D ]\}4} | Fdv	rt
dx|   	qdz|3d v 	rt
d{|3d   	q|2H| i  |2|  8d_}5tI|2|  }6|5dck	rtJd||3d n|3d 	dH}7z|6	rd}Kd~/|7n|7|4 }8W nb tL
yM   tMdd |7D 
r<g }9|7D ]8}:d|:v 
r1z|:	d\};}<|9N|<, gtO|;  W 
q tP
y0   |9!|:,  Y 
qw |9!|:,  
q|9}7|6
rGd}Kd~/|7n|7|4 }8Y nw |2|  8d\}=|=
rf|=|8k
rft
d| |=|8f  |8|2|  d\< | }	q	qF|2tt d< |
rdB|tfadS dS |dkr=|  d, }|d duk
sd| }g }>d}.d}?d}@|D ]:}1|1duk
r|.d }.
q|.d7k
r|?, }?|?
sd}?|>!|?|@g |.d( }.d}?d}@|.d( 
r|?|1 }?
q|@|1 }@
q|?, }?|?
sd}?|>!|?|@g i }Adtt v 
rtt d }A|>D ].}1|1d |Avrg |A|1d < dd t|1d 	d D D ]}|r,|A|1d  !| qq|Att d< d|?tfadS |dkrtd|  dtj}|r|3 }Bdtt vrai tt d< | d}i tt d |< d}Cd|Bv r|Bd durd|Bv r|Bd du rd}C|Ctt d | d< dd |Bd 	dHD }i }D|D ]9}3d\|3v rtd|3tj}$|$r|$ d, |D|$ d, < nt
dt|3  n|3|D|3< |Dtt d | d< qdS 	 dS t2| 3  t
d dS |dv r;dtt vri tt d< tt d }E|  ddkr/d|Ev r/tQ|Ed tRr#|Ed g|Ed< |Ed !|  d dS |  d|E|  d< dS |dkratdu rNtrLt
d dS t}FtSt|F tdd( |  d dS tdkrrt2| 3  t
d dS dS )a  
    Reads each line in the input file in sequence and updates global vars.

    Effectively reads and collects information from the input file to the
    global variable groupcache, a dictionary containing info about each part
    of the fortran module.

    At the end of analyzeline, information is filtered into the correct dict
    keys, but parameter values and dimensions are not yet interpreted.
    r*  r  N)r   r  r  rd   r   .r   zBanalyzeline: no group yet. Creating program group with name "%s".
programr#  r$  r%  rk   fromskyfrom)r   r  r  zblock\s*data
block datazpython\s*modulepython modulezabstract\s*interfaceabstract interfacerd   r  )r]  _BLOCK_DATA_r	   )	interfacer  r  z2analyzeline: No name/args pattern found for line.
c                 S   rt  r%   r   rq   xr%   r%   r&   rs         zanalyzeline.<locals>.<listcomp>r  z<analyzeline: argument list is malformed (missing argument).
)r  r  r)  r(  r   r   r
   r&  r  r  z&analyzeline: Creating module block %s
moduler'  zDanalyzeline: Creating additional interface block (groupcounter=%s).
r  unknown_interfacez%s:%sunknown_r   r   r  prefixr      r  varnamesr]  r   r   r   bindlanglang	lang_namer  c                 S   rt  r%   r  r  r%   r%   r&   rs     r  variable)r   r  r   r   r   r   r   r  ::r  rW  z'All arguments will have attribute %s%s
r  zXanalyzeline: cannot handle multiple attributes without type specification. Ignoring %r.
c                 S   rt  r%   r  r  r%   r%   r&   rs     rt   r   r   zEanalyzeline: no name pattern found in %s statement for %s. Skipping.
operator
assignmentr   __user__z8analyzeline: missing __user__ module (could be nothing)
z;analyzeline: appending intent(callback) %s to %s arguments
z,analyzeline: intent(callback) %s is ignored
z=analyzeline: intent(callback) %s is already in argument list
)r   r   r   r   r   r  z(analyzeline: ignoring program arguments
r   c                 S   rt  r%   r  r  r%   r%   r&   rs     rt   implementedbyr  c                 S   rt  r%   r  r  r%   r%   r&   rs     rt   r`  zManalyzeline: could not extract name,expr in parameter statement "%s" of "%s"
zGanalyzeline: Overwriting the value of parameter "%s" ("%s") with "%s".
r0   r1   r  ecomplexz+1j*(z1analyzeline: Failed to evaluate %r. Ignoring: %s
r   nonez<analyzeline: Overwriting earlier "implicit none" statement.
z9\s*(?P<this>.*?)\s*(\(\s*(?P<after>[a-z-, ]+)\s*\)\s*|)\ZzDanalyzeline: could not extract info of implicit statement part "%s"
zManalyzeline: could not extract types pattern of implicit statement part "%s"
r^  r_  ra  -c                 S   rt  r%   r  r  r%   r%   r&   rs   g  rt   zZanalyzeline: expected "<char>-<char>" instead of "%s" in range list of implicit statement
z^analyzeline: expected "<char>-<char>" instead of "%s" in range list of implicit statement (2)
r  '/rT  rV  z>analyzeline: implied-DO list "%s" is not supported. Skipping.
c                 S   rt  r%   r  r  r%   r%   r&   rs     rt   r   z=Comment line in declaration "%s" is not supported. Skipping.
z\(.*?\)z(/{}/), c                 s   s    | ]}d |v V  qdS )r   Nr%   )rq   r   r%   r%   r&   	<genexpr>      zanalyzeline.<locals>.<genexpr>r   z=analyzeline: changing init expression of "%s" ("%s") to "%s"
r	  z//_BLNK_c                 S   rt  r%   r  r  r%   r%   r&   rs     rt   r
  zR\A\s*(?P<name>\b\w+\b)\s*((,(\s*\bonly\b\s*:|(?P<notonly>))\s*(?P<list>.*))|)\s*\Zre  notonlyonlyc                 S   rt  r%   r  r  r%   r%   r&   rs     rt   z7\A\s*(?P<local>\b\w+\b)\s*=\s*>\s*(?P<use>\b\w+\b)\s*\Zlocalz0analyzeline: Not local=>use pattern found in %s
mapz0analyzeline: Could not crack the use statement.
)r  r  usercodez-analyzeline: No context for multiline block.
z+analyzeline: No code implemented for line.
)Tr   r$   r   r   r   r   r   basenamer   r  r.   r   r.  r/  r   r   r   r   r   ry  dictr  rw   r  remover   r   r   r   r   rl   re  rf  r  copydeepcopyrW   r   rz  crackline_bindlangrn  r@  cracktypespec0
updatevarsr   findrH  r   rT   namepatternrw  r  rp  ri   get_parametersdetermineexprtypero  real16patternfinditerr{  r   evalSyntaxError	NameError	TypeErrortypespattern4implicitcracktypespecr   ordchrr   	enumerate
setdefaultgetdimensionfindallr  
IndexErroranyextendr4   r   
isinstancer   appendmultiline)Gr   r;   r,   r%  newnamerk   rx  r   r)  r   	bindcline
needmoduleneedinterfaceitrm  bindcdattr0   selectorattredecl	last_namer   iplchr  rR  apinitexprru  ttvr   implrj  rS  
kindselect
charselectra  r   begcendcodlilrX  fcinpr   r$  r   idxvtypevdimmatchesnew_valexpanded_listr   
multipliervaluecurrent_valclbnol	commonkeymmisonlyr   r  gcr%   r%   r&   rJ    s  













 








	



$
 














 






"
2








",("
",



 








rJ  c                 C   s:   d| vri | d< | d }||vrg ||< ||  | d S )Nf2pymultilinesr  )r   context_namemlr  r%   r%   r&   r  2  s   r  c                 C   s   d }d }t d| t jrd} nt d| t jrd} n|   } tt|}|s/td d S | }t	|
 D ]
}t|| ||< q9| dv rP|d }|d }|d	}|d
kri|d |  }||d d  }| |||fS )Nzdouble\s*complexdouble complexzdouble\s*precisionzdouble precisionz>cracktypespec0: no kind/char_selector pattern found for line.
)r  r3   logicalr1   	characterrd   r*  r  r  r   r&  )r   r   r   r   r   selectpatternrH  r.   r  re  rf  r\  r  )r0   r   r  r  rR  r  rm  r  r%   r%   r&   r  <  s0   
r  z)\s*(?P<name>\b\w+\b)\s*(?P<after>.*)\s*\ZzB\s*(\(\s*(kind\s*=)?\s*(?P<kind>.*)\s*\)|\*\s*(?P<kind2>.*?))\s*\Zz2\s*(\((?P<lenkind>.*)\)|\*\s*(?P<charlen>.*))\s*\Zz\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>.*)|(f2py_len\s*=\s*(?P<f2py_len>.*))|))\s*\Zz\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*\Zc                 C   s   |   } t| dkr| S | d }tdt| d D ]}| | dkr2| |d  dv s1| |d  dv r2q|| |  }q|| d  }|S )Nr   r   r   z()[]{}=+-/* r
   )r   rT   r   )exprexpr2r  r%   r%   r&   removespacesc  s   r  c                 C   s~   d}d}d}d}| D ]2}|dkr|dv r||7 }|}q
|s#|dv r#|}||kr+| }n|dkr6|r6|d7 }q
||7 }|}q
|S )	a(  
    The function replace all spaces in the input variable line which are 
    surrounded with quotation marks, with the triplet "@_@".

    For instance, for the input "a 'b c'" the function returns "a 'b@_@c'"

    Parameters
    ----------
    line : str

    Returns
    -------
    str

    r	   FN\)r	  r  ")r  r
  r   @_@r%   )r,   fragmentinsidecurrent_quoteescapedr   r%   r%   r&   markinnerspacesr  s&   r  c              	   C   s8  d}t | |\}}}|rFdd t|dD }g }td}	|D ]"}
|
s&q!|	|
}|r>|d }||
t|d  }
|	|
 q!|}dd t|dD }g }|D ]"}dd tt
t|d	d
dD D ]}|rw|	|dd	 qjqV|D ]}t|}|stdt|  q{t|d}i }|tt d v rtt d |  }d|v}|r| |d< n| r| |d kstd||d | f  d|vrt||d< n:|rt| D ]0}||d v r|| |d | kstd|||d | || f  qt|| |d |< qd|vr'|r'|r||d< nEtd||f  n<|rct| D ]2}||d v rV|| |d | ksVtd|||d | || f  q0t|| |d |< q0d|vrm||d< n|r|d |kstd||d |f  d|vrt||d< n8|r|D ]}
|
|d vr|d 	|
 qn t| |d< t||d< t||d< ||d< t||d< d|dpg v r|tt d v rdtt vrg tt d< tt d 	| |drmtt|d}|rb| }dD ]}||d  dur"||d  ||< ||d = q
t| D ]}|| dur=t|| ||< q*||= q*d |v rd!|v r|d  d"kr]|d! |d < |d!= nG| d#krd|vsl|d spi |d< d |d v r||d d = |d  |d d$< |d = n|d! d% |d   |d!< |d = td&| || ||d! f  d |v r| d'v rd|vs|d si |d< |d  |d d$< |d = n*| d#krd|vs|d si |d< d |d v r|d d = |d  |d d$< |d = d(|v rd)|v r|d) |d( kstd*||d) |d( f  n|d( |d)< d!|v rad+|d!  }d|vs.|d s4|g|d< n9|d 	| |d D ]!}|dd, d-kr_||kr_|d d.= td/|||f   nq?ntd0||d   t| D ]}|| s}||= qs|tt d |< d1tt v rtt d1 	| |}q{|S )2z
    Returns last_name, the variable name without special chars, parenthesis
        or dimension specifiers.

    Alters groupcache to add the name, typespec, attrspec (and possibly value)
    of current variable.
    Nc                 S   rt  r%   r  r  r%   r%   r&   rs     rt   zupdatevars.<locals>.<listcomp>r  z(?P<start>[a-zA-Z]+)r{  c                 S   rt  r%   r  r  r%   r%   r&   rs     rt   c                 S   rt  r%   r  r  r%   r%   r&   rs     rt   r   r[  z@ @r  z;updatevars: no name pattern found for entity=%s. Skipping.
rk   r$  r0   zIupdatevars: attempt to change the type of "%s" ("%s") to "%s". Ignoring.
r^  zVupdatevars: attempt to change the kindselector "%s" of "%s" ("%s") to "%s". Ignoring.
r_  zEupdatevars:%s: attempt to change empty charselector to %r. Ignoring.
zVupdatevars: attempt to change the charselector "%s" of "%s" ("%s") to "%s". Ignoring.
ra  zMupdatevars: attempt to change the typename of "%s" ("%s") to "%s". Ignoring.
r]  r   r)  r'  r  )rT   arrayinit2rT   r  r	   r  r   r  z-updatevars: "%s %s" is mapped to "%s %s(%s)"
r  r3   r  r1   r  r`  zTupdatevars: attempt to change the init expression of "%s" ("%s") to "%s". Ignoring.
dimension(%s)	   r   r
   z5updatevars:%s: attempt to change %r to %r. Ignoring.
z?updatevars: could not crack entity declaration "%s". Ignoring.
r  )r  r  r  r   r   r   r   r   rT   r  r  r  r   r  r.   r   rl   r/  r   r  re  rf  ri   ro  lenarraypatternrH  r  r\  )r0   r  r]  
entitydeclr  r  r  ra  r   r   r   r   selel1r  e1enamer  not_has_typespecrm  rR  d1lkdmdm1r%   r%   r&   r    s<  


(




$

$



(












r  c           	      C   s  d }d }d }|r| dv rLt |}|stdt|  d S | }|d |d< |d= t| D ]	}|| s9||= q0t| D ]
\}}t|||< q@n| dkrt	|}|satdt|  d S | }|d |d< |d= |d rt
t|d }| }d	D ]}||d
  r||d
  ||< || ||< ||d
 = q|d d ur|d |d< |d= t| D ]	}|| s||= qt| D ]
\}}t|||< qn'| dkrtd|tj}|r|d}ntdt| |   ntdt|  |||fS )Nr  z4cracktypespec: no kindselector pattern found for %s
kind2r   r  z4cracktypespec: no charselector pattern found for %s
charlenlenkind)rT   kindr  f2py_lenrd   z\s*\(\s*(?P<name>\w+)\s*\)rk   z'cracktypespec: no typename found in %s
z'cracktypespec: no selector used for %s
)r^  r   r.   r   r  re  rf  itemsrl   r_  lenkindpatternr  r   r   r   )	r0   r  r  r  ra  rm  r  r&  r!  r%   r%   r&   r  @  s|   






r  c                 C   s   | si } |s| S d| vr|g| d< | S |r| d  | || d v r$| S |dkr7d| d vr7| d  | | S |dkrJd| d vrJ| d  | | S |dkr]d| d vr[| d  | | S |dkrpd| d vrn| d  | | S | d  | | S )Nr]  rF   	automaticr   r   r  )rj  r  rl  r%   r%   r&   rg  |  s6   
	rg  c                 C   Z   | si } |s| S d| vr|| d< | S t | D ]}|s"|| d vr*|| | d |< q| S )Nr^  re  rf  rj  selrl  rm  r%   r%   r&   rh    s   rh  c                 C   r,  )Nr_  r-  r.  r%   r%   r&   ri    s   ri  unknownc                 C   s   d| v r| d S |S )Nrk   r%   )r%  r0  r%   r%   r&   getblockname  s   r1  c                 C   s0   zd| d | d f a W d S  ty   Y d S w )Nz
In: %s:%s
r  rk   )r   r   )r%  r%   r%   r&   setmesstext  s
   r2  c                 C   s2   i }d| v rt | d }d| v r|| d  |S )Nparent_blockr
  )get_usedictupdate)r%  usedictr%   r%   r&   r4    s   r4  c           	      C   s   |d u ri }t | }|s|S t| D ]J\}}| }|tvr,td|| df  qt| }t|}|s7q|r?td|  t| D ]\}}||v rYtdt	|t	|f  |||< qEq|S )Nz0get_useparameters: no module %s info used by %s
rk   z,get_useparameters: mapping for %s not impl.
zEget_useparameters: overriding parameter %s with value from module %s
)
r4  re  r)  r   r   r.   ro  r  ri   r   )	r%  	param_mapr6  usenamemappingmvarsru  rm  r  r%   r%   r&   get_useparameters  s4   
r;  c           
         s   t s| S t| tr fdd| D }|S t|  td| d f d  d u r,t|   d ur_d| v r_| d }t| D ] }|| }d|v r^|d }d|v r^|d }| v r^ | |d< q> fd	d| d
 D }	|	| d
< | S )Nc                       g | ]}t |d   dqS r   )tabr7  
postcrack2)rq   gr7  r>  r%   r&   rs         zpostcrack2.<locals>.<listcomp>%sBlock: %s
rk   r   r$  r^  r'  c                    r<  r=  r?  rq   brB  r%   r&   rs     rC  r#  )r   r  re  r2  r.   r;  rf  )
r%  r>  r7  retr$  r   varr'  valnew_bodyr%   rB  r&   r@    s6   
r@  c                 C   s8  t | tr3g }g }| D ]#}t| t||d d}d|v r)d|d v r)|| q|| q|| S t|  t | tsHd| vrHtdt|  d| v r]| d dks]td|| d f d	 t	| } t
| } t| | d
< t| d
 | d< | dr|| d }t| ||d| d< g }d| v r| d }t| D ]}d|v r|| qni }d}	d| v r| d }	| drg }
d| v r| d }
t| d
 }|	r|	d }nd}||v rd}d||f |v r|d }d||f |v sd||f }dg i |	d d}| d D ]u}||
v r\g }d}| d D ]I}|d }|d dkrRd}|d D ]}|d }d|v r;|d |kr;t|}|d |=  nq|rR|d sJ| d |= |
|
|=  nq
|d | q||v rpt|| sp|| |d
 |< q|d
 s{|d r|
| d< d|gi || d d}i ||< t| |r|| d< | S )zi
    TODO:
          function return values
          determine expression types if in argument list
    r   r>  rk   r  r%  z0postcrack: Expected block dictionary instead of r  rD  r   r$  sortvarsr)  r#  r
  r	   r'  r(  __user__routinesunknown__user__routinesr   z%s_%ir  _user_interface)r%  r#  r$  rk   r
   r  )r%  r#  r$  rk   r(  )r  re  r2  	postcrackr  r  r   r   r.   analyzeargsanalyzecommonanalyzevarssortvarnamesro  analyzebodyrf  r  rW   
isexternalr   )r%  r)  r>  greturetrA  userisdefineduseblockrm  rk   r(  r:  mnamer  r  r  edefjrF  bbmblockr%   r%   r&   rP    s   










rP  c                 C   s  g }g }t |  D ]}d| | v r| | d r|| q
|| q
t|}d}|r|d }d}|dd  D ]}|| | d v rFd} nq8|rm|dd  |g }|d }||krltdd| d  || }	 |S n|| |dd  }t|}d}|s,|S )Nrd  r   r   zTsortvarnames: failed to compute dependencies because of cyclic dependencies between r  r   )re  rf  r  rT   ri   r   )r$  indepdepr  r   r  rO  wr%   r%   r&   rT  l  sF   
rT  c                 C   s~  t | s| S g }t| d  D ]}g }| d | D ]}td|tj}|rg }|dr<dd t|ddD }t	|d
 }|| d v rsd	| d | v rd| d | d	 d
d|  n&d
d| g| d | d	< n|rd	d
d| gi| d |< ni | d |< ||vr|| n
|}td||f  || q|| d |< qd| vr|| d< | S | d | | d< | S )Nr	  z2\A\s*\b(?P<name>.*?)\b\s*(\((?P<dims>.*?)\)|)\s*\Zdimsc                 S   rt  r%   r  r  r%   r%   r&   rs     r  z!analyzecommon.<locals>.<listcomp>r  rk   r$  r]  r  r  zNanalyzecommon: failed to extract "<name>[(<dims>)]" from "%s" in common /%s/.

commonvars)	hascommonre  rf  r   r   r   r   r  r  rl   r   r  r   ri   )r%  rd  rm  comvarsr  r   rc  r   r%   r%   r&   rR    sR   


rR  c                 C   s<  t |  dd | d  D }g }| d D ]}| |d< |d dv rY|d ur,|d |vr,q|d	 }|d | v r?t|d  |d tv rFqtrO|d tvrOqt|d
dd|d< n|}t|||d d}|d dv rx|d sx|dsxd|vrxq|d 	dddkrt
| q|d dkr|d t|d < || q|S )Nc                 S   s*   i | ]\}}d |vsd|d  vr||qS )r]  r   r%   )rq   keyr  r%   r%   r&   
<dictcomp>  s
    zanalyzebody.<locals>.<dictcomp>r$  r#  r3  r%  r  rk   r)  z
      Tas_interfacesaved_interfacer   rK  r  r  r  r   r	   pythonmoduler  )r2  r)  rf  r!   r  r"   crack2fortrangenrP  ro  r   r   r   )r%  r)  r>  maybe_privater#  rF  as_r%   r%   r&   rU    sF   
rU  c                 C   s   t |  t}i }d| v rO| d d u r&d }tdkr"tdt| d   ||fS t| d  D ] }| d | ddvrD| d | ||< q.| d | d ||< q.||fS )Nr   r   z6buildimplicitrules: no implicit rules for routine %s.
rk   r0   )rF   r+  )r2  defaultimplicitrulesr   r.   r   re  rf  ro  )r%  implicitrules	attrrulesrm  r%   r%   r&   buildimplicitrules  s    rs  c                 C   s,   t | ||}t|ttfv r|S td| )z2 Like `eval` but returns only integers and floats zr=%r)r  rd   r4   r6   r   )r  rA  r   r   r%   r%   r&   myeval  s   rt  z\A\b\w+\b\Zc              	   C   s
  zt t| i i }d|dfW S  ty   Y nw t| r"dd| fS t| }|D ]}t||kr1q(td| d | r<q(td| d tj	}|| }|rz|| }|rkd|
d	d|
d
f }||}|sWt|i i }	|| }|rd|
d	d|
d
f }||}|sxt|i i |	 }
|| }|rd|
d	d|
d
f }||}|st|i i }|| }|rd|
d	d|
d
f }||}|st|i i }|
d |	 |kr|
d |	 |kr|
|	|fW   S W  dS W  dS  ty   Y  dS w q(dS )a  
    Obtain ``a`` and ``b`` when ``e == "a*x+b"``, where ``x`` is a symbol in
    xset.

    >>> getlincoef('2*x + 1', {'x'})
    (2, 1, 'x')
    >>> getlincoef('3*x + x*2 + 2 + 1', {'x'})
    (5, 3, 'x')
    >>> getlincoef('0', {'x'})
    (0, 0, None)
    >>> getlincoef('0*x', {'x'})
    (0, 0, 'x')
    >>> getlincoef('x*x', {'x'})
    (None, None, None)

    This can be tricked by sufficiently complex expressions

    >>> getlincoef('(x - 0.5)*(x - 1.5)*(x - 1)*x + 2*x + 3', {'x'})
    (2.0, 3.0, 'x')
    r   Nr   z\w\s*\([^)]*\b\b(?P<before>.*?)\b\b(?P<after>.*)z%s(%s)%sr  r  g      ?g      ?)NNN)r4   rt  r   getlincoef_re_1r   rT   r   rz  r   r   r   )r  xsetr   len_er  rQ  r   rR  eerF  r   c2r%   r%   r&   
getlincoef	  s   










  r}  z\b[a-z][\w$]*\bc                 C   s   | |v rW||   dg }d||  v r5t||  s5t||  d D ]}||vr4||v r4|| kr4|| q!|d d  D ]}| |g pHt|||D ]}||vrT|| qIq;n
tdt|   g }||| < |S )Nrd  r`  z,_get_depend_dict: no dependence info for %s
)ro  isstringword_patternr  r  _get_depend_dictr.   r   )rk   r$  depswordswordrb  r%   r%   r&   r  N	  s(   


r  c                 C   s*   t |  }i }|D ]}t|| | q
|S r(   )re  rf  r  )r$  rv   depend_dictr   r%   r%   r&   _calc_depend_dictd	  s
   r  c                    s   t  g }t  D ]} | s||  |= q rBt  D ]\}} fdd|D }|s;||  |= q#| |< q# sfdd|D S )Nc                       g | ]}| v r|qS r%   r%   )rq   r   )r  r%   r&   rs   u	      z$get_sorted_names.<locals>.<listcomp>c                    r  r%   r%   )rq   rk   r$  r%   r&   rs   {	  r  )r  re  rf  r  r)  )r$  rv   rk   lstnew_lstr%   )r  r$  r&   get_sorted_namesl	  s    


r  c                 C   s@   | d dv r| dd } t | rdS t| rdS d|  d S )	Nr   '"r   r
         zkind(rV  )r  r   real8pattern)r_   r%   r%   r&   
_kind_func~	  s   

r  c                 C   sL   d|  }|dkr
dS |dkrdS |dkrdS |dkrd	S |dd
 kr$dS dS )Nr      r   i   r&  l        r  l            r        r
   r%   )r   r   r%   r%   r&   _selected_int_kind_func	  s   r  c                 C   sZ   | dk rdS | dk rdS t   }|dr| dkrdS d	S | dk r%dS | dkr+dS d	S )
N   r  r  r  )
aarch64alphaarm64	loongarchmipspowerppcriscvs390xsparc!      r   r
   )platformmachiner   r   )pr   radixr  r%   r%   r&   _selected_real_kind_func	  s   
r  c                 C   s:  t  |}t  |}dtfdtfdtffD ]\}}||vr!|||< qg }t| D ]}d| | v r=d| | d v r=|| q(tdtj}tdtj}	tdtj}
|D ]D}d	| | v r| | d	 }t	| | ry|
 }d
D ]}|j| }qq|d|}|	d|}d}d| | v rd| | d v rt|}|d| | d d  d}t||k }|s|
|s|d}t|dkrd|d d 
 |d 
 d}t| | rt|}t|D ]}t|| |  
 dd|| | < qd|}nt| | rtd| d dd | | d D p"d gd }t|r.d}nt|r6d}zt||||d||< W n" tyd } z|||< td| d|d W Y d }~nd }~ww t| | r|t|| tr|t || ||< |
 }||kr|| ||< qUt!| |  td|d  qU|S )!Nr'  selected_int_kindselected_real_kindr]  r  z \bkind\s*\(\s*(?P<value>.*)\s*\)z-\bselected_int_kind\s*\(\s*(?P<value>.*)\s*\)z4\bselected_(int|real)_kind\s*\(\s*(?P<value>.*)\s*\)r`  ))z.false.False)z.true.Truez
kind("\1")zselected_int_kind(\1)Fr^  r   r	   r   r
   r  r  zAget_parameters[TODO]: implement evaluation of complex expression r   c                 S   s$   g | ]}| d r|d  qS )r   )r   removeprefixr   rq   r  r%   r%   r&   rs   	  s    z"get_parameters.<locals>.<listcomp>r   r  r  )dimspeczget_parameters: got "" on zget_parameters:parameter z does not have value?!
)"r  r  r  r  r  r  r   r   r   	islogicalr   r   subrT   r   r  r   isdoublere  r  r  r{  r   	iscomplexr.   rz  r  
param_evalr   r~  r  r4   r  rw  )r$  global_paramsru  g_paramsrk   funcparam_namesr   kind_reselected_int_kind_reselected_kind_rer  replis_replaced
orig_v_lenv_r  r   r  r   nlr%   r%   r&   r  	  s   





&


"
r  c                 C   s   | dv rdS t | |S )N)z(:)(*)r   r  )_eval_scalar)lengthru  r%   r%   r&   _eval_length
  s   
r  z\d+_c              
   C   s   t | r| dd } zt| i |} t| trtnt| } W | S  tttfy-   |  Y S  t	yL } zt
d|| t| f  W Y d }~| S d }~ww )Nr   r   z,"%s" in evaluating %r (available names: %s)
)_is_kind_numberr  r  r  r   r   r  r  r  r   ri   re  rf  )r  ru  r   r%   r%   r&   r  
  s   r  c           >         s  t |  t| \}}t| d | d dkr#| d vr#i | d < d| d v rbd= d| d d v rb| d d d }ttdd | d	 D B D ]}d
D ]}||v r`t|i ||< qOqKg }| d }|D ]}z|  || W qj ty   Y qjw t	 D ]}||vr|| qt
t| }	i }
tdj}t	 D ].}||}|r|| |  }z|
|  W q ty   td| tjj|
|< Y qw q|D ]}|d t|	 v rt| ||d  |< d| vrnd| v r
d| d v sn|r[|d  }t|| 	 D ]>}|dkr-|| | dkr-q|| vr@|| | | |< q|dkrX|| | D ]}t| ||< qKqn|| d v rntdt|| d f  d| v rd| d v r| d d }z
tt|i |	}W n
 ty   Y nw || d d< d| v rd| d v r؈| d d }z
tt|i |	}W n
 ty   Y nw || d d< i }d| v rQ| d }|  g | d< d\}}}}}|D ]K}|dd dkr|dd  dd }na|dd dkr)|dd  dd }nK|dd dkr?|dd  dd }n5|dd  d!krU|d d  dd }n|dd" d#krk|d"d  dd }n	t| ||< |rd| vrg | d< d$d% t|d&D D ]}|d'd}|| d vr| d | qd}|r|d(d)}|d*d+}d#| vr|g| d#< n	| d# | d}|durd| vrg | d< td,d% t|d&D D ]}|| d vr| d | qd}|durEd!| vr!g | d!< d-d% t|d&D D ]}|| d! vrA| d! | q-d}q|rQd| vrQg | d< td.d% t|d&D D ]}zt||	}W n tt tfy   td/|d+ Y nw |d0krd0nd1}||kr|g}nt|d0d2}t!|d3krd1|v rd1g}d1}t!|dkr|d |krd4|d g}t!|d3krFt"t#j$j%|\}}|| d }|j&t#j'j(d5}i }| d D ]Z}t#)|} |*| r@z|+| \}}!||!fd6d7}"t|, }#|#-|!,  W n t.y, }$ zd}"t|, }#W Y d}$~$nd}$~$ww tfd8d|#D }%|"t|%f||< q|||< | d | qed!| vr(d| v r(|| d v r(| dg }&g }'t/t0t1t2| }(t3| rt4| d D ]:\})}||  du rn|(rl 5 D ]\}\}*}+ fd9d:t },||, ||&v sd;| v sd| v rȐq|*dur||,vrd<}-|*t#)d=| d>|) d?}.|.j&t#j'j(d5}.|.| d;< |g|+ | d< d!| vrd=| d>|) d@| g| d!< n4dA}-d| vr g | d< dB| d vr2| d dB |&| |'d=| d>|) d@|  | dg }/dC|/v sadD|/v sa|/|-r^dDndC |/rj|/| d< q dur 5 D ]K\}\}*}+| dg }%| dg D ]}0|06drd7|0 }0|%8|0dEd dF q|%rtt|%| d< ||%vr|&| quqnNt9| rd| v rd1| d v rt:| d d1 |	}1|1| d d1< n#d| d v rt:| d d |	}1| d d= |1| d d1< |'r|'| d!< |&r(tt|&| d< d;| v rd| vr<g | d< dC| d vrWdD| d vrW| d dC d| vrg | d< t|
5 D ]\}}|| d; r| d | qj| d s| d= t;| rt<| d; |	| d;< qt	 D ]}|| d krd#| v r| d# | d#< | d dkrdG| v r| dG v rt=| | dG  |< dH| v r| dH }2|2dId}3|2|3k }4|3dJd}2|2|3k }5t>d |2}|rt?|@dK|@dL\}6}7}}8tA|6|7\}9}:};|6| d< z| dG r5|6| dG  d< W n
 ty@   Y nw |9rfd|9v r`zt|9d i |	|9d< W n
 ty_   Y nw |9| d< |:ro|:| d< |;rx|;| dM< |4rt| dI|< |5rt| dJ|< qtdNt| dH   q| d dOvrbdP| v rt| d | dP  }<nt| d }<t	 D ]}t/tBtC| r|<| qdQ| v r|<8t| dQ 	  t| dQ 	 D ]}| dQ | D ]}||<vr|<| qq| d dkr!dG| v r|<| dG  n|<| d  | d dRv r@| d }=|=v r@d|= v r@|= d | d< | d dSkrP|<8t	  t	 D ]}||<vr`|= qVS )TzH
    Sets correct dimension information for each variable/parameter
    r$  r%  r   rk   r	   r]  c                 s   s    | ]}|d  V  qdS )rk   Nr%   rE  r%   r%   r&   r  :
  r  zanalyzevars.<locals>.<genexpr>r#  r  r)  z[A-Za-z][\w$]*z.*\b%s\br   r0   r   	undefinedzCanalyzevars: typespec of variable %s is not defined in routine %s.
r_  rT   r^  r'  )NNNNNNr  r   r   r
   r   r  rd  r   rc  r  rb  c                 S   rt  r%   r  r  r%   r%   r&   rs   
  rt   zanalyzevars.<locals>.<listcomp>r  r   z\n\nz

z\n r   c                 S   rt  r%   r  r  r%   r%   r&   rs   
  rt   c                 S   rt  r%   r  r  r%   r%   r&   rs   
  rt   c                 S   rt  r%   r  r  r%   r%   r&   rs   
  rt   z4analyzevars: could not parse dimension for variable :r   z@:@r&  1)languagec                 S   s   | | | S r(   r%   )r  r   rF  r%   r%   r&   solve_v
  s   zanalyzevars.<locals>.solve_vc                 3   s     | ]}|j  v r|j V  qd S r(   )r  r  r  r%   r&   r  
  s    
c                    s:     | d g gd D ]}||vr|| || q
d S )Nr   )ro  add)r  r  v1)coeffs_and_depscompute_depsr%   r&   r    s   

z!analyzevars.<locals>.compute_depsr`  Fzshape(r  rV  z) == Tinr   r   r  r  r   r  pure	recursiver*  r  ra  z'analyzevars: prefix (%s) were not used
)r  rl  r  r  rd  r  )r   r   rd   )Dr2  rs  r  r  rg  ro  r  KeyErrorre  rf  r  r;  r   r   r   r{  r   r   r   r.   r   r   r  r   reverser   r  r  r   rw   param_parser   r  rT   r  r   ExprparsetostringLanguager   	as_symbolr  linear_solvesymbolsr5  RuntimeErrorl_orisintent_inisintent_inoutisintent_inplaceisarrayr  r)  r   r   r  r~  r  isscalarr  rn  r@  r  r   r  isintent_callbackisintent_aux)>r%  rq  rr  genr   rm  svarsr)  r   ru  dep_matches
name_matchr  r   ln0r   dimension_exprsr  dimr  rd  rc  rb  r   tmpr  dim_charr  r   d2dsizesolver_and_depsr  rF  r  all_symbolsr   v_depsn_depsn_checks
n_is_inputr  solverr  all_depsis_requiredr  v_attraar  prpr1ispureisrecr0   r  r  r  r  ra  
neededvarsrk   r%   )r  r  r$  r&   rS  *
  s  "

 


 


&









L














rS  z\A[a-z]+[\w$]*\Zc                 C   s  |du r.z	t | ||}W |S  ty- } z| }td| d| d W Y d}~|S d}~ww t|dk sA|ddt|d  dkrItd| d	|dd
 d}t|dkr|d d}t|dkrvt|d |}tdt|d }n"t|d |}t|d |}	tt|t|	d }ntd| d| 	dr| dd n| d} g }
| D ]-}zt |||}W n ty } ztd| d|d W Y d}~nd}~ww |

| qtt||
}|S )a  
    Creates a dictionary of indices and values for each parameter in a
    parameter array to be evaluated later.

    WARNING: It is not possible to initialize multidimensional array
    parameters e.g. dimension(-3:1, 4, 3:5) at this point. This is because in
    Fortran initialization through array constructor requires the RESHAPE
    intrinsic function. Since the right-hand side of the parameter declaration
    is not executed in f2py, but rather at the compiled c/fortran extension,
    later, it is not possible to execute a reshape of a parameter array.
    One issue remains: if the user wants to access the array parameter from
    python, we should either
    1) allow them to access the parameter array using python standard indexing
       (which is often incompatible with the original fortran indexing)
    2) allow the parameter array to be accessed in python as a dictionary with
       fortran indices as keys
    We are choosing 2 for now.
    Nzparam_eval: got "r  r   r&  r   rY  zparam_eval: dimension z can't be parsedr
   r  r   r  z.param_eval: multidimensional array parameters z not supportedz(/r   )r  r   r.   rT   r   r  r  r   r4   r   r  r  zip)r  r  ru  r  r  r   dimrangeboundlbounduboundv_evalitemr%   r%   r&   r    sH    &
 "r  c                 C   s   d| v r*| d|  d }| |  dd | d }tt||}t|| | S | |v r4t||  S |D ]+}td| d tj}|| }|ra|	dt||  |	d } || }|sJq6| S )	a  Recursively parse array dimensions.

    Parses the declaration of an array variable or parameter
    `dimension` keyword, and is called recursively if the
    dimension for this array is a previously defined parameter
    (found in `params`).

    Parameters
    ----------
    d : str
        Fortran expression describing the dimension of an array.
    params : dict
        Previously parsed parameters declared in the Fortran source file.

    Returns
    -------
    out : str
        Parsed dimension expression.

    Examples
    --------

    * If the line being analyzed is

      `integer, parameter, dimension(2) :: pa = (/ 3, 5 /)`

      then `d = 2` and we return immediately, with

    >>> d = '2'
    >>> param_parse(d, params)
    2

    * If the line being analyzed is

      `integer, parameter, dimension(pa) :: pb = (/1, 2, 3/)`

      then `d = 'pa'`; since `pa` is a previously parsed parameter,
      and `pa = 3`, we call `param_parse` recursively, to obtain

    >>> d = 'pa'
    >>> params = {'pa': 3}
    >>> param_parse(d, params)
    3

    * If the line being analyzed is

      `integer, parameter, dimension(pa(1)) :: pb = (/1, 2, 3/)`

      then `d = 'pa(1)'`; since `pa` is a previously parsed parameter,
      and `pa(1) = 3`, we call `param_parse` recursively, to obtain

    >>> d = 'pa(1)'
    >>> params = dict(pa={1: 3, 2: 5})
    >>> param_parse(d, params)
    3
    rT  Nr   rV  rv  rw  r  r  )
r  rfindr4   r  r   r   r   r   r   r   )r  ru  dnameddimsrW   r  rQ  r   r%   r%   r&   r    s,   9


r  c                 C   s  | }t |  }|r^t|\}}t| |d |}d}| D ]}	|	 }	|	tjtj vr,d}	||	 }q|d dkr<|d }n|d }|} | |d v sN| |d v r^| d } | |d v sN| |d v sN| |v r~d	}
| t|
 |v rx|
d	 }
| t|
 |v sl| t|
 } |r||d | < | S | |d vr||d v r|d | |d | < ni |d | < d
|v r||d
 |d  v rt	|d |  d|d | < | S )Nr$  e_r   r
   r  _er)  r   r   r'  r(  r   )
analyzeargs_re_1r   rs  r  r   r_   ascii_lowercasedigitsr   rg  )r   r%  r)  orig_a	a_is_exprrq  rr  atnar   rm  r%   r%   r&   	expr2nameB  sD   

	r  c                 C   s  t |  t| \}}d| vrg | d< g }| d D ]}t|| |}|| q|| d< d| v rLt| d  D ]\}}|D ]}|| d vrJi | d |< q<q6| d D ]!}|d |v rqd| vr`g | d< |d | d vrq| d |d  qPd| v r| d | d vri | d | d < | S )Nr)  r  r$  r#  rk   r'  r   )r2  rs  r  r  re  r)  )r%  rq  r   r)  r   rm  args1rF  r%   r%   r&   rQ  g  s4   rQ  z\A\(.+?,.+?\)\Zz\A[+-]?\d+(_(?P<name>\w+)|)\Zz*\A[+-]?[\d.]+[-\d+de.]*(_(?P<name>\w+)|)\Zz
\A\(.*\)\Zz\A(?P<name>\w+)\s*\(.*?\)\s*\Zc                 C   sP   t | tr	ddiS t | trddiS t | trddiS t | tr"| S tt| )Nr0   r3   r1   r  )r  r4   r6   r  r  AssertionErrorr   )r   r%   r%   r&   _ensure_exprdict  s   



r  c                 C   s  | |v r
t ||  S |  } t| rddiS t| }|r5d| v r1|dr1tdt|   ddiS t	| }|rSd| v rO|drOtdt|   ddiS dD ]%}dd	 t
| |d
d| d D D ]}||v ryt ||     S qiqUi }t| rt| dd ||}n.t| }|r|d}t|d||}|rd|v r|d= |s|d |v rt ||d  S | d dv rdddidS |stdt|   |S )Nr0   r  rk   z:determineexprtype: selected kind types not supported (%s)
r3   r1   )+r  r   r  c                 S   rt  r%   r  r  r%   r%   r&   rs     rt   z%determineexprtype.<locals>.<listcomp>r  rZ  r   r
   r]  r   r  r  r   )r0   r_  z>determineexprtype: could not determine expressions (%s) type.
)r  r   determineexprtype_re_1r   determineexprtype_re_2r  r   r.   r   determineexprtype_re_3r  r  determineexprtype_re_4r  determineexprtype_re_5)r  r$  rulesr   opr  r  rnr%   r%   r&   r    sX   




(



r  r   Fc                 C   s  t |  d}t| tr3| D ]#}|r'|d dv r'|d tv rqtr'|d tvr'q|t|||d }q|S d}d}d}| d }|dkrCdS g }	d| v rM| d }d| v r|| d }
| d D ]}t|| |	}t|
| sl|	| qY| d d	ksu|	r|d
d	|	 }d}d| v rt| d 
 D ]}d||t || d | f }q| dg d d  }|d	krd|v r|d |rd||t d	||f }d}d| v rt| d |t }d}d| v rt| d |t }|dkrd}d}d| v rd| d  }| d |	vr|	| d  t| d |t |d}t| | d |	|t |d}
d}d| v r&|s&d| d  }d| v rLd}t| d  D ]\}}d||t |d	|f }q5|| }|dkrX|dkrXd}d||||||||||
|||||f }|S )Nr	   r%  r  rk   ri  r  r)  r$  r   z(%s)r  r  z	%s%s%s %sr  callbackz%s%sintent(%s) %sr
  r	  r  r   z result (%s)r#  r  z! in %sr  z%s%sentry %s(%s)r  r  z%%s%s%s %s%s%s %s%s%s%s%s%s%send %s %s)r2  r  re  r!   r"   rm  r  r  r  r   rf  r   ro  r  use2fortrancommon2fortranvars2fortranr)  )r%  r>  rj  rG  rA  r  rk   r)  	blocktypeargslr$  r   r  rm  
intent_lstr
  r	  r   r#  messentry_stmtsr  r%   r%   r&   rm    s   




rm  c              	   C   sV   d}t |  D ] }|dkrd||d| | f }qd|||d| | f }q|S )Nr	   r  z%s%scommon %sr  z%s%scommon /%s/ %s)re  rf  r   )r	  r>  rG  rm  r%   r%   r&   r!    s   r!  c                 C   s  d}t |  D ]{}d|||f }| | i kr&|r%|d dkr%|d d }qd| | v r6| | d r6d| }d| | v ru| | d rud}t | | d  D ]&}|| | d | krdd	|||f }d}qNd
|||| | d | f }d}qN|r|d dkr|d d }q|S )Nr	   z%s%suse %s,r
   r  r  z%s only:r  r   %s%s%sz
%s%s%s=>%sr-  )r
  r>  rG  r   r   rm  r%   r%   r&   r     s*   r   c              	   C   sR   | d }g }|D ]}z	t  d|  }W n	 ty   Y qw || r&|| q|S )Nr  zisintent_%s)globalsr  r  )rH  r  rG  r  rX  r%   r%   r&   true_intent_list/  s   
r*  c              	   C   s  t |  d}g }|D ]}|| d v r|| q
d| v r7| d D ]}||v r0||vr/|| q td|  q d| v rB|| d  |sVt| D ]}||vrU|| qJ|D ],}d|| v r|| d D ]}||v rd|| v r||| d v rtd||f  qgd| v r|| d v rt|| rd	|||f }d
|||f }t|| rd|||f }||v rd|| vrqXd}	| d D ]}
||
d kr|
d dkrd}	 nq|	rqX||vrt| t	d|  qX|| d kr| d dks| 
drqXd|| vr(d|| v rd|| d v r||v rd
|||f }qXt||  t	d|  qX|| d }|dkrDd|| v rDd||| d f }i }d|| v rT|| d }nd|| v ra|| d }d|v r|d dv rvd||d f }n6d ||d f }n-d!|v rd"||d! f }d#|v rd$||d# f }nd%| }nd#|v rd&||d# f }d'}d|| v rd(d) || d D }|rd*|v rd+|v r|d+ |rd,|d-|f }d-}d.|| v rd/||d-|| d. f }d-}d0|| v rt|| }|rd1||d-|f }d-}d2|| v r*d3||d-|| d2 f }d-}d|| v rAd4||d-|| d f }d-}d5|| v rx|| d5 }|| d d6v rpzt|}d7|j|jf }W n
 tyo   Y nw d8|||f }nd9||f }d:|||f }qX|S );Nr	   r$  rd  z7vars2fortran: Confused?!: "%s" is not defined in vars.
r  rd  zHvars2fortran: Warning: cross-dependence between variables "%s" and "%s"
r'  z%s%sintent(callback) %sz%s%sexternal %sz%s%soptional %sr0   r   r#  rk   r%  r   r   z/vars2fortran: No definition for argument "%s".
r   r]  r   z-vars2fortran: No typespec for argument "%s".
rd   ra  z%s(%s)r^  r_  r   )r   r  z%s*(%s)z%s*%srT   z	%s(len=%sr'  z%s,kind=%s)z%s)z%s(kind=%s)r   c                 S   s   g | ]}|d vr|qS ))r   r%   )rq   r   r%   r%   r&   rs     s    z vars2fortran.<locals>.<listcomp>z
intent(in)zintent(out)z%s, %sr  r   z%s%sdimension(%s)r  z%s%sintent(%s)rc  z%s%scheck(%s)z%s%sdepend(%s)r`  )r  r  z(%s,%s)z%s :: %s=%sz%s :: %sr(  )r2  r  ri   r  re  rf  r  
isoptionalshowr.   ro  r  r   r*  r  r1   imagr   )r%  r$  r)  r>  rj  rG  noutr   r  r   rF  vardefr  r   r  r  r  r%   r%   r&   r"  =  s   



$
 






r"  c                 C   sz   t dd t| t t dd g attd }t dd tD ]}t d|j dd t||}qt dd t	|}t| S )NzReading fortran codes...
r   zPost-processing...
z"Applying post-processing hooks...
z  r   zPost-processing (stage 2)...
)
r.   r   r-  r   rP  r   post_processing_hooks__name__traverser@  )filespostlisthookr%   r%   r&   crackfortran  s   




r6  c                 C   s$   t | d }d}dt }|| | S )Nr   zE!    -*- f90 -*-
! Note: the context of this file is case sensitive.
z
! This file was auto-generated with f2py (version:%s).
! See:
! https://web.archive.org/web/20140822061353/http://cens.ioc.ee/projects/f2py2e
)rm  f2py_version)r%  pyfheaderfooterr%   r%   r&   crack2fortran  s   r;  c                 C   s(   t | tot| dkot | d ttfS )Nr&  r   )r  tuplerT   r4   r   )objr%   r%   r&   _is_visit_pair  s
   

r>  c                 O   s<  t | r,| d dkr| S || ||g|R i |}|dur%t |s#J |S | }| \}} nd| f}d}t| trbg }t| D ]#\}	}
t|	|
f|g|R ||g |d|\}}|dur`|| q=n2t| trt }|  D ]"\}}
t||
f|g|R ||g |d|\}}|dur|||< qnn| }|du r|S ||fS )a  Traverse f2py data structure with the following visit function:

    def visit(item, parents, result, *args, **kwargs):
        """

        parents is a list of key-"f2py data structure" pairs from which
        items are taken from.

        result is a f2py data structure that is filled with the
        return value of the visit function.

        item is 2-tuple (index, value) if parents[-1][1] is a list
        item is 2-tuple (key, value) if parents[-1][1] is a dict

        The return value of visit must be None, or of the same kind as
        item, that is, if parents[-1] is a list, the return value must
        be 2-tuple (new_index, new_value), or if parents[-1] is a
        dict, the return value must be 2-tuple (new_key, new_value).

        If new_index or new_value is None, the return value of visit
        is ignored, that is, it will not be added to the result.

        If the return value is None, the content of obj will be
        traversed, otherwise not.
        """
    r   r3  N)parentsr   )r>  r  re  r  r2  r  r  r)  )r=  visitr?  r   r)  kwargs
new_resultparent
result_keyrW   r  	new_indexnew_itemrg  new_key	new_valuer%   r%   r&   r2    sZ   





r2  c              
   O   s:  |d \}}| \}}dd }	|dv r#|d d dksJ |d d }
n|d	kr8|d
 d dks1J |d
 d }
nd}
d}|
durU|}|
  D ]\}}t|rS|	||}qFn(|dkr}|d
 d d }
|}|
  D ]\}}t|r|td| d d| |}qg|dur||krtd| d| d| d| d	d ||fS dS )a  Previously, Fortran character was incorrectly treated as
    character*1. This hook fixes the usage of the corresponding
    variables in `check`, `dimension`, `=`, and `callstatement`
    expressions.

    The usage of `char*` in `callprotoargument` expression can be left
    unchanged because C `character` is C typedef of `char`, although,
    new implementations should use `character*` in the corresponding
    expressions.

    See https://github.com/numpy/numpy/pull/19388 for more information.

    r
   c                 S   s0   t d|  d | |}t d|  d | |}|S )Nz[*]\s*\bru  z\b\s*[\[]\s*0\s*[\]])r   r  )varnamer  r%   r%   r&   	fix_usage=  s
   z8character_backward_compatibility_hook.<locals>.fix_usage)r   rc  r   r$  r   r`  r   Ncallstatementz
(?<![&])\bru  r   zcharacter_bc_hook[r  z]: replaced `z` -> `z`
)r)  ischaracterr   r  r.   )r  r?  r   r)  rA  
parent_keyparent_valuerg  r  rJ  	vars_dictrH  rI  vdr%   r%   r&   %character_backward_compatibility_hook+  sL   
rR  __main__r  z-quietz-verboser&  z-fixz?Use option -f90 before -fix if Fortran 90 code is in fix form.
z-skipemptyendsz--ignore-containsz-f77z-f90r   z-hz-showz-mr  zUnknown option %s
z	OSError: a    Warning: You have specified module name for non Fortran 77 code that
  should not need one (expect if you are scanning F90 code for non
  module blocks but then you should use flag -skipemptyends and also
  be sure that the files do not contain programs without program
  statement).
z Writing fortran code to file %s
rb  )r   )r   )r  )r0  r(   )r	   N)Nr	   )r	   )NN)r   r   )r   F)r	   F)__doc__r)   r_   r   r   r   r  r  r   pathlibr   r   ImportErrorr	   r   auxfuncsr   versionr7  r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r/  r   r   r.  r#   r   r"   r$   r   r!   r    r   r'   r.   	_MAXCACHErp  r   rh   ry   r   rl   rw   rz   r{   r   r   rz  r   r   r   r   r   r   r   r   r   r,  r   beforethisafterfortrantypesr@  r  r=  r>  groupbegins77r   groupbegins90r   	groupendsr;  endifsr:  moduleproceduresrF  r?  r0  r1  r3  r4  r7  r8  r9  r2  r5  r6  rB  rE  rI  rA  rC  rD  r<  Sr+  r,  r   r!  rG  crackline_bind_1r  r-  rH  r  r\  rn  r  rv  r  r  r  r  r  rp  rr  ry  r~  r  rJ  r  r  r  r^  r_  r*  r  r  r  r  r  rg  rh  ri  r1  r2  r4  r;  r@  rP  rT  rR  rU  rs  rt  rx  r}  r  r  r  r  r  r  r  r  r  r  r  rS  r  r  r  r  rQ  r  r  r  r  r  r  r  rm  r!  r   r*  r"  r0  r6  r;  r>  r2  rR  r  r1  r3  funcsrX  f2f3showblocklistargvr   ri   r   r   r   OSErrordetailr4  r8  r+   r%   r%   r%   r&   <module>   sZ    &
	 c





















  

    W
% *<		 `"+-He   
>P%-K
 B
<




 H